book.tex 538 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  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.bib}
  57. \begin{document}
  58. \frontmatter
  59. \HalfTitle{Essentials of Compilation}
  60. \halftitlepage
  61. %% \begin{seriespage}
  62. %% \seriestitle{Industrial Economics}
  63. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  64. %% \title{Engineering and Economics}
  65. %% \author{Samuel Endgrove}
  66. %% \title{Structural Economics: From Beginning to End}
  67. %% \author{Guang Xi}
  68. %% \end{seriespage}
  69. \Title{Essentials of Compilation}
  70. \Booksubtitle{The Incremental, Nano-Pass Approach}
  71. \edition{First Edition}
  72. \BookAuthor{Jeremy G. Siek}
  73. \imprint{The MIT Press\\
  74. Cambridge, Massachusetts\\
  75. London, England}
  76. \begin{copyrightpage}
  77. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  78. or personal downloading under the
  79. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  80. license.
  81. Copyright in this monograph has been licensed exclusively to The MIT
  82. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  83. version to the public in 2022. All inquiries regarding rights should
  84. be addressed to The MIT Press, Rights and Permissions Department.
  85. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  86. %% All rights reserved. No part of this book may be reproduced in any
  87. %% form by any electronic or mechanical means (including photocopying,
  88. %% recording, or information storage and retrieval) without permission in
  89. %% writing from the publisher.
  90. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  91. %% United States of America.
  92. %% Library of Congress Cataloging-in-Publication Data is available.
  93. %% ISBN:
  94. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  95. \end{copyrightpage}
  96. \dedication{This book is dedicated to the programming language wonks
  97. at Indiana University.}
  98. %% \begin{epigraphpage}
  99. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  100. %% \textit{Book Name if any}}
  101. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  102. %% \end{epigraphpage}
  103. \tableofcontents
  104. \listoffigures
  105. \listoftables
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \chapter*{Preface}
  108. \addcontentsline{toc}{fmbm}{Preface}
  109. There is a magical moment when a programmer presses the ``run'' button
  110. and the software begins to execute. Somehow a program written in a
  111. high-level language is running on a computer that is only capable of
  112. shuffling bits. Here we reveal the wizardry that makes that moment
  113. possible. Beginning with the groundbreaking work of Backus and
  114. colleagues in the 1950s, computer scientists discovered techniques for
  115. constructing programs, called \emph{compilers}, that automatically
  116. translate high-level programs into machine code.
  117. We take you on a journey by constructing your own compiler for a small
  118. but powerful language. Along the way we explain the essential
  119. concepts, algorithms, and data structures that underlie compilers. We
  120. develop your understanding of how programs are mapped onto computer
  121. hardware, which is helpful when reasoning about properties at the
  122. junction between hardware and software such as execution time,
  123. software errors, and security vulnerabilities. For those interested
  124. in pursuing compiler construction, our goal is to provide a
  125. stepping-stone to advanced topics such as just-in-time compilation,
  126. program analysis, and program optimization. For those interested in
  127. designing and implementing programming languages, we connect
  128. language design choices to their impact on the compiler and the generated
  129. code.
  130. A compiler is typically organized as a sequence of stages that
  131. progressively translates a program to code that runs on hardware. We
  132. take this approach to the extreme by partitioning our compiler into a
  133. large number of \emph{nanopasses}, each of which performs a single
  134. task. This allows us to test the output of each pass in isolation, and
  135. furthermore, allows us to focus our attention making the compiler far
  136. easier to understand.
  137. %% [TODO: easier to understand/debug for those maintaining the compiler,
  138. %% proving correctness]
  139. The most familiar approach to describing compilers is with one pass
  140. per chapter. The problem with that is it obfuscates how language
  141. features motivate design choices in a compiler. We take an
  142. \emph{incremental} approach in which we build a complete compiler in
  143. each chapter, starting with arithmetic and variables and add new
  144. features in subsequent chapters.
  145. Our choice of language features is designed to elicit the fundamental
  146. concepts and algorithms used in compilers.
  147. \begin{itemize}
  148. \item We begin with integer arithmetic and local variables in
  149. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  150. the fundamental tools of compiler construction: \emph{abstract
  151. syntax trees} and \emph{recursive functions}.
  152. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  153. \emph{graph coloring} to assign variables to machine registers.
  154. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  155. an elegant recursive algorithm for mapping expressions to
  156. \emph{control-flow graphs}.
  157. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  158. \emph{garbage collection}.
  159. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  160. but lack lexical scoping, similar to the C programming
  161. language~\citep{Kernighan:1988nx} except that we generate efficient
  162. tail calls. The reader learns about the procedure call stack,
  163. \emph{calling conventions}, and their interaction with register
  164. allocation and garbage collection.
  165. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  166. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  167. \emph{closure conversion}, in which lambdas are translated into a
  168. combination of functions and tuples.
  169. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  170. point the input languages are statically typed. The reader extends
  171. the statically typed language with an \code{Any} type which serves
  172. as a target for compiling the dynamically typed language.
  173. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  174. programming languages with the addition of loops and mutable
  175. variables. These additions elicit the need for \emph{dataflow
  176. analysis} in the register allocator.
  177. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  178. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  179. in which different regions of a program may be static or dynamically
  180. typed. The reader implements runtime support for \emph{proxies} that
  181. allow values to safely move between regions.
  182. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  183. leveraging the \code{Any} type and type casts developed in Chapters
  184. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  185. \end{itemize}
  186. There are many language features that we do not include. Our choices
  187. weigh the incidental complexity of a feature against the fundamental
  188. concepts that it exposes. For example, we include tuples and not
  189. records because they both elicit the study of heap allocation and
  190. garbage collection but records come with more incidental complexity.
  191. Since 2016 this book has served as the textbook for the compiler
  192. course at Indiana University, a 16-week course for upper-level
  193. undergraduates and first-year graduate students.
  194. %
  195. Prior to this course, students learn to program in both imperative and
  196. functional languages, study data structures and algorithms, and take
  197. discrete mathematics.
  198. %
  199. At the beginning of the course, students form groups of 2-4 people.
  200. The groups complete one chapter every two weeks, starting with
  201. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  202. chapters include a challenge problem that we assign to the graduate
  203. students. The last two weeks of the course involve a final project in
  204. which students design and implement a compiler extension of their
  205. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  206. \ref{ch:Rpoly} can be used in support of these projects or they can
  207. replace some of the earlier chapters. For example, a course with an
  208. emphasis on statically-typed imperative languages would skip
  209. Chapter~\ref{ch:Rdyn} in favor of
  210. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  211. the dependencies between chapters.
  212. This book has also been used in compiler courses at California
  213. Polytechnic State University, Rose–Hulman Institute of Technology, and
  214. University of Massachusetts Lowell.
  215. \begin{figure}[tp]
  216. \begin{tikzpicture}[baseline=(current bounding box.center)]
  217. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  218. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  219. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  220. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  221. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  222. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  223. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  224. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  225. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  226. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  227. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  228. \path[->] (C1) edge [above] node {} (C2);
  229. \path[->] (C2) edge [above] node {} (C3);
  230. \path[->] (C3) edge [above] node {} (C4);
  231. \path[->] (C4) edge [above] node {} (C5);
  232. \path[->] (C5) edge [above] node {} (C6);
  233. \path[->] (C6) edge [above] node {} (C7);
  234. \path[->] (C4) edge [above] node {} (C8);
  235. \path[->] (C4) edge [above] node {} (C9);
  236. \path[->] (C8) edge [above] node {} (C10);
  237. \path[->] (C10) edge [above] node {} (C11);
  238. \end{tikzpicture}
  239. \caption{Diagram of chapter dependencies.}
  240. \label{fig:chapter-dependences}
  241. \end{figure}
  242. We use the \href{https://racket-lang.org/}{Racket} language both for
  243. the implementation of the compiler and for the input language, so the
  244. reader should be proficient with Racket or Scheme. There are many
  245. excellent resources for learning Scheme and
  246. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  247. support code for this book is in the \code{github} repository at the
  248. following URL:
  249. \begin{center}\small
  250. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  251. \end{center}
  252. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  253. is helpful but not necessary for the reader to have taken a computer
  254. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  255. of x86-64 assembly language that are needed.
  256. %
  257. We follow the System V calling
  258. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  259. that we generate works with the runtime system (written in C) when it
  260. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  261. operating systems.
  262. %
  263. On the Windows operating system, \code{gcc} uses the Microsoft x64
  264. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  265. assembly code that we generate does \emph{not} work with the runtime
  266. system on Windows. One workaround is to use a virtual machine with
  267. Linux as the guest operating system.
  268. \section*{Acknowledgments}
  269. The tradition of compiler construction at Indiana University goes back
  270. to research and courses on programming languages by Daniel Friedman in
  271. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  272. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  273. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  274. the compiler course and continued the development of Chez Scheme.
  275. %
  276. The compiler course evolved to incorporate novel pedagogical ideas
  277. while also including elements of efficient real-world compilers. One
  278. of Friedman's ideas was to split the compiler into many small
  279. passes. Another idea, called ``the game'', was to test the code
  280. generated by each pass using interpreters.
  281. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  282. developed infrastructure to support this approach and evolved the
  283. course to use even smaller
  284. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  285. design decisions in this book are inspired by the assignment
  286. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  287. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  288. organization of the course made it difficult for students to
  289. understand the rationale for the compiler design. Ghuloum proposed the
  290. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  291. on.
  292. We thank the many students who served as teaching assistants for the
  293. compiler course at IU and made suggestions for improving the book
  294. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  295. thank Andre Kuhlenschmidt for his work on the garbage collector,
  296. Michael Vollmer for his work on efficient tail calls, and Michael
  297. Vitousek for his help running the first offering of the incremental
  298. compiler course at IU.
  299. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  300. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  301. for teaching courses based on early drafts of this book and for their
  302. invaluable feedback.
  303. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  304. course in the early 2000's and especially for finding the bug that
  305. sent the garbage collector on a wild goose chase!
  306. \mbox{}\\
  307. \noindent Jeremy G. Siek \\
  308. Bloomington, Indiana
  309. \mainmatter
  310. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  311. \chapter{Preliminaries}
  312. \label{ch:trees-recur}
  313. In this chapter we review the basic tools that are needed to implement
  314. a compiler. Programs are typically input by a programmer as text,
  315. i.e., a sequence of characters. The program-as-text representation is
  316. called \emph{concrete syntax}. We use concrete syntax to concisely
  317. write down and talk about programs. Inside the compiler, we use
  318. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  319. that efficiently supports the operations that the compiler needs to
  320. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  321. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  322. from concrete syntax to abstract syntax is a process called
  323. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  324. implementation of parsing in this book. A parser is provided in the
  325. support code for translating from concrete to abstract syntax.
  326. ASTs can be represented in many different ways inside the compiler,
  327. depending on the programming language used to write the compiler.
  328. %
  329. We use Racket's
  330. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  331. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  332. define the abstract syntax of programming languages
  333. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  334. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  335. recursive functions to construct and deconstruct ASTs
  336. (Section~\ref{sec:recursion}). This chapter provides an brief
  337. introduction to these ideas. \index{subject}{struct}
  338. \section{Abstract Syntax Trees and Racket Structures}
  339. \label{sec:ast}
  340. Compilers use abstract syntax trees to represent programs because they
  341. often need to ask questions like: for a given part of a program, what
  342. kind of language feature is it? What are its sub-parts? Consider the
  343. program on the left and its AST on the right. This program is an
  344. addition operation and it has two sub-parts, a read operation and a
  345. negation. The negation has another sub-part, the integer constant
  346. \code{8}. By using a tree to represent the program, we can easily
  347. follow the links to go from one part of a program to its sub-parts.
  348. \begin{center}
  349. \begin{minipage}{0.4\textwidth}
  350. \begin{lstlisting}
  351. (+ (read) (- 8))
  352. \end{lstlisting}
  353. \end{minipage}
  354. \begin{minipage}{0.4\textwidth}
  355. \begin{equation}
  356. \begin{tikzpicture}
  357. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  358. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  359. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  360. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  361. \draw[->] (plus) to (read);
  362. \draw[->] (plus) to (minus);
  363. \draw[->] (minus) to (8);
  364. \end{tikzpicture}
  365. \label{eq:arith-prog}
  366. \end{equation}
  367. \end{minipage}
  368. \end{center}
  369. We use the standard terminology for trees to describe ASTs: each
  370. circle above is called a \emph{node}. The arrows connect a node to its
  371. \emph{children} (which are also nodes). The top-most node is the
  372. \emph{root}. Every node except for the root has a \emph{parent} (the
  373. node it is the child of). If a node has no children, it is a
  374. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  375. \index{subject}{node}
  376. \index{subject}{children}
  377. \index{subject}{root}
  378. \index{subject}{parent}
  379. \index{subject}{leaf}
  380. \index{subject}{internal node}
  381. %% Recall that an \emph{symbolic expression} (S-expression) is either
  382. %% \begin{enumerate}
  383. %% \item an atom, or
  384. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  385. %% where $e_1$ and $e_2$ are each an S-expression.
  386. %% \end{enumerate}
  387. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  388. %% null value \code{'()}, etc. We can create an S-expression in Racket
  389. %% simply by writing a backquote (called a quasi-quote in Racket)
  390. %% followed by the textual representation of the S-expression. It is
  391. %% quite common to use S-expressions to represent a list, such as $a, b
  392. %% ,c$ in the following way:
  393. %% \begin{lstlisting}
  394. %% `(a . (b . (c . ())))
  395. %% \end{lstlisting}
  396. %% Each element of the list is in the first slot of a pair, and the
  397. %% second slot is either the rest of the list or the null value, to mark
  398. %% the end of the list. Such lists are so common that Racket provides
  399. %% special notation for them that removes the need for the periods
  400. %% and so many parenthesis:
  401. %% \begin{lstlisting}
  402. %% `(a b c)
  403. %% \end{lstlisting}
  404. %% The following expression creates an S-expression that represents AST
  405. %% \eqref{eq:arith-prog}.
  406. %% \begin{lstlisting}
  407. %% `(+ (read) (- 8))
  408. %% \end{lstlisting}
  409. %% When using S-expressions to represent ASTs, the convention is to
  410. %% represent each AST node as a list and to put the operation symbol at
  411. %% the front of the list. The rest of the list contains the children. So
  412. %% in the above case, the root AST node has operation \code{`+} and its
  413. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  414. %% diagram \eqref{eq:arith-prog}.
  415. %% To build larger S-expressions one often needs to splice together
  416. %% several smaller S-expressions. Racket provides the comma operator to
  417. %% splice an S-expression into a larger one. For example, instead of
  418. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  419. %% we could have first created an S-expression for AST
  420. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  421. %% S-expression.
  422. %% \begin{lstlisting}
  423. %% (define ast1.4 `(- 8))
  424. %% (define ast1.1 `(+ (read) ,ast1.4))
  425. %% \end{lstlisting}
  426. %% In general, the Racket expression that follows the comma (splice)
  427. %% can be any expression that produces an S-expression.
  428. We define a Racket \code{struct} for each kind of node. For this
  429. chapter we require just two kinds of nodes: one for integer constants
  430. and one for primitive operations. The following is the \code{struct}
  431. definition for integer constants.
  432. \begin{lstlisting}
  433. (struct Int (value))
  434. \end{lstlisting}
  435. An integer node includes just one thing: the integer value.
  436. To create an AST node for the integer $8$, we write \code{(Int 8)}.
  437. \begin{lstlisting}
  438. (define eight (Int 8))
  439. \end{lstlisting}
  440. We say that the value created by \code{(Int 8)} is an
  441. \emph{instance} of the \code{Int} structure.
  442. The following is the \code{struct} definition for primitive operations.
  443. \begin{lstlisting}
  444. (struct Prim (op args))
  445. \end{lstlisting}
  446. A primitive operation node includes an operator symbol \code{op}
  447. and a list of child \code{args}. For example, to create
  448. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  449. \begin{lstlisting}
  450. (define neg-eight (Prim '- (list eight)))
  451. \end{lstlisting}
  452. Primitive operations may have zero or more children. The \code{read}
  453. operator has zero children:
  454. \begin{lstlisting}
  455. (define rd (Prim 'read '()))
  456. \end{lstlisting}
  457. whereas the addition operator has two children:
  458. \begin{lstlisting}
  459. (define ast1.1 (Prim '+ (list rd neg-eight)))
  460. \end{lstlisting}
  461. We have made a design choice regarding the \code{Prim} structure.
  462. Instead of using one structure for many different operations
  463. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  464. structure for each operation, as follows.
  465. \begin{lstlisting}
  466. (struct Read ())
  467. (struct Add (left right))
  468. (struct Neg (value))
  469. \end{lstlisting}
  470. The reason we choose to use just one structure is that in many parts
  471. of the compiler the code for the different primitive operators is the
  472. same, so we might as well just write that code once, which is enabled
  473. by using a single structure.
  474. When compiling a program such as \eqref{eq:arith-prog}, we need to
  475. know that the operation associated with the root node is addition and
  476. we need to be able to access its two children. Racket provides pattern
  477. matching to support these kinds of queries, as we see in
  478. Section~\ref{sec:pattern-matching}.
  479. In this book, we often write down the concrete syntax of a program
  480. even when we really have in mind the AST because the concrete syntax
  481. is more concise. We recommend that, in your mind, you always think of
  482. programs as abstract syntax trees.
  483. \section{Grammars}
  484. \label{sec:grammar}
  485. \index{subject}{integer}
  486. \index{subject}{literal}
  487. \index{subject}{constant}
  488. A programming language can be thought of as a \emph{set} of programs.
  489. The set is typically infinite (one can always create larger and larger
  490. programs), so one cannot simply describe a language by listing all of
  491. the programs in the language. Instead we write down a set of rules, a
  492. \emph{grammar}, for building programs. Grammars are often used to
  493. define the concrete syntax of a language, but they can also be used to
  494. describe the abstract syntax. We write our rules in a variant of
  495. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  496. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  497. As an example, we describe a small language, named \LangInt{}, that consists of
  498. integers and arithmetic operations.
  499. \index{subject}{grammar}
  500. The first grammar rule for the abstract syntax of \LangInt{} says that an
  501. instance of the \code{Int} structure is an expression:
  502. \begin{equation}
  503. \Exp ::= \INT{\Int} \label{eq:arith-int}
  504. \end{equation}
  505. %
  506. Each rule has a left-hand-side and a right-hand-side. The way to read
  507. a rule is that if you have an AST node that matches the
  508. right-hand-side, then you can categorize it according to the
  509. left-hand-side.
  510. %
  511. A name such as $\Exp$ that is defined by the grammar rules is a
  512. \emph{non-terminal}. \index{subject}{non-terminal}
  513. %
  514. The name $\Int$ is also a non-terminal, but instead of defining it
  515. with a grammar rule, we define it with the following explanation. We
  516. make the simplifying design decision that all of the languages in this
  517. book only handle machine-representable integers. On most modern
  518. machines this corresponds to integers represented with 64-bits, i.e.,
  519. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  520. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  521. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  522. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  523. that the sequence of decimals represent an integer in range $-2^{62}$
  524. to $2^{62}-1$.
  525. The second grammar rule is the \texttt{read} operation that receives
  526. an input integer from the user of the program.
  527. \begin{equation}
  528. \Exp ::= \READ{} \label{eq:arith-read}
  529. \end{equation}
  530. The third rule says that, given an $\Exp$ node, the negation of that
  531. node is also an $\Exp$.
  532. \begin{equation}
  533. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  534. \end{equation}
  535. Symbols in typewriter font such as \key{-} and \key{read} are
  536. \emph{terminal} symbols and must literally appear in the program for
  537. the rule to be applicable.
  538. \index{subject}{terminal}
  539. We can apply these rules to categorize the ASTs that are in the
  540. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  541. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  542. following AST is an $\Exp$.
  543. \begin{center}
  544. \begin{minipage}{0.4\textwidth}
  545. \begin{lstlisting}
  546. (Prim '- (list (Int 8)))
  547. \end{lstlisting}
  548. \end{minipage}
  549. \begin{minipage}{0.25\textwidth}
  550. \begin{equation}
  551. \begin{tikzpicture}
  552. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  553. \node[draw, circle] (8) at (0, -1.2) {$8$};
  554. \draw[->] (minus) to (8);
  555. \end{tikzpicture}
  556. \label{eq:arith-neg8}
  557. \end{equation}
  558. \end{minipage}
  559. \end{center}
  560. The next grammar rule is for addition expressions:
  561. \begin{equation}
  562. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  563. \end{equation}
  564. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  565. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  566. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  567. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  568. to show that
  569. \begin{lstlisting}
  570. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  571. \end{lstlisting}
  572. is an $\Exp$ in the \LangInt{} language.
  573. If you have an AST for which the above rules do not apply, then the
  574. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  575. is not in \LangInt{} because there are no rules for \code{+} with only one
  576. argument, nor for \key{-} with two arguments. Whenever we define a
  577. language with a grammar, the language only includes those programs
  578. that are justified by the rules.
  579. The last grammar rule for \LangInt{} states that there is a \code{Program}
  580. node to mark the top of the whole program:
  581. \[
  582. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  583. \]
  584. The \code{Program} structure is defined as follows
  585. \begin{lstlisting}
  586. (struct Program (info body))
  587. \end{lstlisting}
  588. where \code{body} is an expression. In later chapters, the \code{info}
  589. part will be used to store auxiliary information but for now it is
  590. just the empty list.
  591. It is common to have many grammar rules with the same left-hand side
  592. but different right-hand sides, such as the rules for $\Exp$ in the
  593. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  594. combine several right-hand-sides into a single rule.
  595. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  596. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  597. defined in Figure~\ref{fig:r0-concrete-syntax}.
  598. The \code{read-program} function provided in \code{utilities.rkt} of
  599. the support code reads a program in from a file (the sequence of
  600. characters in the concrete syntax of Racket) and parses it into an
  601. abstract syntax tree. See the description of \code{read-program} in
  602. Appendix~\ref{appendix:utilities} for more details.
  603. \begin{figure}[tp]
  604. \fbox{
  605. \begin{minipage}{0.96\textwidth}
  606. \[
  607. \begin{array}{rcl}
  608. \begin{array}{rcl}
  609. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  610. \LangInt{} &::=& \Exp
  611. \end{array}
  612. \end{array}
  613. \]
  614. \end{minipage}
  615. }
  616. \caption{The concrete syntax of \LangInt{}.}
  617. \label{fig:r0-concrete-syntax}
  618. \end{figure}
  619. \begin{figure}[tp]
  620. \fbox{
  621. \begin{minipage}{0.96\textwidth}
  622. \[
  623. \begin{array}{rcl}
  624. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  625. &\mid& \ADD{\Exp}{\Exp} \\
  626. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  627. \end{array}
  628. \]
  629. \end{minipage}
  630. }
  631. \caption{The abstract syntax of \LangInt{}.}
  632. \label{fig:r0-syntax}
  633. \end{figure}
  634. \section{Pattern Matching}
  635. \label{sec:pattern-matching}
  636. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  637. the parts of an AST node. Racket provides the \texttt{match} form to
  638. access the parts of a structure. Consider the following example and
  639. the output on the right. \index{subject}{match} \index{subject}{pattern matching}
  640. \begin{center}
  641. \begin{minipage}{0.5\textwidth}
  642. \begin{lstlisting}
  643. (match ast1.1
  644. [(Prim op (list child1 child2))
  645. (print op)])
  646. \end{lstlisting}
  647. \end{minipage}
  648. \vrule
  649. \begin{minipage}{0.25\textwidth}
  650. \begin{lstlisting}
  651. '+
  652. \end{lstlisting}
  653. \end{minipage}
  654. \end{center}
  655. In the above example, the \texttt{match} form takes an AST
  656. \eqref{eq:arith-prog} and binds its parts to the three pattern
  657. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  658. prints out the operator. In general, a match clause consists of a
  659. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  660. recursively defined to be either a pattern variable, a structure name
  661. followed by a pattern for each of the structure's arguments, or an
  662. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  663. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  664. and Chapter 9 of The Racket
  665. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  666. for a complete description of \code{match}.)
  667. %
  668. The body of a match clause may contain arbitrary Racket code. The
  669. pattern variables can be used in the scope of the body, such as
  670. \code{op} in \code{(print op)}.
  671. A \code{match} form may contain several clauses, as in the following
  672. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  673. the AST. The \code{match} proceeds through the clauses in order,
  674. checking whether the pattern can match the input AST. The body of the
  675. first clause that matches is executed. The output of \code{leaf?} for
  676. several ASTs is shown on the right.
  677. \begin{center}
  678. \begin{minipage}{0.6\textwidth}
  679. \begin{lstlisting}
  680. (define (leaf? arith)
  681. (match arith
  682. [(Int n) #t]
  683. [(Prim 'read '()) #t]
  684. [(Prim '- (list e1)) #f]
  685. [(Prim '+ (list e1 e2)) #f]))
  686. (leaf? (Prim 'read '()))
  687. (leaf? (Prim '- (list (Int 8))))
  688. (leaf? (Int 8))
  689. \end{lstlisting}
  690. \end{minipage}
  691. \vrule
  692. \begin{minipage}{0.25\textwidth}
  693. \begin{lstlisting}
  694. #t
  695. #f
  696. #t
  697. \end{lstlisting}
  698. \end{minipage}
  699. \end{center}
  700. When writing a \code{match}, we refer to the grammar definition to
  701. identify which non-terminal we are expecting to match against, then we
  702. make sure that 1) we have one clause for each alternative of that
  703. non-terminal and 2) that the pattern in each clause corresponds to the
  704. corresponding right-hand side of a grammar rule. For the \code{match}
  705. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  706. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  707. alternatives, so the \code{match} has 4 clauses. The pattern in each
  708. clause corresponds to the right-hand side of a grammar rule. For
  709. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  710. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  711. patterns, replace non-terminals such as $\Exp$ with pattern variables
  712. of your choice (e.g. \code{e1} and \code{e2}).
  713. \section{Recursive Functions}
  714. \label{sec:recursion}
  715. \index{subject}{recursive function}
  716. Programs are inherently recursive. For example, an \LangInt{} expression is
  717. often made of smaller expressions. Thus, the natural way to process an
  718. entire program is with a recursive function. As a first example of
  719. such a recursive function, we define \texttt{exp?} below, which takes
  720. an arbitrary value and determines whether or not it is an \LangInt{}
  721. expression.
  722. %
  723. We say that a function is defined by \emph{structural recursion} when
  724. it is defined using a sequence of match clauses that correspond to a
  725. grammar, and the body of each clause makes a recursive call on each
  726. child node.\footnote{This principle of structuring code according to
  727. the data definition is advocated in the book \emph{How to Design
  728. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  729. Below we also define a second function, named \code{Rint?}, that
  730. determines whether an AST is an \LangInt{} program. In general we can
  731. expect to write one recursive function to handle each non-terminal in
  732. a grammar.\index{subject}{structural recursion}
  733. %
  734. \begin{center}
  735. \begin{minipage}{0.7\textwidth}
  736. \begin{lstlisting}
  737. (define (exp? ast)
  738. (match ast
  739. [(Int n) #t]
  740. [(Prim 'read '()) #t]
  741. [(Prim '- (list e)) (exp? e)]
  742. [(Prim '+ (list e1 e2))
  743. (and (exp? e1) (exp? e2))]
  744. [else #f]))
  745. (define (Rint? ast)
  746. (match ast
  747. [(Program '() e) (exp? e)]
  748. [else #f]))
  749. (Rint? (Program '() ast1.1)
  750. (Rint? (Program '()
  751. (Prim '- (list (Prim 'read '())
  752. (Prim '+ (list (Num 8)))))))
  753. \end{lstlisting}
  754. \end{minipage}
  755. \vrule
  756. \begin{minipage}{0.25\textwidth}
  757. \begin{lstlisting}
  758. #t
  759. #f
  760. \end{lstlisting}
  761. \end{minipage}
  762. \end{center}
  763. You may be tempted to merge the two functions into one, like this:
  764. \begin{center}
  765. \begin{minipage}{0.5\textwidth}
  766. \begin{lstlisting}
  767. (define (Rint? ast)
  768. (match ast
  769. [(Int n) #t]
  770. [(Prim 'read '()) #t]
  771. [(Prim '- (list e)) (Rint? e)]
  772. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  773. [(Program '() e) (Rint? e)]
  774. [else #f]))
  775. \end{lstlisting}
  776. \end{minipage}
  777. \end{center}
  778. %
  779. Sometimes such a trick will save a few lines of code, especially when
  780. it comes to the \code{Program} wrapper. Yet this style is generally
  781. \emph{not} recommended because it can get you into trouble.
  782. %
  783. For example, the above function is subtly wrong:
  784. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  785. returns true when it should return false.
  786. \section{Interpreters}
  787. \label{sec:interp-Rint}
  788. \index{subject}{interpreter}
  789. In general, the intended behavior of a program is defined by the
  790. specification of the language. For example, the Scheme language is
  791. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  792. defined in its reference manual~\citep{plt-tr}. In this book we use
  793. interpreters to specify each language that we consider. An interpreter
  794. that is designated as the definition of a language is called a
  795. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  796. \index{subject}{definitional interpreter} We warm up by creating a definitional
  797. interpreter for the \LangInt{} language, which serves as a second example
  798. of structural recursion. The \texttt{interp-Rint} function is defined in
  799. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  800. input program followed by a call to the \lstinline{interp-exp} helper
  801. function, which in turn has one match clause per grammar rule for
  802. \LangInt{} expressions.
  803. \begin{figure}[tp]
  804. \begin{lstlisting}
  805. (define (interp-exp e)
  806. (match e
  807. [(Int n) n]
  808. [(Prim 'read '())
  809. (define r (read))
  810. (cond [(fixnum? r) r]
  811. [else (error 'interp-exp "read expected an integer" r)])]
  812. [(Prim '- (list e))
  813. (define v (interp-exp e))
  814. (fx- 0 v)]
  815. [(Prim '+ (list e1 e2))
  816. (define v1 (interp-exp e1))
  817. (define v2 (interp-exp e2))
  818. (fx+ v1 v2)]))
  819. (define (interp-Rint p)
  820. (match p
  821. [(Program '() e) (interp-exp e)]))
  822. \end{lstlisting}
  823. \caption{Interpreter for the \LangInt{} language.}
  824. \label{fig:interp-Rint}
  825. \end{figure}
  826. Let us consider the result of interpreting a few \LangInt{} programs. The
  827. following program adds two integers.
  828. \begin{lstlisting}
  829. (+ 10 32)
  830. \end{lstlisting}
  831. The result is \key{42}, the answer to life, the universe, and
  832. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  833. Galaxy} by Douglas Adams.}.
  834. %
  835. We wrote the above program in concrete syntax whereas the parsed
  836. abstract syntax is:
  837. \begin{lstlisting}
  838. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  839. \end{lstlisting}
  840. The next example demonstrates that expressions may be nested within
  841. each other, in this case nesting several additions and negations.
  842. \begin{lstlisting}
  843. (+ 10 (- (+ 12 20)))
  844. \end{lstlisting}
  845. What is the result of the above program?
  846. As mentioned previously, the \LangInt{} language does not support
  847. arbitrarily-large integers, but only $63$-bit integers, so we
  848. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  849. in Racket.
  850. Suppose
  851. \[
  852. n = 999999999999999999
  853. \]
  854. which indeed fits in $63$-bits. What happens when we run the
  855. following program in our interpreter?
  856. \begin{lstlisting}
  857. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  858. \end{lstlisting}
  859. It produces an error:
  860. \begin{lstlisting}
  861. fx+: result is not a fixnum
  862. \end{lstlisting}
  863. We establish the convention that if running the definitional
  864. interpreter on a program produces an error then the meaning of that
  865. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  866. error is a \code{trapped-error}. A compiler for the language is under
  867. no obligations regarding programs with unspecified behavior; it does
  868. not have to produce an executable, and if it does, that executable can
  869. do anything. On the other hand, if the error is a
  870. \code{trapped-error}, then the compiler must produce an executable and
  871. it is required to report that an error occurred. To signal an error,
  872. exit with a return code of \code{255}. The interpreters in chapters
  873. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  874. \code{trapped-error}.
  875. %% This convention applies to the languages defined in this
  876. %% book, as a way to simplify the student's task of implementing them,
  877. %% but this convention is not applicable to all programming languages.
  878. %%
  879. Moving on to the last feature of the \LangInt{} language, the \key{read}
  880. operation prompts the user of the program for an integer. Recall that
  881. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  882. \code{8}. So if we run
  883. \begin{lstlisting}
  884. (interp-Rint (Program '() ast1.1))
  885. \end{lstlisting}
  886. and if the input is \code{50}, the result is \code{42}.
  887. We include the \key{read} operation in \LangInt{} so a clever student
  888. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  889. during compilation to obtain the output and then generates the trivial
  890. code to produce the output. (Yes, a clever student did this in the
  891. first instance of this course.)
  892. The job of a compiler is to translate a program in one language into a
  893. program in another language so that the output program behaves the
  894. same way as the input program does. This idea is depicted in the
  895. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  896. $\mathcal{L}_2$, and a definitional interpreter for each language.
  897. Given a compiler that translates from language $\mathcal{L}_1$ to
  898. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  899. compiler must translate it into some program $P_2$ such that
  900. interpreting $P_1$ and $P_2$ on their respective interpreters with
  901. same input $i$ yields the same output $o$.
  902. \begin{equation} \label{eq:compile-correct}
  903. \begin{tikzpicture}[baseline=(current bounding box.center)]
  904. \node (p1) at (0, 0) {$P_1$};
  905. \node (p2) at (3, 0) {$P_2$};
  906. \node (o) at (3, -2.5) {$o$};
  907. \path[->] (p1) edge [above] node {compile} (p2);
  908. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  909. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  910. \end{tikzpicture}
  911. \end{equation}
  912. In the next section we see our first example of a compiler.
  913. \section{Example Compiler: a Partial Evaluator}
  914. \label{sec:partial-evaluation}
  915. In this section we consider a compiler that translates \LangInt{} programs
  916. into \LangInt{} programs that may be more efficient, that is, this compiler
  917. is an optimizer. This optimizer eagerly computes the parts of the
  918. program that do not depend on any inputs, a process known as
  919. \emph{partial evaluation}~\citep{Jones:1993uq}.
  920. \index{subject}{partial evaluation}
  921. For example, given the following program
  922. \begin{lstlisting}
  923. (+ (read) (- (+ 5 3)))
  924. \end{lstlisting}
  925. our compiler will translate it into the program
  926. \begin{lstlisting}
  927. (+ (read) -8)
  928. \end{lstlisting}
  929. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  930. evaluator for the \LangInt{} language. The output of the partial evaluator
  931. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  932. recursion over $\Exp$ is captured in the \code{pe-exp} function
  933. whereas the code for partially evaluating the negation and addition
  934. operations is factored into two separate helper functions:
  935. \code{pe-neg} and \code{pe-add}. The input to these helper
  936. functions is the output of partially evaluating the children.
  937. \begin{figure}[tp]
  938. \begin{lstlisting}
  939. (define (pe-neg r)
  940. (match r
  941. [(Int n) (Int (fx- 0 n))]
  942. [else (Prim '- (list r))]))
  943. (define (pe-add r1 r2)
  944. (match* (r1 r2)
  945. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  946. [(_ _) (Prim '+ (list r1 r2))]))
  947. (define (pe-exp e)
  948. (match e
  949. [(Int n) (Int n)]
  950. [(Prim 'read '()) (Prim 'read '())]
  951. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  952. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  953. (define (pe-Rint p)
  954. (match p
  955. [(Program '() e) (Program '() (pe-exp e))]))
  956. \end{lstlisting}
  957. \caption{A partial evaluator for \LangInt{}.}
  958. \label{fig:pe-arith}
  959. \end{figure}
  960. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  961. arguments are integers and if they are, perform the appropriate
  962. arithmetic. Otherwise, they create an AST node for the arithmetic
  963. operation.
  964. To gain some confidence that the partial evaluator is correct, we can
  965. test whether it produces programs that get the same result as the
  966. input programs. That is, we can test whether it satisfies Diagram
  967. \ref{eq:compile-correct}. The following code runs the partial
  968. evaluator on several examples and tests the output program. The
  969. \texttt{parse-program} and \texttt{assert} functions are defined in
  970. Appendix~\ref{appendix:utilities}.\\
  971. \begin{minipage}{1.0\textwidth}
  972. \begin{lstlisting}
  973. (define (test-pe p)
  974. (assert "testing pe-Rint"
  975. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  976. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  977. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  978. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  979. \end{lstlisting}
  980. \end{minipage}
  981. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  982. \chapter{Integers and Variables}
  983. \label{ch:Rvar}
  984. This chapter is about compiling a subset of Racket to x86-64 assembly
  985. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  986. integer arithmetic and local variable binding. We often refer to
  987. x86-64 simply as x86. The chapter begins with a description of the
  988. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  989. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  990. is large so we discuss only the instructions needed for compiling
  991. \LangVar{}. We introduce more x86 instructions in later chapters.
  992. After introducing \LangVar{} and x86, we reflect on their differences
  993. and come up with a plan to break down the translation from \LangVar{}
  994. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  995. rest of the sections in this chapter give detailed hints regarding
  996. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  997. We hope to give enough hints that the well-prepared reader, together
  998. with a few friends, can implement a compiler from \LangVar{} to x86 in
  999. a couple weeks. To give the reader a feeling for the scale of this
  1000. first compiler, the instructor solution for the \LangVar{} compiler is
  1001. approximately 500 lines of code.
  1002. \section{The \LangVar{} Language}
  1003. \label{sec:s0}
  1004. \index{subject}{variable}
  1005. The \LangVar{} language extends the \LangInt{} language with variable
  1006. definitions. The concrete syntax of the \LangVar{} language is defined by
  1007. the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the abstract
  1008. syntax is defined in Figure~\ref{fig:Rvar-syntax}. The non-terminal
  1009. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1010. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1011. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1012. \key{Program} struct to mark the top of the program.
  1013. %% The $\itm{info}$
  1014. %% field of the \key{Program} structure contains an \emph{association
  1015. %% list} (a list of key-value pairs) that is used to communicate
  1016. %% auxiliary data from one compiler pass the next.
  1017. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1018. exhibit several compilation techniques.
  1019. \begin{figure}[tp]
  1020. \centering
  1021. \fbox{
  1022. \begin{minipage}{0.96\textwidth}
  1023. \[
  1024. \begin{array}{rcl}
  1025. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1026. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1027. \LangVarM{} &::=& \Exp
  1028. \end{array}
  1029. \]
  1030. \end{minipage}
  1031. }
  1032. \caption{The concrete syntax of \LangVar{}.}
  1033. \label{fig:Rvar-concrete-syntax}
  1034. \end{figure}
  1035. \begin{figure}[tp]
  1036. \centering
  1037. \fbox{
  1038. \begin{minipage}{0.96\textwidth}
  1039. \[
  1040. \begin{array}{rcl}
  1041. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1042. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1043. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1044. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1045. \end{array}
  1046. \]
  1047. \end{minipage}
  1048. }
  1049. \caption{The abstract syntax of \LangVar{}.}
  1050. \label{fig:Rvar-syntax}
  1051. \end{figure}
  1052. Let us dive further into the syntax and semantics of the \LangVar{}
  1053. language. The \key{let} feature defines a variable for use within its
  1054. body and initializes the variable with the value of an expression.
  1055. The abstract syntax for \key{let} is defined in
  1056. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1057. \begin{lstlisting}
  1058. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1059. \end{lstlisting}
  1060. For example, the following program initializes \code{x} to $32$ and then
  1061. evaluates the body \code{(+ 10 x)}, producing $42$.
  1062. \begin{lstlisting}
  1063. (let ([x (+ 12 20)]) (+ 10 x))
  1064. \end{lstlisting}
  1065. When there are multiple \key{let}'s for the same variable, the closest
  1066. enclosing \key{let} is used. That is, variable definitions overshadow
  1067. prior definitions. Consider the following program with two \key{let}'s
  1068. that define variables named \code{x}. Can you figure out the result?
  1069. \begin{lstlisting}
  1070. (let ([x 32]) (+ (let ([x 10]) x) x))
  1071. \end{lstlisting}
  1072. For the purposes of depicting which variable uses correspond to which
  1073. definitions, the following shows the \code{x}'s annotated with
  1074. subscripts to distinguish them. Double check that your answer for the
  1075. above is the same as your answer for this annotated version of the
  1076. program.
  1077. \begin{lstlisting}
  1078. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1079. \end{lstlisting}
  1080. The initializing expression is always evaluated before the body of the
  1081. \key{let}, so in the following, the \key{read} for \code{x} is
  1082. performed before the \key{read} for \code{y}. Given the input
  1083. $52$ then $10$, the following produces $42$ (not $-42$).
  1084. \begin{lstlisting}
  1085. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1086. \end{lstlisting}
  1087. \subsection{Extensible Interpreters via Method Overriding}
  1088. \label{sec:extensible-interp}
  1089. To prepare for discussing the interpreter for \LangVar{}, we
  1090. explain why we to implement the interpreter using
  1091. object-oriented programming, that is, as a collection of methods
  1092. inside of a class. Throughout this book we define many interpreters,
  1093. one for each of the languages that we study. Because each language
  1094. builds on the prior one, there is a lot of commonality between these
  1095. interpreters. We want to write down those common parts just once
  1096. instead of many times. A naive approach would be to have, for example,
  1097. the interpreter for \LangIf{} handle all of the new features in that
  1098. language and then have a default case that dispatches to the
  1099. interpreter for \LangVar{}. The following code sketches this idea.
  1100. \begin{center}
  1101. \begin{minipage}{0.45\textwidth}
  1102. \begin{lstlisting}
  1103. (define (interp-Rvar e)
  1104. (match e
  1105. [(Prim '- (list e))
  1106. (fx- 0 (interp-Rvar e))]
  1107. ...))
  1108. \end{lstlisting}
  1109. \end{minipage}
  1110. \begin{minipage}{0.45\textwidth}
  1111. \begin{lstlisting}
  1112. (define (interp-Rif e)
  1113. (match e
  1114. [(If cnd thn els)
  1115. (match (interp-Rif cnd)
  1116. [#t (interp-Rif thn)]
  1117. [#f (interp-Rif els)])]
  1118. ...
  1119. [else (interp-Rvar e)]))
  1120. \end{lstlisting}
  1121. \end{minipage}
  1122. \end{center}
  1123. The problem with this approach is that it does not handle situations
  1124. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1125. feature, like the \code{-} operator, as in the following program.
  1126. \begin{lstlisting}
  1127. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1128. \end{lstlisting}
  1129. If we invoke \code{interp-Rif} on this program, it dispatches to
  1130. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1131. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1132. which is an \code{If}. But there is no case for \code{If} in
  1133. \code{interp-Rvar}, so we get an error!
  1134. To make our interpreters extensible we need something called
  1135. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1136. recursive knot is delayed to when the functions are
  1137. composed. Object-oriented languages provide open recursion with the
  1138. late-binding of overridden methods\index{subject}{method overriding}. The
  1139. following code sketches this idea for interpreting \LangVar{} and
  1140. \LangIf{} using the
  1141. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1142. \index{subject}{class} feature of Racket. We define one class for each
  1143. language and define a method for interpreting expressions inside each
  1144. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1145. and the method \code{interp-exp} in \LangIf{} overrides the
  1146. \code{interp-exp} in \LangVar{}. Note that the default case of
  1147. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1148. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1149. that dispatches to the \code{interp-exp} in \LangVar{}.
  1150. \begin{center}
  1151. \begin{minipage}{0.45\textwidth}
  1152. \begin{lstlisting}
  1153. (define interp-Rvar-class
  1154. (class object%
  1155. (define/public (interp-exp e)
  1156. (match e
  1157. [(Prim '- (list e))
  1158. (fx- 0 (interp-exp e))]
  1159. ...))
  1160. ...))
  1161. \end{lstlisting}
  1162. \end{minipage}
  1163. \begin{minipage}{0.45\textwidth}
  1164. \begin{lstlisting}
  1165. (define interp-Rif-class
  1166. (class interp-Rvar-class
  1167. (define/override (interp-exp e)
  1168. (match e
  1169. [(If cnd thn els)
  1170. (match (interp-exp cnd)
  1171. [#t (interp-exp thn)]
  1172. [#f (interp-exp els)])]
  1173. ...
  1174. [else (super interp-exp e)]))
  1175. ...
  1176. ))
  1177. \end{lstlisting}
  1178. \end{minipage}
  1179. \end{center}
  1180. Getting back to the troublesome example, repeated here:
  1181. \begin{lstlisting}
  1182. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1183. \end{lstlisting}
  1184. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1185. expression by creating an object of the \LangIf{} class and sending it the
  1186. \code{interp-exp} method with the argument \code{e0}.
  1187. \begin{lstlisting}
  1188. (send (new interp-Rif-class) interp-exp e0)
  1189. \end{lstlisting}
  1190. The default case of \code{interp-exp} in \LangIf{} handles it by
  1191. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1192. handles the \code{-} operator. But then for the recursive method call,
  1193. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1194. \code{If} is handled correctly. Thus, method overriding gives us the
  1195. open recursion that we need to implement our interpreters in an
  1196. extensible way.
  1197. \subsection{Definitional Interpreter for \LangVar{}}
  1198. \begin{figure}[tp]
  1199. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1200. \small
  1201. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1202. An \emph{association list} (alist) is a list of key-value pairs.
  1203. For example, we can map people to their ages with an alist.
  1204. \index{subject}{alist}\index{subject}{association list}
  1205. \begin{lstlisting}[basicstyle=\ttfamily]
  1206. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1207. \end{lstlisting}
  1208. The \emph{dictionary} interface is for mapping keys to values.
  1209. Every alist implements this interface. \index{subject}{dictionary} The package
  1210. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1211. provides many functions for working with dictionaries. Here
  1212. are a few of them:
  1213. \begin{description}
  1214. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1215. returns the value associated with the given $\itm{key}$.
  1216. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1217. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1218. but otherwise is the same as $\itm{dict}$.
  1219. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1220. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1221. of keys and values in $\itm{dict}$. For example, the following
  1222. creates a new alist in which the ages are incremented.
  1223. \end{description}
  1224. \vspace{-10pt}
  1225. \begin{lstlisting}[basicstyle=\ttfamily]
  1226. (for/list ([(k v) (in-dict ages)])
  1227. (cons k (add1 v)))
  1228. \end{lstlisting}
  1229. \end{tcolorbox}
  1230. %\end{wrapfigure}
  1231. \caption{Association lists implement the dictionary interface.}
  1232. \label{fig:alist}
  1233. \end{figure}
  1234. Having justified the use of classes and methods to implement
  1235. interpreters, we turn to the definitional interpreter for \LangVar{}
  1236. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1237. \LangInt{} but adds two new \key{match} cases for variables and
  1238. \key{let}. For \key{let} we need a way to communicate the value bound
  1239. to a variable to all the uses of the variable. To accomplish this, we
  1240. maintain a mapping from variables to values. Throughout the compiler
  1241. we often need to map variables to information about them. We refer to
  1242. these mappings as
  1243. \emph{environments}\index{subject}{environment}.\footnote{Another common term
  1244. for environment in the compiler literature is \emph{symbol
  1245. table}\index{subject}{symbol table}.}
  1246. %
  1247. For simplicity, we use an association list (alist) to represent the
  1248. environment. Figure~\ref{fig:alist} gives a brief introduction to
  1249. alists and the \code{racket/dict} package. The \code{interp-exp}
  1250. function takes the current environment, \code{env}, as an extra
  1251. parameter. When the interpreter encounters a variable, it finds the
  1252. corresponding value using the \code{dict-ref} function. When the
  1253. interpreter encounters a \key{Let}, it evaluates the initializing
  1254. expression, extends the environment with the result value bound to the
  1255. variable, using \code{dict-set}, then evaluates the body of the
  1256. \key{Let}.
  1257. \begin{figure}[tp]
  1258. \begin{lstlisting}
  1259. (define interp-Rvar-class
  1260. (class object%
  1261. (super-new)
  1262. (define/public ((interp-exp env) e)
  1263. (match e
  1264. [(Int n) n]
  1265. [(Prim 'read '())
  1266. (define r (read))
  1267. (cond [(fixnum? r) r]
  1268. [else (error 'interp-exp "expected an integer" r)])]
  1269. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1270. [(Prim '+ (list e1 e2))
  1271. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1272. [(Var x) (dict-ref env x)]
  1273. [(Let x e body)
  1274. (define new-env (dict-set env x ((interp-exp env) e)))
  1275. ((interp-exp new-env) body)]))
  1276. (define/public (interp-program p)
  1277. (match p
  1278. [(Program '() e) ((interp-exp '()) e)]))
  1279. ))
  1280. (define (interp-Rvar p)
  1281. (send (new interp-Rvar-class) interp-program p))
  1282. \end{lstlisting}
  1283. \caption{Interpreter for the \LangVar{} language.}
  1284. \label{fig:interp-Rvar}
  1285. \end{figure}
  1286. The goal for this chapter is to implement a compiler that translates
  1287. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1288. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1289. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1290. is, they output the same integer $n$. We depict this correctness
  1291. criteria in the following diagram.
  1292. \[
  1293. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1294. \node (p1) at (0, 0) {$P_1$};
  1295. \node (p2) at (4, 0) {$P_2$};
  1296. \node (o) at (4, -2) {$n$};
  1297. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1298. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1299. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1300. \end{tikzpicture}
  1301. \]
  1302. In the next section we introduce the \LangXInt{} subset of x86 that
  1303. suffices for compiling \LangVar{}.
  1304. \section{The \LangXInt{} Assembly Language}
  1305. \label{sec:x86}
  1306. \index{subject}{x86}
  1307. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1308. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1309. assembler.
  1310. %
  1311. A program begins with a \code{main} label followed by a sequence of
  1312. instructions. The \key{globl} directive says that the \key{main}
  1313. procedure is externally visible, which is necessary so that the
  1314. operating system can call it. In the grammar, ellipses such as
  1315. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1316. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1317. %
  1318. An x86 program is stored in the computer's memory. For our purposes,
  1319. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1320. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1321. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1322. the address of the next instruction to be executed. For most
  1323. instructions, the program counter is incremented after the instruction
  1324. is executed, so it points to the next instruction in memory. Most x86
  1325. instructions take two operands, where each operand is either an
  1326. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1327. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1328. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1329. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1330. && \key{r8} \mid \key{r9} \mid \key{r10}
  1331. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1332. \mid \key{r14} \mid \key{r15}}
  1333. \begin{figure}[tp]
  1334. \fbox{
  1335. \begin{minipage}{0.96\textwidth}
  1336. \[
  1337. \begin{array}{lcl}
  1338. \Reg &::=& \allregisters{} \\
  1339. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1340. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1341. \key{subq} \; \Arg\key{,} \Arg \mid
  1342. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1343. && \key{callq} \; \mathit{label} \mid
  1344. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1345. && \itm{label}\key{:}\; \Instr \\
  1346. \LangXIntM{} &::= & \key{.globl main}\\
  1347. & & \key{main:} \; \Instr\ldots
  1348. \end{array}
  1349. \]
  1350. \end{minipage}
  1351. }
  1352. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1353. \label{fig:x86-int-concrete}
  1354. \end{figure}
  1355. A register is a special kind of variable. Each one holds a 64-bit
  1356. value; there are 16 general-purpose registers in the computer and
  1357. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1358. is written with a \key{\%} followed by the register name, such as
  1359. \key{\%rax}.
  1360. An immediate value is written using the notation \key{\$}$n$ where $n$
  1361. is an integer.
  1362. %
  1363. %
  1364. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1365. which obtains the address stored in register $r$ and then adds $n$
  1366. bytes to the address. The resulting address is used to load or store
  1367. to memory depending on whether it occurs as a source or destination
  1368. argument of an instruction.
  1369. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1370. source $s$ and destination $d$, applies the arithmetic operation, then
  1371. writes the result back to the destination $d$.
  1372. %
  1373. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1374. stores the result in $d$.
  1375. %
  1376. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1377. specified by the label and $\key{retq}$ returns from a procedure to
  1378. its caller.
  1379. %
  1380. We discuss procedure calls in more detail later in this chapter and in
  1381. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1382. updates the program counter to the address of the instruction after
  1383. the specified label.
  1384. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1385. all of the x86 instructions used in this book.
  1386. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1387. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1388. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1389. adds $32$ to the $10$ in \key{rax} and
  1390. puts the result, $42$, back into \key{rax}.
  1391. %
  1392. The last instruction, \key{retq}, finishes the \key{main} function by
  1393. returning the integer in \key{rax} to the operating system. The
  1394. operating system interprets this integer as the program's exit
  1395. code. By convention, an exit code of 0 indicates that a program
  1396. completed successfully, and all other exit codes indicate various
  1397. errors. Nevertheless, in this book we return the result of the program
  1398. as the exit code.
  1399. \begin{figure}[tbp]
  1400. \begin{lstlisting}
  1401. .globl main
  1402. main:
  1403. movq $10, %rax
  1404. addq $32, %rax
  1405. retq
  1406. \end{lstlisting}
  1407. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1408. \label{fig:p0-x86}
  1409. \end{figure}
  1410. The x86 assembly language varies in a couple of ways depending on what
  1411. operating system it is assembled in. The code examples shown here are
  1412. correct on Linux and most Unix-like platforms, but when assembled on
  1413. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1414. as in \key{\_main}.
  1415. We exhibit the use of memory for storing intermediate results in the
  1416. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1417. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1418. memory called the \emph{procedure call stack} (or \emph{stack} for
  1419. short). \index{subject}{stack}\index{subject}{procedure call stack} The stack consists
  1420. of a separate \emph{frame}\index{subject}{frame} for each procedure call. The
  1421. memory layout for an individual frame is shown in
  1422. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1423. \emph{stack pointer}\index{subject}{stack pointer} and points to the item at
  1424. the top of the stack. The stack grows downward in memory, so we
  1425. increase the size of the stack by subtracting from the stack pointer.
  1426. In the context of a procedure call, the \emph{return
  1427. address}\index{subject}{return address} is the instruction after the call
  1428. instruction on the caller side. The function call instruction,
  1429. \code{callq}, pushes the return address onto the stack prior to
  1430. jumping to the procedure. The register \key{rbp} is the \emph{base
  1431. pointer}\index{subject}{base pointer} and is used to access variables that
  1432. are stored in the frame of the current procedure call. The base
  1433. pointer of the caller is pushed onto the stack after the return
  1434. address and then the base pointer is set to the location of the old
  1435. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1436. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1437. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1438. \begin{figure}[tbp]
  1439. \begin{lstlisting}
  1440. start:
  1441. movq $10, -8(%rbp)
  1442. negq -8(%rbp)
  1443. movq -8(%rbp), %rax
  1444. addq $52, %rax
  1445. jmp conclusion
  1446. .globl main
  1447. main:
  1448. pushq %rbp
  1449. movq %rsp, %rbp
  1450. subq $16, %rsp
  1451. jmp start
  1452. conclusion:
  1453. addq $16, %rsp
  1454. popq %rbp
  1455. retq
  1456. \end{lstlisting}
  1457. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1458. \label{fig:p1-x86}
  1459. \end{figure}
  1460. \begin{figure}[tbp]
  1461. \centering
  1462. \begin{tabular}{|r|l|} \hline
  1463. Position & Contents \\ \hline
  1464. 8(\key{\%rbp}) & return address \\
  1465. 0(\key{\%rbp}) & old \key{rbp} \\
  1466. -8(\key{\%rbp}) & variable $1$ \\
  1467. -16(\key{\%rbp}) & variable $2$ \\
  1468. \ldots & \ldots \\
  1469. 0(\key{\%rsp}) & variable $n$\\ \hline
  1470. \end{tabular}
  1471. \caption{Memory layout of a frame.}
  1472. \label{fig:frame}
  1473. \end{figure}
  1474. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1475. control is transferred from the operating system to the \code{main}
  1476. function. The operating system issues a \code{callq main} instruction
  1477. which pushes its return address on the stack and then jumps to
  1478. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1479. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1480. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1481. alignment (because the \code{callq} pushed the return address). The
  1482. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  1483. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1484. pointer for the caller onto the stack and subtracts $8$ from the stack
  1485. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1486. base pointer so that it points the location of the old base
  1487. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1488. pointer down to make enough room for storing variables. This program
  1489. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1490. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1491. functions. The last instruction of the prelude is \code{jmp start},
  1492. which transfers control to the instructions that were generated from
  1493. the Racket expression \code{(+ 52 (- 10))}.
  1494. The first instruction under the \code{start} label is
  1495. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1496. %
  1497. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1498. %
  1499. The next instruction moves the $-10$ from variable $1$ into the
  1500. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1501. the value in \code{rax}, updating its contents to $42$.
  1502. The three instructions under the label \code{conclusion} are the
  1503. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  1504. two instructions restore the \code{rsp} and \code{rbp} registers to
  1505. the state they were in at the beginning of the procedure. The
  1506. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1507. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1508. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1509. instruction, \key{retq}, jumps back to the procedure that called this
  1510. one and adds $8$ to the stack pointer.
  1511. The compiler needs a convenient representation for manipulating x86
  1512. programs, so we define an abstract syntax for x86 in
  1513. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1514. \LangXInt{}. The main difference compared to the concrete syntax of
  1515. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1516. allowed in front of every instruction. Instead instructions are
  1517. grouped into \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  1518. label associated with every block, which is why the \key{X86Program}
  1519. struct includes an alist mapping labels to blocks. The reason for this
  1520. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1521. introduce conditional branching. The \code{Block} structure includes
  1522. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1523. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1524. $\itm{info}$ field should contain an empty list. Also, regarding the
  1525. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1526. integer for representing the arity of the function, i.e., the number
  1527. of arguments, which is helpful to know during register allocation
  1528. (Chapter~\ref{ch:register-allocation-Rvar}).
  1529. \begin{figure}[tp]
  1530. \fbox{
  1531. \begin{minipage}{0.98\textwidth}
  1532. \small
  1533. \[
  1534. \begin{array}{lcl}
  1535. \Reg &::=& \allregisters{} \\
  1536. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1537. \mid \DEREF{\Reg}{\Int} \\
  1538. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1539. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1540. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1541. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1542. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1543. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1544. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1545. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1546. \end{array}
  1547. \]
  1548. \end{minipage}
  1549. }
  1550. \caption{The abstract syntax of \LangXInt{} assembly.}
  1551. \label{fig:x86-int-ast}
  1552. \end{figure}
  1553. \section{Planning the trip to x86 via the \LangCVar{} language}
  1554. \label{sec:plan-s0-x86}
  1555. To compile one language to another it helps to focus on the
  1556. differences between the two languages because the compiler will need
  1557. to bridge those differences. What are the differences between \LangVar{}
  1558. and x86 assembly? Here are some of the most important ones:
  1559. \begin{enumerate}
  1560. \item[(a)] x86 arithmetic instructions typically have two arguments
  1561. and update the second argument in place. In contrast, \LangVar{}
  1562. arithmetic operations take two arguments and produce a new value.
  1563. An x86 instruction may have at most one memory-accessing argument.
  1564. Furthermore, some instructions place special restrictions on their
  1565. arguments.
  1566. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1567. expression, whereas x86 instructions restrict their arguments to be
  1568. integer constants, registers, and memory locations.
  1569. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1570. sequence of instructions and jumps to labeled positions, whereas in
  1571. \LangVar{} the order of evaluation is a left-to-right depth-first
  1572. traversal of the abstract syntax tree.
  1573. \item[(d)] A program in \LangVar{} can have any number of variables
  1574. whereas x86 has 16 registers and the procedure calls stack.
  1575. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  1576. same name. In x86, registers have unique names and memory locations
  1577. have unique addresses.
  1578. \end{enumerate}
  1579. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1580. the problem into several steps, dealing with the above differences one
  1581. at a time. Each of these steps is called a \emph{pass} of the
  1582. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  1583. %
  1584. This terminology comes from the way each step passes over the AST of
  1585. the program.
  1586. %
  1587. We begin by sketching how we might implement each pass, and give them
  1588. names. We then figure out an ordering of the passes and the
  1589. input/output language for each pass. The very first pass has
  1590. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1591. its output language. In between we can choose whichever language is
  1592. most convenient for expressing the output of each pass, whether that
  1593. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1594. our own design. Finally, to implement each pass we write one
  1595. recursive function per non-terminal in the grammar of the input
  1596. language of the pass. \index{subject}{intermediate language}
  1597. \begin{description}
  1598. \item[\key{select-instructions}] handles the difference between
  1599. \LangVar{} operations and x86 instructions. This pass converts each
  1600. \LangVar{} operation to a short sequence of instructions that
  1601. accomplishes the same task.
  1602. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1603. a primitive operation is a variable or integer, that is, an
  1604. \emph{atomic} expression. We refer to non-atomic expressions as
  1605. \emph{complex}. This pass introduces temporary variables to hold
  1606. the results of complex subexpressions.\index{subject}{atomic
  1607. expression}\index{subject}{complex expression}%
  1608. \footnote{The subexpressions of an operation are often called
  1609. operators and operands which explains the presence of
  1610. \code{opera*} in the name of this pass.}
  1611. \item[\key{explicate-control}] makes the execution order of the
  1612. program explicit. It convert the abstract syntax tree representation
  1613. into a control-flow graph in which each node contains a sequence of
  1614. statements and the edges between nodes say which nodes contain jumps
  1615. to other nodes.
  1616. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1617. registers or stack locations in x86.
  1618. \item[\key{uniquify}] deals with the shadowing of variables by
  1619. renaming every variable to a unique name.
  1620. \end{description}
  1621. The next question is: in what order should we apply these passes? This
  1622. question can be challenging because it is difficult to know ahead of
  1623. time which orderings will be better (easier to implement, produce more
  1624. efficient code, etc.) so oftentimes trial-and-error is
  1625. involved. Nevertheless, we can try to plan ahead and make educated
  1626. choices regarding the ordering.
  1627. What should be the ordering of \key{explicate-control} with respect to
  1628. \key{uniquify}? The \key{uniquify} pass should come first because
  1629. \key{explicate-control} changes all the \key{let}-bound variables to
  1630. become local variables whose scope is the entire program, which would
  1631. confuse variables with the same name.
  1632. %
  1633. We place \key{remove-complex-opera*} before \key{explicate-control}
  1634. because the later removes the \key{let} form, but it is convenient to
  1635. use \key{let} in the output of \key{remove-complex-opera*}.
  1636. %
  1637. The ordering of \key{uniquify} with respect to
  1638. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1639. \key{uniquify} to come first.
  1640. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1641. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1642. learn that, in x86, registers are used for passing arguments to
  1643. functions and it is preferable to assign parameters to their
  1644. corresponding registers. On the other hand, by selecting instructions
  1645. first we may run into a dead end in \key{assign-homes}. Recall that
  1646. only one argument of an x86 instruction may be a memory access but
  1647. \key{assign-homes} might fail to assign even one of them to a
  1648. register.
  1649. %
  1650. A sophisticated approach is to iteratively repeat the two passes until
  1651. a solution is found. However, to reduce implementation complexity we
  1652. recommend a simpler approach in which \key{select-instructions} comes
  1653. first, followed by the \key{assign-homes}, then a third pass named
  1654. \key{patch-instructions} that uses a reserved register to fix
  1655. outstanding problems.
  1656. \begin{figure}[tbp]
  1657. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1658. \node (Rvar) at (0,2) {\large \LangVar{}};
  1659. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1660. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1661. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1662. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1663. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1664. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1665. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1666. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1667. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1668. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1669. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1670. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1671. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1672. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1673. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1674. \end{tikzpicture}
  1675. \caption{Diagram of the passes for compiling \LangVar{}. }
  1676. \label{fig:Rvar-passes}
  1677. \end{figure}
  1678. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1679. passes and identifies the input and output language of each pass. The
  1680. last pass, \key{print-x86}, converts from the abstract syntax of
  1681. \LangXInt{} to the concrete syntax. In the following two sections
  1682. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1683. dialect of x86. The remainder of this chapter gives hints regarding
  1684. the implementation of each of the compiler passes in
  1685. Figure~\ref{fig:Rvar-passes}.
  1686. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1687. %% are programs that are still in the \LangVar{} language, though the
  1688. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1689. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1690. %% %
  1691. %% The output of \key{explicate-control} is in an intermediate language
  1692. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1693. %% syntax, which we introduce in the next section. The
  1694. %% \key{select-instruction} pass translates from \LangCVar{} to
  1695. %% \LangXVar{}. The \key{assign-homes} and
  1696. %% \key{patch-instructions}
  1697. %% passes input and output variants of x86 assembly.
  1698. \subsection{The \LangCVar{} Intermediate Language}
  1699. The output of \key{explicate-control} is similar to the $C$
  1700. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1701. categories for expressions and statements, so we name it \LangCVar{}. The
  1702. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1703. (The concrete syntax for \LangCVar{} is in the Appendix,
  1704. Figure~\ref{fig:c0-concrete-syntax}.)
  1705. %
  1706. The \LangCVar{} language supports the same operators as \LangVar{} but
  1707. the arguments of operators are restricted to atomic
  1708. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1709. assignment statements which can be executed in sequence using the
  1710. \key{Seq} form. A sequence of statements always ends with
  1711. \key{Return}, a guarantee that is baked into the grammar rules for
  1712. \itm{tail}. The naming of this non-terminal comes from the term
  1713. \emph{tail position}\index{subject}{tail position}, which refers to an
  1714. expression that is the last one to execute within a function.
  1715. A \LangCVar{} program consists of a control-flow graph represented as
  1716. an alist mapping labels to tails. This is more general than necessary
  1717. for the present chapter, as we do not yet introduce \key{goto} for
  1718. jumping to labels, but it saves us from having to change the syntax in
  1719. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1720. \key{start}, and the whole program is its tail.
  1721. %
  1722. The $\itm{info}$ field of the \key{CProgram} form, after the
  1723. \key{explicate-control} pass, contains a mapping from the symbol
  1724. \key{locals} to a list of variables, that is, a list of all the
  1725. variables used in the program. At the start of the program, these
  1726. variables are uninitialized; they become initialized on their first
  1727. assignment.
  1728. \begin{figure}[tbp]
  1729. \fbox{
  1730. \begin{minipage}{0.96\textwidth}
  1731. \[
  1732. \begin{array}{lcl}
  1733. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1734. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1735. &\mid& \ADD{\Atm}{\Atm}\\
  1736. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1737. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1738. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1739. \end{array}
  1740. \]
  1741. \end{minipage}
  1742. }
  1743. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1744. \label{fig:c0-syntax}
  1745. \end{figure}
  1746. The definitional interpreter for \LangCVar{} is in the support code,
  1747. in the file \code{interp-Cvar.rkt}.
  1748. \subsection{The \LangXVar{} dialect}
  1749. The \LangXVar{} language is the output of the pass
  1750. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1751. number of program-scope variables and removes the restrictions
  1752. regarding instruction arguments.
  1753. \section{Uniquify Variables}
  1754. \label{sec:uniquify-Rvar}
  1755. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1756. programs in which every \key{let} binds a unique variable name. For
  1757. example, the \code{uniquify} pass should translate the program on the
  1758. left into the program on the right.
  1759. \begin{transformation}
  1760. \begin{lstlisting}
  1761. (let ([x 32])
  1762. (+ (let ([x 10]) x) x))
  1763. \end{lstlisting}
  1764. \compilesto
  1765. \begin{lstlisting}
  1766. (let ([x.1 32])
  1767. (+ (let ([x.2 10]) x.2) x.1))
  1768. \end{lstlisting}
  1769. \end{transformation}
  1770. The following is another example translation, this time of a program
  1771. with a \key{let} nested inside the initializing expression of another
  1772. \key{let}.
  1773. \begin{transformation}
  1774. \begin{lstlisting}
  1775. (let ([x (let ([x 4])
  1776. (+ x 1))])
  1777. (+ x 2))
  1778. \end{lstlisting}
  1779. \compilesto
  1780. \begin{lstlisting}
  1781. (let ([x.2 (let ([x.1 4])
  1782. (+ x.1 1))])
  1783. (+ x.2 2))
  1784. \end{lstlisting}
  1785. \end{transformation}
  1786. We recommend implementing \code{uniquify} by creating a structurally
  1787. recursive function named \code{uniquify-exp} that mostly just copies
  1788. an expression. However, when encountering a \key{let}, it should
  1789. generate a unique name for the variable and associate the old name
  1790. with the new name in an alist.\footnote{The Racket function
  1791. \code{gensym} is handy for generating unique variable names.} The
  1792. \code{uniquify-exp} function needs to access this alist when it gets
  1793. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1794. for the alist.
  1795. The skeleton of the \code{uniquify-exp} function is shown in
  1796. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1797. convenient to partially apply it to an alist and then apply it to
  1798. different expressions, as in the last case for primitive operations in
  1799. Figure~\ref{fig:uniquify-Rvar}. The
  1800. %
  1801. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1802. %
  1803. form of Racket is useful for transforming each element of a list to
  1804. produce a new list.\index{subject}{for/list}
  1805. \begin{figure}[tbp]
  1806. \begin{lstlisting}
  1807. (define (uniquify-exp env)
  1808. (lambda (e)
  1809. (match e
  1810. [(Var x) ___]
  1811. [(Int n) (Int n)]
  1812. [(Let x e body) ___]
  1813. [(Prim op es)
  1814. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1815. (define (uniquify p)
  1816. (match p
  1817. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1818. \end{lstlisting}
  1819. \caption{Skeleton for the \key{uniquify} pass.}
  1820. \label{fig:uniquify-Rvar}
  1821. \end{figure}
  1822. \begin{exercise}
  1823. \normalfont % I don't like the italics for exercises. -Jeremy
  1824. Complete the \code{uniquify} pass by filling in the blanks in
  1825. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1826. variables and for the \key{let} form in the file \code{compiler.rkt}
  1827. in the support code.
  1828. \end{exercise}
  1829. \begin{exercise}
  1830. \normalfont % I don't like the italics for exercises. -Jeremy
  1831. \label{ex:Rvar}
  1832. Create five \LangVar{} programs that exercise the most interesting
  1833. parts of the \key{uniquify} pass, that is, the programs should include
  1834. \key{let} forms, variables, and variables that shadow each other.
  1835. The five programs should be placed in the subdirectory named
  1836. \key{tests} and the file names should start with \code{var\_test\_}
  1837. followed by a unique integer and end with the file extension
  1838. \key{.rkt}.
  1839. %
  1840. The \key{run-tests.rkt} script in the support code checks whether the
  1841. output programs produce the same result as the input programs. The
  1842. script uses the \key{interp-tests} function
  1843. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1844. your \key{uniquify} pass on the example programs. The \code{passes}
  1845. parameter of \key{interp-tests} is a list that should have one entry
  1846. for each pass in your compiler. For now, define \code{passes} to
  1847. contain just one entry for \code{uniquify} as shown below.
  1848. \begin{lstlisting}
  1849. (define passes
  1850. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1851. \end{lstlisting}
  1852. Run the \key{run-tests.rkt} script in the support code to check
  1853. whether the output programs produce the same result as the input
  1854. programs.
  1855. \end{exercise}
  1856. \section{Remove Complex Operands}
  1857. \label{sec:remove-complex-opera-Rvar}
  1858. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  1859. into a restricted form in which the arguments of operations are atomic
  1860. expressions. Put another way, this pass removes complex
  1861. operands\index{subject}{complex operand}, such as the expression \code{(- 10)}
  1862. in the program below. This is accomplished by introducing a new
  1863. \key{let}-bound variable, binding the complex operand to the new
  1864. variable, and then using the new variable in place of the complex
  1865. operand, as shown in the output of \code{remove-complex-opera*} on the
  1866. right.
  1867. \begin{transformation}
  1868. % var_test_19.rkt
  1869. \begin{lstlisting}
  1870. (let ([x (+ 42 (- 10))])
  1871. (+ x 10))
  1872. \end{lstlisting}
  1873. \compilesto
  1874. \begin{lstlisting}
  1875. (let ([x (let ([tmp.1 (- 10)])
  1876. (+ 42 tmp.1))])
  1877. (+ x 10))
  1878. \end{lstlisting}
  1879. \end{transformation}
  1880. \begin{figure}[tp]
  1881. \centering
  1882. \fbox{
  1883. \begin{minipage}{0.96\textwidth}
  1884. \[
  1885. \begin{array}{rcl}
  1886. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1887. \Exp &::=& \Atm \mid \READ{} \\
  1888. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1889. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1890. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1891. \end{array}
  1892. \]
  1893. \end{minipage}
  1894. }
  1895. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  1896. atomic expressions, like administrative normal form (ANF).}
  1897. \label{fig:Rvar-anf-syntax}
  1898. \end{figure}
  1899. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  1900. this pass, the language \LangVarANF{}. The only difference is that
  1901. operator arguments are restricted to be atomic expressions that are
  1902. defined by the \Atm{} non-terminal. In particular, integer constants
  1903. and variables are atomic. In the literature, restricting arguments to
  1904. be atomic expressions is one of the ideas in \emph{administrative
  1905. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1906. \index{subject}{administrative normal form} \index{subject}{ANF}
  1907. We recommend implementing this pass with two mutually recursive
  1908. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1909. \code{rco-atom} to subexpressions that need to become atomic and to
  1910. apply \code{rco-exp} to subexpressions that do not. Both functions
  1911. take an \LangVar{} expression as input. The \code{rco-exp} function
  1912. returns an expression. The \code{rco-atom} function returns two
  1913. things: an atomic expression and an alist mapping temporary variables to
  1914. complex subexpressions. You can return multiple things from a function
  1915. using Racket's \key{values} form and you can receive multiple things
  1916. from a function call using the \key{define-values} form.
  1917. Also, the
  1918. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1919. form is useful for applying a function to each element of a list, in
  1920. the case where the function returns multiple values.
  1921. \index{subject}{for/lists}
  1922. Returning to the example program with the expression \code{(+ 42 (-
  1923. 10))}, the subexpression \code{(- 10)} should be processed using the
  1924. \code{rco-atom} function because it is an argument of the \code{+} and
  1925. therefore needs to become atomic. The output of \code{rco-atom}
  1926. applied to \code{(- 10)} is as follows.
  1927. \begin{transformation}
  1928. \begin{lstlisting}
  1929. (- 10)
  1930. \end{lstlisting}
  1931. \compilesto
  1932. \begin{lstlisting}
  1933. tmp.1
  1934. ((tmp.1 . (- 10)))
  1935. \end{lstlisting}
  1936. \end{transformation}
  1937. Take special care of programs such as the following that bind a
  1938. variable to an atomic expression. You should leave such variable
  1939. bindings unchanged, as shown in the program on the right \\
  1940. \begin{transformation}
  1941. % var_test_20.rkt
  1942. \begin{lstlisting}
  1943. (let ([a 42])
  1944. (let ([b a])
  1945. b))
  1946. \end{lstlisting}
  1947. \compilesto
  1948. \begin{lstlisting}
  1949. (let ([a 42])
  1950. (let ([b a])
  1951. b))
  1952. \end{lstlisting}
  1953. \end{transformation}
  1954. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1955. produce the following output with unnecessary temporary variables.
  1956. \begin{center}
  1957. \begin{minipage}{0.4\textwidth}
  1958. \begin{lstlisting}
  1959. (let ([tmp.1 42])
  1960. (let ([a tmp.1])
  1961. (let ([tmp.2 a])
  1962. (let ([b tmp.2])
  1963. b))))
  1964. \end{lstlisting}
  1965. \end{minipage}
  1966. \end{center}
  1967. \begin{exercise}
  1968. \normalfont
  1969. Implement the \code{remove-complex-opera*} function in
  1970. \code{compiler.rkt}.
  1971. %
  1972. Create three new \LangVar{} programs that exercise the interesting
  1973. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  1974. regarding file names described in Exercise~\ref{ex:Rvar}.
  1975. %
  1976. In the \code{run-tests.rkt} script, add the following entry to the
  1977. list of \code{passes} and then run the script to test your compiler.
  1978. \begin{lstlisting}
  1979. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  1980. \end{lstlisting}
  1981. While debugging your compiler, it is often useful to see the
  1982. intermediate programs that are output from each pass. To print the
  1983. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  1984. \code{interp-tests} in \code{run-tests.rkt}.
  1985. \end{exercise}
  1986. \section{Explicate Control}
  1987. \label{sec:explicate-control-Rvar}
  1988. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  1989. programs that make the order of execution explicit in their
  1990. syntax. For now this amounts to flattening \key{let} constructs into a
  1991. sequence of assignment statements. For example, consider the following
  1992. \LangVar{} program.\\
  1993. % var_test_11.rkt
  1994. \begin{minipage}{0.96\textwidth}
  1995. \begin{lstlisting}
  1996. (let ([y (let ([x 20])
  1997. (+ x (let ([x 22]) x)))])
  1998. y)
  1999. \end{lstlisting}
  2000. \end{minipage}\\
  2001. %
  2002. The output of the previous pass and of \code{explicate-control} is
  2003. shown below. Recall that the right-hand-side of a \key{let} executes
  2004. before its body, so the order of evaluation for this program is to
  2005. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2006. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2007. output of \code{explicate-control} makes this ordering explicit.
  2008. \begin{transformation}
  2009. \begin{lstlisting}
  2010. (let ([y (let ([x.1 20])
  2011. (let ([x.2 22])
  2012. (+ x.1 x.2)))])
  2013. y)
  2014. \end{lstlisting}
  2015. \compilesto
  2016. \begin{lstlisting}[language=C]
  2017. start:
  2018. x.1 = 20;
  2019. x.2 = 22;
  2020. y = (+ x.1 x.2);
  2021. return y;
  2022. \end{lstlisting}
  2023. \end{transformation}
  2024. \begin{figure}[tbp]
  2025. \begin{lstlisting}
  2026. (define (explicate-tail e)
  2027. (match e
  2028. [(Var x) ___]
  2029. [(Int n) (Return (Int n))]
  2030. [(Let x rhs body) ___]
  2031. [(Prim op es) ___]
  2032. [else (error "explicate-tail unhandled case" e)]))
  2033. (define (explicate-assign e x cont)
  2034. (match e
  2035. [(Var x) ___]
  2036. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2037. [(Let y rhs body) ___]
  2038. [(Prim op es) ___]
  2039. [else (error "explicate-assign unhandled case" e)]))
  2040. (define (explicate-control p)
  2041. (match p
  2042. [(Program info body) ___]))
  2043. \end{lstlisting}
  2044. \caption{Skeleton for the \key{explicate-control} pass.}
  2045. \label{fig:explicate-control-Rvar}
  2046. \end{figure}
  2047. The organization of this pass depends on the notion of tail position
  2048. that we have alluded to earlier.
  2049. \begin{definition}
  2050. The following rules define when an expression is in \textbf{\emph{tail
  2051. position}}\index{subject}{tail position} for the language \LangVar{}.
  2052. \begin{enumerate}
  2053. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2054. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2055. \end{enumerate}
  2056. \end{definition}
  2057. We recommend implementing \code{explicate-control} using two mutually
  2058. recursive functions, \code{explicate-tail} and
  2059. \code{explicate-assign}, as suggested in the skeleton code in
  2060. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2061. function should be applied to expressions in tail position whereas the
  2062. \code{explicate-assign} should be applied to expressions that occur on
  2063. the right-hand-side of a \key{let}.
  2064. %
  2065. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2066. input and produces a \Tail{} in \LangCVar{} (see
  2067. Figure~\ref{fig:c0-syntax}).
  2068. %
  2069. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2070. the variable that it is to be assigned to, and a \Tail{} in
  2071. \LangCVar{} for the code that comes after the assignment. The
  2072. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2073. The \code{explicate-assign} function is in accumulator-passing style:
  2074. the \code{cont} parameter is used for accumulating the output. This
  2075. accumulator-passing style plays an important role in how we generate
  2076. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2077. \begin{exercise}\normalfont
  2078. %
  2079. Implement the \code{explicate-control} function in
  2080. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2081. exercise the code in \code{explicate-control}.
  2082. %
  2083. In the \code{run-tests.rkt} script, add the following entry to the
  2084. list of \code{passes} and then run the script to test your compiler.
  2085. \begin{lstlisting}
  2086. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2087. \end{lstlisting}
  2088. \end{exercise}
  2089. \section{Select Instructions}
  2090. \label{sec:select-Rvar}
  2091. \index{subject}{instruction selection}
  2092. In the \code{select-instructions} pass we begin the work of
  2093. translating from \LangCVar{} to \LangXVar{}. The target language of
  2094. this pass is a variant of x86 that still uses variables, so we add an
  2095. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2096. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2097. recommend implementing the \code{select-instructions} with
  2098. three auxiliary functions, one for each of the non-terminals of
  2099. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2100. The cases for $\Atm$ are straightforward; variables stay
  2101. the same and integer constants are changed to immediates:
  2102. $\INT{n}$ changes to $\IMM{n}$.
  2103. Next we consider the cases for $\Stmt$, starting with arithmetic
  2104. operations. For example, consider the addition operation. We can use
  2105. the \key{addq} instruction, but it performs an in-place update. So we
  2106. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2107. add $\itm{arg}_2$ to \itm{var}.
  2108. \begin{transformation}
  2109. \begin{lstlisting}
  2110. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2111. \end{lstlisting}
  2112. \compilesto
  2113. \begin{lstlisting}
  2114. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2115. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2116. \end{lstlisting}
  2117. \end{transformation}
  2118. There are also cases that require special care to avoid generating
  2119. needlessly complicated code. For example, if one of the arguments of
  2120. the addition is the same variable as the left-hand side of the
  2121. assignment, then there is no need for the extra move instruction. The
  2122. assignment statement can be translated into a single \key{addq}
  2123. instruction as follows.
  2124. \begin{transformation}
  2125. \begin{lstlisting}
  2126. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2127. \end{lstlisting}
  2128. \compilesto
  2129. \begin{lstlisting}
  2130. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2131. \end{lstlisting}
  2132. \end{transformation}
  2133. The \key{read} operation does not have a direct counterpart in x86
  2134. assembly, so we provide this functionality with the function
  2135. \code{read\_int} in the file \code{runtime.c}, written in
  2136. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2137. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2138. system}, or simply the \emph{runtime} for short. When compiling your
  2139. generated x86 assembly code, you need to compile \code{runtime.c} to
  2140. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2141. \code{-c}) and link it into the executable. For our purposes of code
  2142. generation, all you need to do is translate an assignment of
  2143. \key{read} into a call to the \code{read\_int} function followed by a
  2144. move from \code{rax} to the left-hand-side variable. (Recall that the
  2145. return value of a function goes into \code{rax}.)
  2146. \begin{transformation}
  2147. \begin{lstlisting}
  2148. |$\itm{var}$| = (read);
  2149. \end{lstlisting}
  2150. \compilesto
  2151. \begin{lstlisting}
  2152. callq read_int
  2153. movq %rax, |$\itm{var}$|
  2154. \end{lstlisting}
  2155. \end{transformation}
  2156. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2157. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2158. assignment to the \key{rax} register followed by a jump to the
  2159. conclusion of the program (so the conclusion needs to be labeled).
  2160. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2161. recursively and then append the resulting instructions.
  2162. \begin{exercise}
  2163. \normalfont Implement the \key{select-instructions} pass in
  2164. \code{compiler.rkt}. Create three new example programs that are
  2165. designed to exercise all of the interesting cases in this pass.
  2166. %
  2167. In the \code{run-tests.rkt} script, add the following entry to the
  2168. list of \code{passes} and then run the script to test your compiler.
  2169. \begin{lstlisting}
  2170. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2171. \end{lstlisting}
  2172. \end{exercise}
  2173. \section{Assign Homes}
  2174. \label{sec:assign-Rvar}
  2175. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2176. \LangXVar{} programs that no longer use program variables.
  2177. Thus, the \key{assign-homes} pass is responsible for placing all of
  2178. the program variables in registers or on the stack. For runtime
  2179. efficiency, it is better to place variables in registers, but as there
  2180. are only 16 registers, some programs must necessarily resort to
  2181. placing some variables on the stack. In this chapter we focus on the
  2182. mechanics of placing variables on the stack. We study an algorithm for
  2183. placing variables in registers in
  2184. Chapter~\ref{ch:register-allocation-Rvar}.
  2185. Consider again the following \LangVar{} program from
  2186. Section~\ref{sec:remove-complex-opera-Rvar}.
  2187. % var_test_20.rkt
  2188. \begin{lstlisting}
  2189. (let ([a 42])
  2190. (let ([b a])
  2191. b))
  2192. \end{lstlisting}
  2193. The output of \code{select-instructions} is shown on the left and the
  2194. output of \code{assign-homes} on the right. In this example, we
  2195. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2196. variable \code{b} to location \code{-16(\%rbp)}.
  2197. \begin{transformation}
  2198. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2199. locals-types:
  2200. a : Integer, b : Integer
  2201. start:
  2202. movq $42, a
  2203. movq a, b
  2204. movq b, %rax
  2205. jmp conclusion
  2206. \end{lstlisting}
  2207. \compilesto
  2208. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2209. stack-space: 16
  2210. start:
  2211. movq $42, -8(%rbp)
  2212. movq -8(%rbp), -16(%rbp)
  2213. movq -16(%rbp), %rax
  2214. jmp conclusion
  2215. \end{lstlisting}
  2216. \end{transformation}
  2217. The \code{locals-types} entry in the $\itm{info}$ of the
  2218. \code{X86Program} node is an alist mapping all the variables in the
  2219. program to their types (for now just \code{Integer}). The
  2220. \code{assign-homes} pass should replace all uses of those variables
  2221. with stack locations. As an aside, the \code{locals-types} entry is
  2222. computed by \code{type-check-Cvar} in the support code, which installs
  2223. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2224. be propagated to the \code{X86Program} node.
  2225. In the process of assigning variables to stack locations, it is
  2226. convenient for you to compute and store the size of the frame (in
  2227. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2228. the key \code{stack-space}, which is needed later to generate the
  2229. conclusion of the \code{main} procedure. The x86-64 standard requires
  2230. the frame size to be a multiple of 16 bytes.\index{subject}{frame}
  2231. \begin{exercise}\normalfont
  2232. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2233. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2234. \Block{}. We recommend that the auxiliary functions take an extra
  2235. parameter that is an alist mapping variable names to homes (stack
  2236. locations for now).
  2237. %
  2238. In the \code{run-tests.rkt} script, add the following entry to the
  2239. list of \code{passes} and then run the script to test your compiler.
  2240. \begin{lstlisting}
  2241. (list "assign homes" assign-homes interp-x86-0)
  2242. \end{lstlisting}
  2243. \end{exercise}
  2244. \section{Patch Instructions}
  2245. \label{sec:patch-s0}
  2246. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2247. \LangXInt{} by making sure that each instruction adheres to the
  2248. restriction that at most one argument of an instruction may be a
  2249. memory reference.
  2250. We return to the following example.\\
  2251. \begin{minipage}{0.5\textwidth}
  2252. % var_test_20.rkt
  2253. \begin{lstlisting}
  2254. (let ([a 42])
  2255. (let ([b a])
  2256. b))
  2257. \end{lstlisting}
  2258. \end{minipage}\\
  2259. The \key{assign-homes} pass produces the following output
  2260. for this program. \\
  2261. \begin{minipage}{0.5\textwidth}
  2262. \begin{lstlisting}
  2263. stack-space: 16
  2264. start:
  2265. movq $42, -8(%rbp)
  2266. movq -8(%rbp), -16(%rbp)
  2267. movq -16(%rbp), %rax
  2268. jmp conclusion
  2269. \end{lstlisting}
  2270. \end{minipage}\\
  2271. The second \key{movq} instruction is problematic because both
  2272. arguments are stack locations. We suggest fixing this problem by
  2273. moving from the source location to the register \key{rax} and then
  2274. from \key{rax} to the destination location, as follows.
  2275. \begin{lstlisting}
  2276. movq -8(%rbp), %rax
  2277. movq %rax, -16(%rbp)
  2278. \end{lstlisting}
  2279. \begin{exercise}
  2280. \normalfont Implement the \key{patch-instructions} pass in
  2281. \code{compiler.rkt}. Create three new example programs that are
  2282. designed to exercise all of the interesting cases in this pass.
  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 "patch instructions" patch-instructions interp-x86-0)
  2288. \end{lstlisting}
  2289. \end{exercise}
  2290. \section{Print x86}
  2291. \label{sec:print-x86}
  2292. The last step of the compiler from \LangVar{} to x86 is to convert the
  2293. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2294. string representation (defined in
  2295. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2296. \key{string-append} functions are useful in this regard. The main work
  2297. that this step needs to perform is to create the \key{main} function
  2298. and the standard instructions for its prelude and conclusion, as shown
  2299. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2300. know the amount of space needed for the stack frame, which you can
  2301. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2302. the \key{X86Program} node.
  2303. When running on Mac OS X, you compiler should prefix an underscore to
  2304. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2305. useful for determining which operating system the compiler is running
  2306. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2307. \begin{exercise}\normalfont
  2308. %
  2309. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2310. %
  2311. In the \code{run-tests.rkt} script, add the following entry to the
  2312. list of \code{passes} and then run the script to test your compiler.
  2313. \begin{lstlisting}
  2314. (list "print x86" print-x86 #f)
  2315. \end{lstlisting}
  2316. %
  2317. Uncomment the call to the \key{compiler-tests} function
  2318. (Appendix~\ref{appendix:utilities}), which tests your complete
  2319. compiler by executing the generated x86 code. Compile the provided
  2320. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2321. script to test your compiler.
  2322. \end{exercise}
  2323. \section{Challenge: Partial Evaluator for \LangVar{}}
  2324. \label{sec:pe-Rvar}
  2325. \index{subject}{partial evaluation}
  2326. This section describes optional challenge exercises that involve
  2327. adapting and improving the partial evaluator for \LangInt{} that was
  2328. introduced in Section~\ref{sec:partial-evaluation}.
  2329. \begin{exercise}\label{ex:pe-Rvar}
  2330. \normalfont
  2331. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2332. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2333. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2334. and variables to the \LangInt{} language, so you will need to add cases for
  2335. them in the \code{pe-exp} function. Once complete, add the partial
  2336. evaluation pass to the front of your compiler and make sure that your
  2337. compiler still passes all of the tests.
  2338. \end{exercise}
  2339. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2340. \begin{exercise}
  2341. \normalfont
  2342. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2343. \code{pe-add} auxiliary functions with functions that know more about
  2344. arithmetic. For example, your partial evaluator should translate
  2345. \[
  2346. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2347. \code{(+ 2 (read))}
  2348. \]
  2349. To accomplish this, the \code{pe-exp} function should produce output
  2350. in the form of the $\itm{residual}$ non-terminal of the following
  2351. grammar. The idea is that when processing an addition expression, we
  2352. can always produce either 1) an integer constant, 2) an addition
  2353. expression with an integer constant on the left-hand side but not the
  2354. right-hand side, or 3) or an addition expression in which neither
  2355. subexpression is a constant.
  2356. \[
  2357. \begin{array}{lcl}
  2358. \itm{inert} &::=& \Var
  2359. \mid \LP\key{read}\RP
  2360. \mid \LP\key{-} ~\Var\RP
  2361. \mid \LP\key{-} ~\LP\key{read}\RP\RP
  2362. \mid \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  2363. &\mid& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  2364. \itm{residual} &::=& \Int
  2365. \mid \LP\key{+}~ \Int~ \itm{inert}\RP
  2366. \mid \itm{inert}
  2367. \end{array}
  2368. \]
  2369. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2370. inputs are $\itm{residual}$ expressions and they should return
  2371. $\itm{residual}$ expressions. Once the improvements are complete,
  2372. make sure that your compiler still passes all of the tests. After
  2373. all, fast code is useless if it produces incorrect results!
  2374. \end{exercise}
  2375. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2376. \chapter{Register Allocation}
  2377. \label{ch:register-allocation-Rvar}
  2378. \index{subject}{register allocation}
  2379. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2380. stack. In this Chapter we learn how to improve the performance of the
  2381. generated code by placing some variables into registers. The CPU can
  2382. access a register in a single cycle, whereas accessing the stack can
  2383. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2384. serves as a running example. The source program is on the left and the
  2385. output of instruction selection is on the right. The program is almost
  2386. in the x86 assembly language but it still uses variables.
  2387. \begin{figure}
  2388. \begin{minipage}{0.45\textwidth}
  2389. Example \LangVar{} program:
  2390. % var_test_28.rkt
  2391. \begin{lstlisting}
  2392. (let ([v 1])
  2393. (let ([w 42])
  2394. (let ([x (+ v 7)])
  2395. (let ([y x])
  2396. (let ([z (+ x w)])
  2397. (+ z (- y)))))))
  2398. \end{lstlisting}
  2399. \end{minipage}
  2400. \begin{minipage}{0.45\textwidth}
  2401. After instruction selection:
  2402. \begin{lstlisting}
  2403. locals-types:
  2404. x : Integer, y : Integer,
  2405. z : Integer, t : Integer,
  2406. v : Integer, w : Integer
  2407. start:
  2408. movq $1, v
  2409. movq $42, w
  2410. movq v, x
  2411. addq $7, x
  2412. movq x, y
  2413. movq x, z
  2414. addq w, z
  2415. movq y, t
  2416. negq t
  2417. movq z, %rax
  2418. addq t, %rax
  2419. jmp conclusion
  2420. \end{lstlisting}
  2421. \end{minipage}
  2422. \caption{A running example for register allocation.}
  2423. \label{fig:reg-eg}
  2424. \end{figure}
  2425. The goal of register allocation is to fit as many variables into
  2426. registers as possible. Some programs have more variables than
  2427. registers so we cannot always map each variable to a different
  2428. register. Fortunately, it is common for different variables to be
  2429. needed during different periods of time during program execution, and
  2430. in such cases several variables can be mapped to the same register.
  2431. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2432. After the variable \code{x} is moved to \code{z} it is no longer
  2433. needed. Variable \code{z}, on the other hand, is used only after this
  2434. point, so \code{x} and \code{z} could share the same register. The
  2435. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2436. where a variable is needed. Once we have that information, we compute
  2437. which variables are needed at the same time, i.e., which ones
  2438. \emph{interfere} with each other, and represent this relation as an
  2439. undirected graph whose vertices are variables and edges indicate when
  2440. two variables interfere (Section~\ref{sec:build-interference}). We
  2441. then model register allocation as a graph coloring problem
  2442. (Section~\ref{sec:graph-coloring}).
  2443. If we run out of registers despite these efforts, we place the
  2444. remaining variables on the stack, similar to what we did in
  2445. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2446. for assigning a variable to a stack location. The decision to spill a
  2447. variable is handled as part of the graph coloring process
  2448. (Section~\ref{sec:graph-coloring}).
  2449. We make the simplifying assumption that each variable is assigned to
  2450. one location (a register or stack address). A more sophisticated
  2451. approach is to assign a variable to one or more locations in different
  2452. regions of the program. For example, if a variable is used many times
  2453. in short sequence and then only used again after many other
  2454. instructions, it could be more efficient to assign the variable to a
  2455. register during the initial sequence and then move it to the stack for
  2456. the rest of its lifetime. We refer the interested reader to
  2457. \citet{Cooper:2011aa} for more information about that approach.
  2458. % discuss prioritizing variables based on how much they are used.
  2459. \section{Registers and Calling Conventions}
  2460. \label{sec:calling-conventions}
  2461. \index{subject}{calling conventions}
  2462. As we perform register allocation, we need to be aware of the
  2463. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  2464. functions calls are performed in x86.
  2465. %
  2466. Even though \LangVar{} does not include programmer-defined functions,
  2467. our generated code includes a \code{main} function that is called by
  2468. the operating system and our generated code contains calls to the
  2469. \code{read\_int} function.
  2470. Function calls require coordination between two pieces of code that
  2471. may be written by different programmers or generated by different
  2472. compilers. Here we follow the System V calling conventions that are
  2473. used by the GNU C compiler on Linux and
  2474. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2475. %
  2476. The calling conventions include rules about how functions share the
  2477. use of registers. In particular, the caller is responsible for freeing
  2478. up some registers prior to the function call for use by the callee.
  2479. These are called the \emph{caller-saved registers}
  2480. \index{subject}{caller-saved registers}
  2481. and they are
  2482. \begin{lstlisting}
  2483. rax rcx rdx rsi rdi r8 r9 r10 r11
  2484. \end{lstlisting}
  2485. On the other hand, the callee is responsible for preserving the values
  2486. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  2487. which are
  2488. \begin{lstlisting}
  2489. rsp rbp rbx r12 r13 r14 r15
  2490. \end{lstlisting}
  2491. We can think about this caller/callee convention from two points of
  2492. view, the caller view and the callee view:
  2493. \begin{itemize}
  2494. \item The caller should assume that all the caller-saved registers get
  2495. overwritten with arbitrary values by the callee. On the other hand,
  2496. the caller can safely assume that all the callee-saved registers
  2497. contain the same values after the call that they did before the
  2498. call.
  2499. \item The callee can freely use any of the caller-saved registers.
  2500. However, if the callee wants to use a callee-saved register, the
  2501. callee must arrange to put the original value back in the register
  2502. prior to returning to the caller. This can be accomplished by saving
  2503. the value to the stack in the prelude of the function and restoring
  2504. the value in the conclusion of the function.
  2505. \end{itemize}
  2506. In x86, registers are also used for passing arguments to a function
  2507. and for the return value. In particular, the first six arguments to a
  2508. function are passed in the following six registers, in this order.
  2509. \begin{lstlisting}
  2510. rdi rsi rdx rcx r8 r9
  2511. \end{lstlisting}
  2512. If there are more than six arguments, then the convention is to use
  2513. space on the frame of the caller for the rest of the
  2514. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2515. need more than six arguments. For now, the only function we care about
  2516. is \code{read\_int} and it takes zero arguments.
  2517. %
  2518. The register \code{rax} is used for the return value of a function.
  2519. The next question is how these calling conventions impact register
  2520. allocation. Consider the \LangVar{} program in
  2521. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2522. example from the caller point of view and then from the callee point
  2523. of view.
  2524. The program makes two calls to the \code{read} function. Also, the
  2525. variable \code{x} is in use during the second call to \code{read}, so
  2526. we need to make sure that the value in \code{x} does not get
  2527. accidentally wiped out by the call to \code{read}. One obvious
  2528. approach is to save all the values in caller-saved registers to the
  2529. stack prior to each function call, and restore them after each
  2530. call. That way, if the register allocator chooses to assign \code{x}
  2531. to a caller-saved register, its value will be preserved across the
  2532. call to \code{read}. However, saving and restoring to the stack is
  2533. relatively slow. If \code{x} is not used many times, it may be better
  2534. to assign \code{x} to a stack location in the first place. Or better
  2535. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2536. register, then it won't need to be saved and restored during function
  2537. calls.
  2538. The approach that we recommend for variables that are in use during a
  2539. function call is to either assign them to callee-saved registers or to
  2540. spill them to the stack. On the other hand, for variables that are not
  2541. in use during a function call, we try the following alternatives in
  2542. order 1) look for an available caller-saved register (to leave room
  2543. for other variables in the callee-saved register), 2) look for a
  2544. callee-saved register, and 3) spill the variable to the stack.
  2545. It is straightforward to implement this approach in a graph coloring
  2546. register allocator. First, we know which variables are in use during
  2547. every function call because we compute that information for every
  2548. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2549. build the interference graph (Section~\ref{sec:build-interference}),
  2550. we can place an edge between each of these variables and the
  2551. caller-saved registers in the interference graph. This will prevent
  2552. the graph coloring algorithm from assigning those variables to
  2553. caller-saved registers.
  2554. Returning to the example in
  2555. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2556. generated x86 code on the right-hand side, focusing on the
  2557. \code{start} block. Notice that variable \code{x} is assigned to
  2558. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2559. place during the second call to \code{read\_int}. Next, notice that
  2560. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2561. because there are no function calls in the remainder of the block.
  2562. Next we analyze the example from the callee point of view, focusing on
  2563. the prelude and conclusion of the \code{main} function. As usual the
  2564. prelude begins with saving the \code{rbp} register to the stack and
  2565. setting the \code{rbp} to the current stack pointer. We now know why
  2566. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2567. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2568. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2569. (\code{x}). The other callee-saved registers are not saved in the
  2570. prelude because they are not used. The prelude subtracts 8 bytes from
  2571. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2572. \code{start} block. Shifting attention to the \code{conclusion}, we
  2573. see that \code{rbx} is restored from the stack with a \code{popq}
  2574. instruction. \index{subject}{prelude}\index{subject}{conclusion}
  2575. \begin{figure}[tp]
  2576. \begin{minipage}{0.45\textwidth}
  2577. Example \LangVar{} program:
  2578. %var_test_14.rkt
  2579. \begin{lstlisting}
  2580. (let ([x (read)])
  2581. (let ([y (read)])
  2582. (+ (+ x y) 42)))
  2583. \end{lstlisting}
  2584. \end{minipage}
  2585. \begin{minipage}{0.45\textwidth}
  2586. Generated x86 assembly:
  2587. \begin{lstlisting}
  2588. start:
  2589. callq read_int
  2590. movq %rax, %rbx
  2591. callq read_int
  2592. movq %rax, %rcx
  2593. addq %rcx, %rbx
  2594. movq %rbx, %rax
  2595. addq $42, %rax
  2596. jmp _conclusion
  2597. .globl main
  2598. main:
  2599. pushq %rbp
  2600. movq %rsp, %rbp
  2601. pushq %rbx
  2602. subq $8, %rsp
  2603. jmp start
  2604. conclusion:
  2605. addq $8, %rsp
  2606. popq %rbx
  2607. popq %rbp
  2608. retq
  2609. \end{lstlisting}
  2610. \end{minipage}
  2611. \caption{An example with function calls.}
  2612. \label{fig:example-calling-conventions}
  2613. \end{figure}
  2614. %\clearpage
  2615. \section{Liveness Analysis}
  2616. \label{sec:liveness-analysis-Rvar}
  2617. \index{subject}{liveness analysis}
  2618. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2619. is, it discovers which variables are in-use in different regions of a
  2620. program.
  2621. %
  2622. A variable or register is \emph{live} at a program point if its
  2623. current value is used at some later point in the program. We
  2624. refer to variables and registers collectively as \emph{locations}.
  2625. %
  2626. Consider the following code fragment in which there are two writes to
  2627. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2628. \begin{center}
  2629. \begin{minipage}{0.96\textwidth}
  2630. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2631. movq $5, a
  2632. movq $30, b
  2633. movq a, c
  2634. movq $10, b
  2635. addq b, c
  2636. \end{lstlisting}
  2637. \end{minipage}
  2638. \end{center}
  2639. The answer is no because \code{a} is live from line 1 to 3 and
  2640. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2641. line 2 is never used because it is overwritten (line 4) before the
  2642. next read (line 5).
  2643. The live locations can be computed by traversing the instruction
  2644. sequence back to front (i.e., backwards in execution order). Let
  2645. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2646. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2647. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2648. locations before instruction $I_k$. We recommend represeting these
  2649. sets with the Racket \code{set} data structure described in
  2650. Figure~\ref{fig:set}.
  2651. \begin{figure}[tp]
  2652. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  2653. \small
  2654. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2655. A \emph{set} is an unordered collection of elements without duplicates.
  2656. Here are some of the operations defined on sets.
  2657. \index{subject}{set}
  2658. \begin{description}
  2659. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  2660. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  2661. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  2662. difference of the two sets.
  2663. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  2664. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  2665. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  2666. \end{description}
  2667. \end{tcolorbox}
  2668. %\end{wrapfigure}
  2669. \caption{The \code{set} data structure.}
  2670. \label{fig:set}
  2671. \end{figure}
  2672. The live locations after an instruction are always the same as the
  2673. live locations before the next instruction.
  2674. \index{subject}{live-after} \index{subject}{live-before}
  2675. \begin{equation} \label{eq:live-after-before-next}
  2676. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2677. \end{equation}
  2678. To start things off, there are no live locations after the last
  2679. instruction, so
  2680. \begin{equation}\label{eq:live-last-empty}
  2681. L_{\mathsf{after}}(n) = \emptyset
  2682. \end{equation}
  2683. We then apply the following rule repeatedly, traversing the
  2684. instruction sequence back to front.
  2685. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2686. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2687. \end{equation}
  2688. where $W(k)$ are the locations written to by instruction $I_k$ and
  2689. $R(k)$ are the locations read by instruction $I_k$.
  2690. There is a special case for \code{jmp} instructions. The locations
  2691. that are live before a \code{jmp} should be the locations in
  2692. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2693. maintaining an alist named \code{label->live} that maps each label to
  2694. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2695. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2696. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2697. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2698. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2699. Let us walk through the above example, applying these formulas
  2700. starting with the instruction on line 5. We collect the answers in
  2701. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2702. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2703. instruction (formula~\ref{eq:live-last-empty}). The
  2704. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2705. because it reads from variables \code{b} and \code{c}
  2706. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2707. \[
  2708. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2709. \]
  2710. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2711. the live-before set from line 5 to be the live-after set for this
  2712. instruction (formula~\ref{eq:live-after-before-next}).
  2713. \[
  2714. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2715. \]
  2716. This move instruction writes to \code{b} and does not read from any
  2717. variables, so we have the following live-before set
  2718. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2719. \[
  2720. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2721. \]
  2722. The live-before for instruction \code{movq a, c}
  2723. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2724. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2725. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2726. variable that is not live and does not read from a variable.
  2727. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2728. because it writes to variable \code{a}.
  2729. \begin{figure}[tbp]
  2730. \begin{minipage}{0.45\textwidth}
  2731. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2732. movq $5, a
  2733. movq $30, b
  2734. movq a, c
  2735. movq $10, b
  2736. addq b, c
  2737. \end{lstlisting}
  2738. \end{minipage}
  2739. \vrule\hspace{10pt}
  2740. \begin{minipage}{0.45\textwidth}
  2741. \begin{align*}
  2742. L_{\mathsf{before}}(1)= \emptyset,
  2743. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2744. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2745. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2746. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2747. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2748. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2749. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2750. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2751. L_{\mathsf{after}}(5)= \emptyset
  2752. \end{align*}
  2753. \end{minipage}
  2754. \caption{Example output of liveness analysis on a short example.}
  2755. \label{fig:liveness-example-0}
  2756. \end{figure}
  2757. \begin{exercise}\normalfont
  2758. Perform liveness analysis on the running example in
  2759. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2760. sets for each instruction. Compare your answers to the solution
  2761. shown in Figure~\ref{fig:live-eg}.
  2762. \end{exercise}
  2763. \begin{figure}[tp]
  2764. \hspace{20pt}
  2765. \begin{minipage}{0.45\textwidth}
  2766. \begin{lstlisting}
  2767. |$\{\ttm{rsp}\}$|
  2768. movq $1, v
  2769. |$\{\ttm{v},\ttm{rsp}\}$|
  2770. movq $42, w
  2771. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2772. movq v, x
  2773. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2774. addq $7, x
  2775. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2776. movq x, y
  2777. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2778. movq x, z
  2779. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2780. addq w, z
  2781. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2782. movq y, t
  2783. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2784. negq t
  2785. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2786. movq z, %rax
  2787. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2788. addq t, %rax
  2789. |$\{\ttm{rax},\ttm{rsp}\}$|
  2790. jmp conclusion
  2791. \end{lstlisting}
  2792. \end{minipage}
  2793. \caption{The running example annotated with live-after sets.}
  2794. \label{fig:live-eg}
  2795. \end{figure}
  2796. \begin{exercise}\normalfont
  2797. Implement the \code{uncover-live} pass. Store the sequence of
  2798. live-after sets in the $\itm{info}$ field of the \code{Block}
  2799. structure.
  2800. %
  2801. We recommend creating an auxiliary function that takes a list of
  2802. instructions and an initial live-after set (typically empty) and
  2803. returns the list of live-after sets.
  2804. %
  2805. We also recommend creating auxiliary functions to 1) compute the set
  2806. of locations that appear in an \Arg{}, 2) compute the locations read
  2807. by an instruction (the $R$ function), and 3) the locations written by
  2808. an instruction (the $W$ function). The \code{callq} instruction should
  2809. include all of the caller-saved registers in its write-set $W$ because
  2810. the calling convention says that those registers may be written to
  2811. during the function call. Likewise, the \code{callq} instruction
  2812. should include the appropriate argument-passing registers in its
  2813. read-set $R$, depending on the arity of the function being
  2814. called. (This is why the abstract syntax for \code{callq} includes the
  2815. arity.)
  2816. \end{exercise}
  2817. %\clearpage
  2818. \section{Build the Interference Graph}
  2819. \label{sec:build-interference}
  2820. \begin{figure}[tp]
  2821. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  2822. \small
  2823. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2824. A \emph{graph} is a collection of vertices and edges where each
  2825. edge connects two vertices. A graph is \emph{directed} if each
  2826. edge points from a source to a target. Otherwise the graph is
  2827. \emph{undirected}.
  2828. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  2829. \begin{description}
  2830. %% We currently don't use directed graphs. We instead use
  2831. %% directed multi-graphs. -Jeremy
  2832. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2833. directed graph from a list of edges. Each edge is a list
  2834. containing the source and target vertex.
  2835. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2836. undirected graph from a list of edges. Each edge is represented by
  2837. a list containing two vertices.
  2838. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2839. inserts a vertex into the graph.
  2840. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2841. inserts an edge between the two vertices.
  2842. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2843. returns a sequence of vertices adjacent to the vertex.
  2844. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2845. returns a sequence of all vertices in the graph.
  2846. \end{description}
  2847. \end{tcolorbox}
  2848. %\end{wrapfigure}
  2849. \caption{The Racket \code{graph} package.}
  2850. \label{fig:graph}
  2851. \end{figure}
  2852. Based on the liveness analysis, we know where each location is live.
  2853. However, during register allocation, we need to answer questions of
  2854. the specific form: are locations $u$ and $v$ live at the same time?
  2855. (And therefore cannot be assigned to the same register.) To make this
  2856. question more efficient to answer, we create an explicit data
  2857. structure, an \emph{interference graph}\index{subject}{interference
  2858. graph}. An interference graph is an undirected graph that has an
  2859. edge between two locations if they are live at the same time, that is,
  2860. if they interfere with each other. We recommend using the Racket
  2861. \code{graph} package (Figure~\ref{fig:graph}) to represent
  2862. the interference graph.
  2863. An obvious way to compute the interference graph is to look at the set
  2864. of live locations between each instruction and the next and add an edge to the graph
  2865. for every pair of variables in the same set. This approach is less
  2866. than ideal for two reasons. First, it can be expensive because it
  2867. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2868. locations. Second, in the special case where two locations hold the
  2869. same value (because one was assigned to the other), they can be live
  2870. at the same time without interfering with each other.
  2871. A better way to compute the interference graph is to focus on
  2872. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2873. must not overwrite something in a live location. So for each
  2874. instruction, we create an edge between the locations being written to
  2875. and the live locations. (Except that one should not create self
  2876. edges.) Note that for the \key{callq} instruction, we consider all of
  2877. the caller-saved registers as being written to, so an edge is added
  2878. between every live variable and every caller-saved register. For
  2879. \key{movq}, we deal with the above-mentioned special case by not
  2880. adding an edge between a live variable $v$ and the destination if $v$
  2881. matches the source. So we have the following two rules.
  2882. \begin{enumerate}
  2883. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2884. $d$, then add the edge $(d,v)$ for every $v \in
  2885. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2886. \item For any other instruction $I_k$, for every $d \in W(k)$
  2887. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2888. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2889. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2890. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2891. %% \item If instruction $I_k$ is of the form \key{callq}
  2892. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2893. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2894. \end{enumerate}
  2895. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2896. the above rules to each instruction. We highlight a few of the
  2897. instructions. The first instruction is \lstinline{movq $1, v} and the
  2898. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2899. interferes with \code{rsp}.
  2900. %
  2901. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2902. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2903. interferes with \ttm{w} and \ttm{rsp}.
  2904. %
  2905. The next instruction is \lstinline{movq x, y} and the live-after set
  2906. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2907. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2908. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2909. same value. Figure~\ref{fig:interference-results} lists the
  2910. interference results for all of the instructions and the resulting
  2911. interference graph is shown in Figure~\ref{fig:interfere}.
  2912. \begin{figure}[tbp]
  2913. \begin{quote}
  2914. \begin{tabular}{ll}
  2915. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2916. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2917. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2918. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2919. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2920. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2921. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2922. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2923. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2924. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2925. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2926. \lstinline!jmp conclusion!& no interference.
  2927. \end{tabular}
  2928. \end{quote}
  2929. \caption{Interference results for the running example.}
  2930. \label{fig:interference-results}
  2931. \end{figure}
  2932. \begin{figure}[tbp]
  2933. \large
  2934. \[
  2935. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2936. \node (rax) at (0,0) {$\ttm{rax}$};
  2937. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2938. \node (t1) at (0,2) {$\ttm{t}$};
  2939. \node (z) at (3,2) {$\ttm{z}$};
  2940. \node (x) at (6,2) {$\ttm{x}$};
  2941. \node (y) at (3,0) {$\ttm{y}$};
  2942. \node (w) at (6,0) {$\ttm{w}$};
  2943. \node (v) at (9,0) {$\ttm{v}$};
  2944. \draw (t1) to (rax);
  2945. \draw (t1) to (z);
  2946. \draw (z) to (y);
  2947. \draw (z) to (w);
  2948. \draw (x) to (w);
  2949. \draw (y) to (w);
  2950. \draw (v) to (w);
  2951. \draw (v) to (rsp);
  2952. \draw (w) to (rsp);
  2953. \draw (x) to (rsp);
  2954. \draw (y) to (rsp);
  2955. \path[-.,bend left=15] (z) edge node {} (rsp);
  2956. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2957. \draw (rax) to (rsp);
  2958. \end{tikzpicture}
  2959. \]
  2960. \caption{The interference graph of the example program.}
  2961. \label{fig:interfere}
  2962. \end{figure}
  2963. %% Our next concern is to choose a data structure for representing the
  2964. %% interference graph. There are many choices for how to represent a
  2965. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2966. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2967. %% data structure is to study the algorithm that uses the data structure,
  2968. %% determine what operations need to be performed, and then choose the
  2969. %% data structure that provide the most efficient implementations of
  2970. %% those operations. Often times the choice of data structure can have an
  2971. %% effect on the time complexity of the algorithm, as it does here. If
  2972. %% you skim the next section, you will see that the register allocation
  2973. %% algorithm needs to ask the graph for all of its vertices and, given a
  2974. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2975. %% correct choice of graph representation is that of an adjacency
  2976. %% list. There are helper functions in \code{utilities.rkt} for
  2977. %% representing graphs using the adjacency list representation:
  2978. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2979. %% (Appendix~\ref{appendix:utilities}).
  2980. %% %
  2981. %% \margincomment{\footnotesize To do: change to use the
  2982. %% Racket graph library. \\ --Jeremy}
  2983. %% %
  2984. %% In particular, those functions use a hash table to map each vertex to
  2985. %% the set of adjacent vertices, and the sets are represented using
  2986. %% Racket's \key{set}, which is also a hash table.
  2987. \begin{exercise}\normalfont
  2988. Implement the compiler pass named \code{build-interference} according
  2989. to the algorithm suggested above. We recommend using the \code{graph}
  2990. package to create and inspect the interference graph. The output
  2991. graph of this pass should be stored in the $\itm{info}$ field of the
  2992. program, under the key \code{conflicts}.
  2993. \end{exercise}
  2994. \section{Graph Coloring via Sudoku}
  2995. \label{sec:graph-coloring}
  2996. \index{subject}{graph coloring}
  2997. \index{subject}{Sudoku}
  2998. \index{subject}{color}
  2999. We come to the main event, mapping variables to registers and stack
  3000. locations. Variables that interfere with each other must be mapped to
  3001. different locations. In terms of the interference graph, this means
  3002. that adjacent vertices must be mapped to different locations. If we
  3003. think of locations as colors, the register allocation problem becomes
  3004. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3005. The reader may be more familiar with the graph coloring problem than he
  3006. or she realizes; the popular game of Sudoku is an instance of the
  3007. graph coloring problem. The following describes how to build a graph
  3008. out of an initial Sudoku board.
  3009. \begin{itemize}
  3010. \item There is one vertex in the graph for each Sudoku square.
  3011. \item There is an edge between two vertices if the corresponding squares
  3012. are in the same row, in the same column, or if the squares are in
  3013. the same $3\times 3$ region.
  3014. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3015. \item Based on the initial assignment of numbers to squares in the
  3016. Sudoku board, assign the corresponding colors to the corresponding
  3017. vertices in the graph.
  3018. \end{itemize}
  3019. If you can color the remaining vertices in the graph with the nine
  3020. colors, then you have also solved the corresponding game of Sudoku.
  3021. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3022. the corresponding graph with colored vertices. We map the Sudoku
  3023. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  3024. sampling of the vertices (the colored ones) because showing edges for
  3025. all of the vertices would make the graph unreadable.
  3026. \begin{figure}[tbp]
  3027. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3028. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  3029. \caption{A Sudoku game board and the corresponding colored graph.}
  3030. \label{fig:sudoku-graph}
  3031. \end{figure}
  3032. Some techniques for playing Sudoku correspond to heuristics used in
  3033. graph coloring algorithms. For example, one of the basic techniques
  3034. for Sudoku is called Pencil Marks. The idea is to use a process of
  3035. elimination to determine what numbers are no longer available for a
  3036. square and write down those numbers in the square (writing very
  3037. small). For example, if the number $1$ is assigned to a square, then
  3038. write the pencil mark $1$ in all the squares in the same row, column,
  3039. and region to indicate that $1$ is no longer an option for those other
  3040. squares.
  3041. %
  3042. The Pencil Marks technique corresponds to the notion of
  3043. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  3044. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3045. are no longer available. In graph terminology, we have the following
  3046. definition:
  3047. \begin{equation*}
  3048. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3049. \text{ and } \mathrm{color}(v) = c \}
  3050. \end{equation*}
  3051. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3052. edge with $u$.
  3053. Using the Pencil Marks technique leads to a simple strategy for
  3054. filling in numbers: if there is a square with only one possible number
  3055. left, then choose that number! But what if there are no squares with
  3056. only one possibility left? One brute-force approach is to try them
  3057. all: choose the first one and if that ultimately leads to a solution,
  3058. great. If not, backtrack and choose the next possibility. One good
  3059. thing about Pencil Marks is that it reduces the degree of branching in
  3060. the search tree. Nevertheless, backtracking can be terribly time
  3061. consuming. One way to reduce the amount of backtracking is to use the
  3062. most-constrained-first heuristic. That is, when choosing a square,
  3063. always choose one with the fewest possibilities left (the vertex with
  3064. the highest saturation). The idea is that choosing highly constrained
  3065. squares earlier rather than later is better because later on there may
  3066. not be any possibilities left in the highly saturated squares.
  3067. However, register allocation is easier than Sudoku because the
  3068. register allocator can map variables to stack locations when the
  3069. registers run out. Thus, it makes sense to replace backtracking with
  3070. greedy search: make the best choice at the time and keep going. We
  3071. still wish to minimize the number of colors needed, so we use the
  3072. most-constrained-first heuristic in the greedy search.
  3073. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3074. algorithm for register allocation based on saturation and the
  3075. most-constrained-first heuristic. It is roughly equivalent to the
  3076. DSATUR
  3077. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3078. as in Sudoku, the algorithm represents colors with integers. The
  3079. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3080. for register allocation. The integers $k$ and larger correspond to
  3081. stack locations. The registers that are not used for register
  3082. allocation, such as \code{rax}, are assigned to negative integers. In
  3083. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3084. %% One might wonder why we include registers at all in the liveness
  3085. %% analysis and interference graph. For example, we never allocate a
  3086. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3087. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3088. %% to use register for passing arguments to functions, it will be
  3089. %% necessary for those registers to appear in the interference graph
  3090. %% because those registers will also be assigned to variables, and we
  3091. %% don't want those two uses to encroach on each other. Regarding
  3092. %% registers such as \code{rax} and \code{rsp} that are not used for
  3093. %% variables, we could omit them from the interference graph but that
  3094. %% would require adding special cases to our algorithm, which would
  3095. %% complicate the logic for little gain.
  3096. \begin{figure}[btp]
  3097. \centering
  3098. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3099. Algorithm: DSATUR
  3100. Input: a graph |$G$|
  3101. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3102. |$W \gets \mathrm{vertices}(G)$|
  3103. while |$W \neq \emptyset$| do
  3104. pick a vertex |$u$| from |$W$| with the highest saturation,
  3105. breaking ties randomly
  3106. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3107. |$\mathrm{color}[u] \gets c$|
  3108. |$W \gets W - \{u\}$|
  3109. \end{lstlisting}
  3110. \caption{The saturation-based greedy graph coloring algorithm.}
  3111. \label{fig:satur-algo}
  3112. \end{figure}
  3113. With the DSATUR algorithm in hand, let us return to the running
  3114. example and consider how to color the interference graph in
  3115. Figure~\ref{fig:interfere}.
  3116. %
  3117. We start by assigning the register nodes to their own color. For
  3118. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3119. assigned $-2$. The variables are not yet colored, so they are
  3120. annotated with a dash. We then update the saturation for vertices that
  3121. are adjacent to a register, obtaining the following annotated
  3122. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3123. it interferes with both \code{rax} and \code{rsp}.
  3124. \[
  3125. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3126. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3127. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3128. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3129. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3130. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3131. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3132. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3133. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3134. \draw (t1) to (rax);
  3135. \draw (t1) to (z);
  3136. \draw (z) to (y);
  3137. \draw (z) to (w);
  3138. \draw (x) to (w);
  3139. \draw (y) to (w);
  3140. \draw (v) to (w);
  3141. \draw (v) to (rsp);
  3142. \draw (w) to (rsp);
  3143. \draw (x) to (rsp);
  3144. \draw (y) to (rsp);
  3145. \path[-.,bend left=15] (z) edge node {} (rsp);
  3146. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3147. \draw (rax) to (rsp);
  3148. \end{tikzpicture}
  3149. \]
  3150. The algorithm says to select a maximally saturated vertex. So we pick
  3151. $\ttm{t}$ and color it with the first available integer, which is
  3152. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3153. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3154. \[
  3155. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3156. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3157. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3158. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3159. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3160. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3161. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3162. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3163. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3164. \draw (t1) to (rax);
  3165. \draw (t1) to (z);
  3166. \draw (z) to (y);
  3167. \draw (z) to (w);
  3168. \draw (x) to (w);
  3169. \draw (y) to (w);
  3170. \draw (v) to (w);
  3171. \draw (v) to (rsp);
  3172. \draw (w) to (rsp);
  3173. \draw (x) to (rsp);
  3174. \draw (y) to (rsp);
  3175. \path[-.,bend left=15] (z) edge node {} (rsp);
  3176. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3177. \draw (rax) to (rsp);
  3178. \end{tikzpicture}
  3179. \]
  3180. We repeat the process, selecting the next maximally saturated vertex,
  3181. which is \code{z}, and color it with the first available number, which
  3182. is $1$. We add $1$ to the saturation for the neighboring vertices
  3183. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3184. \[
  3185. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3186. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3187. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3188. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3189. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3190. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3191. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3192. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3193. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3194. \draw (t1) to (rax);
  3195. \draw (t1) to (z);
  3196. \draw (z) to (y);
  3197. \draw (z) to (w);
  3198. \draw (x) to (w);
  3199. \draw (y) to (w);
  3200. \draw (v) to (w);
  3201. \draw (v) to (rsp);
  3202. \draw (w) to (rsp);
  3203. \draw (x) to (rsp);
  3204. \draw (y) to (rsp);
  3205. \path[-.,bend left=15] (z) edge node {} (rsp);
  3206. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3207. \draw (rax) to (rsp);
  3208. \end{tikzpicture}
  3209. \]
  3210. The most saturated vertices are now \code{w} and \code{y}. We color
  3211. \code{w} with the first available color, which is $0$.
  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}:-,\{0,-2\}$};
  3219. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3220. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3221. \node (v) at (10,0) {$\ttm{v}:-,\{0,-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. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3239. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3240. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3241. and \code{z}, whose colors are $0$ and $1$ respectively.
  3242. \[
  3243. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3244. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3245. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3246. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3247. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3248. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3249. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3250. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3251. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3252. \draw (t1) to (rax);
  3253. \draw (t1) to (z);
  3254. \draw (z) to (y);
  3255. \draw (z) to (w);
  3256. \draw (x) to (w);
  3257. \draw (y) to (w);
  3258. \draw (v) to (w);
  3259. \draw (v) to (rsp);
  3260. \draw (w) to (rsp);
  3261. \draw (x) to (rsp);
  3262. \draw (y) to (rsp);
  3263. \path[-.,bend left=15] (z) edge node {} (rsp);
  3264. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3265. \draw (rax) to (rsp);
  3266. \end{tikzpicture}
  3267. \]
  3268. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3269. \[
  3270. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3271. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3272. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3273. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3274. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3275. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3276. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3277. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3278. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3279. \draw (t1) to (rax);
  3280. \draw (t1) to (z);
  3281. \draw (z) to (y);
  3282. \draw (z) to (w);
  3283. \draw (x) to (w);
  3284. \draw (y) to (w);
  3285. \draw (v) to (w);
  3286. \draw (v) to (rsp);
  3287. \draw (w) to (rsp);
  3288. \draw (x) to (rsp);
  3289. \draw (y) to (rsp);
  3290. \path[-.,bend left=15] (z) edge node {} (rsp);
  3291. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3292. \draw (rax) to (rsp);
  3293. \end{tikzpicture}
  3294. \]
  3295. In the last step of the algorithm, we color \code{x} with $1$.
  3296. \[
  3297. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3298. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3299. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3300. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3301. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3302. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3303. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3304. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3305. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3306. \draw (t1) to (rax);
  3307. \draw (t1) to (z);
  3308. \draw (z) to (y);
  3309. \draw (z) to (w);
  3310. \draw (x) to (w);
  3311. \draw (y) to (w);
  3312. \draw (v) to (w);
  3313. \draw (v) to (rsp);
  3314. \draw (w) to (rsp);
  3315. \draw (x) to (rsp);
  3316. \draw (y) to (rsp);
  3317. \path[-.,bend left=15] (z) edge node {} (rsp);
  3318. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3319. \draw (rax) to (rsp);
  3320. \end{tikzpicture}
  3321. \]
  3322. We recommend creating an auxiliary function named \code{color-graph}
  3323. that takes an interference graph and a list of all the variables in
  3324. the program. This function should return a mapping of variables to
  3325. their colors (represented as natural numbers). By creating this helper
  3326. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3327. when we add support for functions.
  3328. To prioritize the processing of highly saturated nodes inside the
  3329. \code{color-graph} function, we recommend using the priority queue
  3330. data structure described in Figure~\ref{fig:priority-queue}. In
  3331. addition, you will need to maintain a mapping from variables to their
  3332. ``handles'' in the priority queue so that you can notify the priority
  3333. queue when their saturation changes.
  3334. \begin{figure}[tp]
  3335. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  3336. \small
  3337. \begin{tcolorbox}[title=Priority Queue]
  3338. A \emph{priority queue} is a collection of items in which the
  3339. removal of items is governed by priority. In a ``min'' queue,
  3340. lower priority items are removed first. An implementation is in
  3341. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  3342. queue} \index{subject}{minimum priority queue}
  3343. \begin{description}
  3344. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3345. priority queue that uses the $\itm{cmp}$ predicate to determine
  3346. whether its first argument has lower or equal priority to its
  3347. second argument.
  3348. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3349. items in the queue.
  3350. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3351. the item into the queue and returns a handle for the item in the
  3352. queue.
  3353. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3354. the lowest priority.
  3355. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3356. notifies the queue that the priority has decreased for the item
  3357. associated with the given handle.
  3358. \end{description}
  3359. \end{tcolorbox}
  3360. %\end{wrapfigure}
  3361. \caption{The priority queue data structure.}
  3362. \label{fig:priority-queue}
  3363. \end{figure}
  3364. With the coloring complete, we finalize the assignment of variables to
  3365. registers and stack locations. We map the first $k$ colors to the $k$
  3366. registers and the rest of the colors to stack locations. Suppose for
  3367. the moment that we have just one register to use for register
  3368. allocation, \key{rcx}. Then we have the following map from colors to
  3369. locations.
  3370. \[
  3371. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3372. \]
  3373. Composing this mapping with the coloring, we arrive at the following
  3374. assignment of variables to locations.
  3375. \begin{gather*}
  3376. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3377. \ttm{w} \mapsto \key{\%rcx}, \,
  3378. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3379. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3380. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3381. \ttm{t} \mapsto \key{\%rcx} \}
  3382. \end{gather*}
  3383. Adapt the code from the \code{assign-homes} pass
  3384. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3385. assigned location. Applying the above assignment to our running
  3386. example, on the left, yields the program on the right.
  3387. % why frame size of 32? -JGS
  3388. \begin{center}
  3389. \begin{minipage}{0.3\textwidth}
  3390. \begin{lstlisting}
  3391. movq $1, v
  3392. movq $42, w
  3393. movq v, x
  3394. addq $7, x
  3395. movq x, y
  3396. movq x, z
  3397. addq w, z
  3398. movq y, t
  3399. negq t
  3400. movq z, %rax
  3401. addq t, %rax
  3402. jmp conclusion
  3403. \end{lstlisting}
  3404. \end{minipage}
  3405. $\Rightarrow\qquad$
  3406. \begin{minipage}{0.45\textwidth}
  3407. \begin{lstlisting}
  3408. movq $1, -8(%rbp)
  3409. movq $42, %rcx
  3410. movq -8(%rbp), -8(%rbp)
  3411. addq $7, -8(%rbp)
  3412. movq -8(%rbp), -16(%rbp)
  3413. movq -8(%rbp), -8(%rbp)
  3414. addq %rcx, -8(%rbp)
  3415. movq -16(%rbp), %rcx
  3416. negq %rcx
  3417. movq -8(%rbp), %rax
  3418. addq %rcx, %rax
  3419. jmp conclusion
  3420. \end{lstlisting}
  3421. \end{minipage}
  3422. \end{center}
  3423. \begin{exercise}\normalfont
  3424. %
  3425. Implement the compiler pass \code{allocate-registers}.
  3426. %
  3427. Create five programs that exercise all of the register allocation
  3428. algorithm, including spilling variables to the stack.
  3429. %
  3430. Replace \code{assign-homes} in the list of \code{passes} in the
  3431. \code{run-tests.rkt} script with the three new passes:
  3432. \code{uncover-live}, \code{build-interference}, and
  3433. \code{allocate-registers}.
  3434. %
  3435. Temporarily remove the \code{print-x86} pass from the list of passes
  3436. and the call to \code{compiler-tests}.
  3437. %
  3438. Run the script to test the register allocator.
  3439. \end{exercise}
  3440. \section{Patch Instructions}
  3441. \label{sec:patch-instructions}
  3442. The remaining step in the compilation to x86 is to ensure that the
  3443. instructions have at most one argument that is a memory access.
  3444. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3445. is problematic. The fix is to first move \code{-8(\%rbp)}
  3446. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3447. %
  3448. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3449. problematic, but they can be fixed by simply deleting them. In
  3450. general, we recommend deleting all the trivial moves whose source and
  3451. destination are the same location.
  3452. %
  3453. The following is the output of \code{patch-instructions} on the
  3454. running example.
  3455. \begin{center}
  3456. \begin{minipage}{0.4\textwidth}
  3457. \begin{lstlisting}
  3458. movq $1, -8(%rbp)
  3459. movq $42, %rcx
  3460. movq -8(%rbp), -8(%rbp)
  3461. addq $7, -8(%rbp)
  3462. movq -8(%rbp), -16(%rbp)
  3463. movq -8(%rbp), -8(%rbp)
  3464. addq %rcx, -8(%rbp)
  3465. movq -16(%rbp), %rcx
  3466. negq %rcx
  3467. movq -8(%rbp), %rax
  3468. addq %rcx, %rax
  3469. jmp conclusion
  3470. \end{lstlisting}
  3471. \end{minipage}
  3472. $\Rightarrow\qquad$
  3473. \begin{minipage}{0.45\textwidth}
  3474. \begin{lstlisting}
  3475. movq $1, -8(%rbp)
  3476. movq $42, %rcx
  3477. addq $7, -8(%rbp)
  3478. movq -8(%rbp), %rax
  3479. movq %rax, -16(%rbp)
  3480. addq %rcx, -8(%rbp)
  3481. movq -16(%rbp), %rcx
  3482. negq %rcx
  3483. movq -8(%rbp), %rax
  3484. addq %rcx, %rax
  3485. jmp conclusion
  3486. \end{lstlisting}
  3487. \end{minipage}
  3488. \end{center}
  3489. \begin{exercise}\normalfont
  3490. %
  3491. Implement the \code{patch-instructions} compiler pass.
  3492. %
  3493. Insert it after \code{allocate-registers} in the list of \code{passes}
  3494. in the \code{run-tests.rkt} script.
  3495. %
  3496. Run the script to test the \code{patch-instructions} pass.
  3497. \end{exercise}
  3498. \section{Print x86}
  3499. \label{sec:print-x86-reg-alloc}
  3500. \index{subject}{calling conventions}
  3501. \index{subject}{prelude}\index{subject}{conclusion}
  3502. Recall that the \code{print-x86} pass generates the prelude and
  3503. conclusion instructions to satisfy the x86 calling conventions
  3504. (Section~\ref{sec:calling-conventions}). With the addition of the
  3505. register allocator, the callee-saved registers used by the register
  3506. allocator must be saved in the prelude and restored in the conclusion.
  3507. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3508. of \code{X86Program} named \code{used-callee} that stores the set of
  3509. callee-saved registers that were assigned to variables. The
  3510. \code{print-x86} pass can then access this information to decide which
  3511. callee-saved registers need to be saved and restored.
  3512. %
  3513. When calculating the size of the frame to adjust the \code{rsp} in the
  3514. prelude, make sure to take into account the space used for saving the
  3515. callee-saved registers. Also, don't forget that the frame needs to be
  3516. a multiple of 16 bytes!
  3517. An overview of all of the passes involved in register allocation is
  3518. shown in Figure~\ref{fig:reg-alloc-passes}.
  3519. \begin{figure}[tbp]
  3520. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3521. \node (Rvar) at (0,2) {\large \LangVar{}};
  3522. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3523. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3524. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3525. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3526. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3527. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3528. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3529. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3530. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3531. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3532. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3533. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3534. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3535. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3536. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3537. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3538. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3539. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3540. \end{tikzpicture}
  3541. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3542. \label{fig:reg-alloc-passes}
  3543. \end{figure}
  3544. \begin{exercise}\normalfont
  3545. Update the \code{print-x86} pass as described in this section.
  3546. %
  3547. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3548. list of passes and the call to \code{compiler-tests}.
  3549. %
  3550. Run the script to test the complete compiler for \LangVar{} that
  3551. performs register allocation.
  3552. \end{exercise}
  3553. \section{Challenge: Move Biasing}
  3554. \label{sec:move-biasing}
  3555. \index{subject}{move biasing}
  3556. This section describes an enhancement to the register allocator for
  3557. students looking for an extra challenge or who have a deeper interest
  3558. in register allocation.
  3559. To motivate the need for move biasing we return to the running example
  3560. but this time use all of the general purpose registers. So we have
  3561. the following mapping of color numbers to registers.
  3562. \[
  3563. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3564. \]
  3565. Using the same assignment of variables to color numbers that was
  3566. produced by the register allocator described in the last section, we
  3567. get the following program.
  3568. \begin{center}
  3569. \begin{minipage}{0.3\textwidth}
  3570. \begin{lstlisting}
  3571. movq $1, v
  3572. movq $42, w
  3573. movq v, x
  3574. addq $7, x
  3575. movq x, y
  3576. movq x, z
  3577. addq w, z
  3578. movq y, t
  3579. negq t
  3580. movq z, %rax
  3581. addq t, %rax
  3582. jmp conclusion
  3583. \end{lstlisting}
  3584. \end{minipage}
  3585. $\Rightarrow\qquad$
  3586. \begin{minipage}{0.45\textwidth}
  3587. \begin{lstlisting}
  3588. movq $1, %rdx
  3589. movq $42, %rcx
  3590. movq %rdx, %rdx
  3591. addq $7, %rdx
  3592. movq %rdx, %rsi
  3593. movq %rdx, %rdx
  3594. addq %rcx, %rdx
  3595. movq %rsi, %rcx
  3596. negq %rcx
  3597. movq %rdx, %rax
  3598. addq %rcx, %rax
  3599. jmp conclusion
  3600. \end{lstlisting}
  3601. \end{minipage}
  3602. \end{center}
  3603. In the above output code there are two \key{movq} instructions that
  3604. can be removed because their source and target are the same. However,
  3605. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3606. register, we could instead remove three \key{movq} instructions. We
  3607. can accomplish this by taking into account which variables appear in
  3608. \key{movq} instructions with which other variables.
  3609. We say that two variables $p$ and $q$ are \emph{move
  3610. related}\index{subject}{move related} if they participate together in a
  3611. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3612. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3613. for a variable, it should prefer a color that has already been used
  3614. for a move-related variable (assuming that they do not interfere). Of
  3615. course, this preference should not override the preference for
  3616. registers over stack locations. This preference should be used as a
  3617. tie breaker when choosing between registers or when choosing between
  3618. stack locations.
  3619. We recommend representing the move relationships in a graph, similar
  3620. to how we represented interference. The following is the \emph{move
  3621. graph} for our running example.
  3622. \[
  3623. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3624. \node (rax) at (0,0) {$\ttm{rax}$};
  3625. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3626. \node (t) at (0,2) {$\ttm{t}$};
  3627. \node (z) at (3,2) {$\ttm{z}$};
  3628. \node (x) at (6,2) {$\ttm{x}$};
  3629. \node (y) at (3,0) {$\ttm{y}$};
  3630. \node (w) at (6,0) {$\ttm{w}$};
  3631. \node (v) at (9,0) {$\ttm{v}$};
  3632. \draw (v) to (x);
  3633. \draw (x) to (y);
  3634. \draw (x) to (z);
  3635. \draw (y) to (t);
  3636. \end{tikzpicture}
  3637. \]
  3638. Now we replay the graph coloring, pausing to see the coloring of
  3639. \code{y}. Recall the following configuration. The most saturated vertices
  3640. were \code{w} and \code{y}.
  3641. \[
  3642. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3643. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3644. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3645. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3646. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3647. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3648. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3649. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3650. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3651. \draw (t1) to (rax);
  3652. \draw (t1) to (z);
  3653. \draw (z) to (y);
  3654. \draw (z) to (w);
  3655. \draw (x) to (w);
  3656. \draw (y) to (w);
  3657. \draw (v) to (w);
  3658. \draw (v) to (rsp);
  3659. \draw (w) to (rsp);
  3660. \draw (x) to (rsp);
  3661. \draw (y) to (rsp);
  3662. \path[-.,bend left=15] (z) edge node {} (rsp);
  3663. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3664. \draw (rax) to (rsp);
  3665. \end{tikzpicture}
  3666. \]
  3667. %
  3668. Last time we chose to color \code{w} with $0$. But this time we see
  3669. that \code{w} is not move related to any vertex, but \code{y} is move
  3670. related to \code{t}. So we choose to color \code{y} the same color as
  3671. \code{t}, $0$.
  3672. \[
  3673. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3674. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3675. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3676. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3677. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3678. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3679. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3680. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3681. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3682. \draw (t1) to (rax);
  3683. \draw (t1) to (z);
  3684. \draw (z) to (y);
  3685. \draw (z) to (w);
  3686. \draw (x) to (w);
  3687. \draw (y) to (w);
  3688. \draw (v) to (w);
  3689. \draw (v) to (rsp);
  3690. \draw (w) to (rsp);
  3691. \draw (x) to (rsp);
  3692. \draw (y) to (rsp);
  3693. \path[-.,bend left=15] (z) edge node {} (rsp);
  3694. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3695. \draw (rax) to (rsp);
  3696. \end{tikzpicture}
  3697. \]
  3698. Now \code{w} is the most saturated, so we color it $2$.
  3699. \[
  3700. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3701. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3702. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3703. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3704. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3705. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3706. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3707. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3708. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3709. \draw (t1) to (rax);
  3710. \draw (t1) to (z);
  3711. \draw (z) to (y);
  3712. \draw (z) to (w);
  3713. \draw (x) to (w);
  3714. \draw (y) to (w);
  3715. \draw (v) to (w);
  3716. \draw (v) to (rsp);
  3717. \draw (w) to (rsp);
  3718. \draw (x) to (rsp);
  3719. \draw (y) to (rsp);
  3720. \path[-.,bend left=15] (z) edge node {} (rsp);
  3721. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3722. \draw (rax) to (rsp);
  3723. \end{tikzpicture}
  3724. \]
  3725. At this point, vertices \code{x} and \code{v} are most saturated, but
  3726. \code{x} is move related to \code{y} and \code{z}, so we color
  3727. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3728. \[
  3729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3730. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3731. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3732. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3733. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3734. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3735. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3736. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3737. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3738. \draw (t1) to (rax);
  3739. \draw (t) to (z);
  3740. \draw (z) to (y);
  3741. \draw (z) to (w);
  3742. \draw (x) to (w);
  3743. \draw (y) to (w);
  3744. \draw (v) to (w);
  3745. \draw (v) to (rsp);
  3746. \draw (w) to (rsp);
  3747. \draw (x) to (rsp);
  3748. \draw (y) to (rsp);
  3749. \path[-.,bend left=15] (z) edge node {} (rsp);
  3750. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3751. \draw (rax) to (rsp);
  3752. \end{tikzpicture}
  3753. \]
  3754. So we have the following assignment of variables to registers.
  3755. \begin{gather*}
  3756. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3757. \ttm{w} \mapsto \key{\%rsi}, \,
  3758. \ttm{x} \mapsto \key{\%rcx}, \,
  3759. \ttm{y} \mapsto \key{\%rcx}, \,
  3760. \ttm{z} \mapsto \key{\%rdx}, \,
  3761. \ttm{t} \mapsto \key{\%rcx} \}
  3762. \end{gather*}
  3763. We apply this register assignment to the running example, on the left,
  3764. to obtain the code in the middle. The \code{patch-instructions} then
  3765. removes the three trivial moves to obtain the code on the right.
  3766. \begin{minipage}{0.25\textwidth}
  3767. \begin{lstlisting}
  3768. movq $1, v
  3769. movq $42, w
  3770. movq v, x
  3771. addq $7, x
  3772. movq x, y
  3773. movq x, z
  3774. addq w, z
  3775. movq y, t
  3776. negq t
  3777. movq z, %rax
  3778. addq t, %rax
  3779. jmp conclusion
  3780. \end{lstlisting}
  3781. \end{minipage}
  3782. $\Rightarrow\qquad$
  3783. \begin{minipage}{0.25\textwidth}
  3784. \begin{lstlisting}
  3785. movq $1, %rcx
  3786. movq $42, %rsi
  3787. movq %rcx, %rcx
  3788. addq $7, %rcx
  3789. movq %rcx, %rcx
  3790. movq %rcx, %rdx
  3791. addq %rsi, %rdx
  3792. movq %rcx, %rcx
  3793. negq %rcx
  3794. movq %rdx, %rax
  3795. addq %rcx, %rax
  3796. jmp conclusion
  3797. \end{lstlisting}
  3798. \end{minipage}
  3799. $\Rightarrow\qquad$
  3800. \begin{minipage}{0.25\textwidth}
  3801. \begin{lstlisting}
  3802. movq $1, %rcx
  3803. movq $42, %rsi
  3804. addq $7, %rcx
  3805. movq %rcx, %rdx
  3806. addq %rsi, %rdx
  3807. negq %rcx
  3808. movq %rdx, %rax
  3809. addq %rcx, %rax
  3810. jmp conclusion
  3811. \end{lstlisting}
  3812. \end{minipage}
  3813. \begin{exercise}\normalfont
  3814. Change your implementation of \code{allocate-registers} to take move
  3815. biasing into account. Create two new tests that include at least one
  3816. opportunity for move biasing and visually inspect the output x86
  3817. programs to make sure that your move biasing is working properly. Make
  3818. sure that your compiler still passes all of the tests.
  3819. \end{exercise}
  3820. %To do: another neat challenge would be to do
  3821. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  3822. %% \subsection{Output of the Running Example}
  3823. %% \label{sec:reg-alloc-output}
  3824. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3825. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3826. and move biasing. To demonstrate both the use of registers and the
  3827. stack, we have limited the register allocator to use just two
  3828. registers: \code{rbx} and \code{rcx}. In the prelude\index{subject}{prelude}
  3829. of the \code{main} function, we push \code{rbx} onto the stack because
  3830. it is a callee-saved register and it was assigned to variable by the
  3831. register allocator. We subtract \code{8} from the \code{rsp} at the
  3832. end of the prelude to reserve space for the one spilled variable.
  3833. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3834. Moving on the the \code{start} block, we see how the registers were
  3835. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3836. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3837. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3838. that the prelude saved the callee-save register \code{rbx} onto the
  3839. stack. The spilled variables must be placed lower on the stack than
  3840. the saved callee-save registers, so in this case \code{w} is placed at
  3841. \code{-16(\%rbp)}.
  3842. In the \code{conclusion}\index{subject}{conclusion}, we undo the work that was
  3843. done in the prelude. We move the stack pointer up by \code{8} bytes
  3844. (the room for spilled variables), then we pop the old values of
  3845. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3846. \code{retq} to return control to the operating system.
  3847. \begin{figure}[tbp]
  3848. % var_test_28.rkt
  3849. % (use-minimal-set-of-registers! #t)
  3850. % and only rbx rcx
  3851. % tmp 0 rbx
  3852. % z 1 rcx
  3853. % y 0 rbx
  3854. % w 2 16(%rbp)
  3855. % v 0 rbx
  3856. % x 0 rbx
  3857. \begin{lstlisting}
  3858. start:
  3859. movq $1, %rbx
  3860. movq $42, -16(%rbp)
  3861. addq $7, %rbx
  3862. movq %rbx, %rcx
  3863. addq -16(%rbp), %rcx
  3864. negq %rbx
  3865. movq %rcx, %rax
  3866. addq %rbx, %rax
  3867. jmp conclusion
  3868. .globl main
  3869. main:
  3870. pushq %rbp
  3871. movq %rsp, %rbp
  3872. pushq %rbx
  3873. subq $8, %rsp
  3874. jmp start
  3875. conclusion:
  3876. addq $8, %rsp
  3877. popq %rbx
  3878. popq %rbp
  3879. retq
  3880. \end{lstlisting}
  3881. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3882. \label{fig:running-example-x86}
  3883. \end{figure}
  3884. % challenge: prioritize variables based on execution frequencies
  3885. % and the number of uses of a variable
  3886. % challenge: enhance the coloring algorithm using Chaitin's
  3887. % approach of prioritizing high-degree variables
  3888. % by removing low-degree variables (coloring them later)
  3889. % from the interference graph
  3890. \section{Further Reading}
  3891. \label{sec:register-allocation-further-reading}
  3892. Early register allocation algorithms were developed for Fortran
  3893. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  3894. of graph coloring began in the late 1970s and early 1980s with the
  3895. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  3896. algorithm is based on the following observation of
  3897. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  3898. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  3899. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  3900. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  3901. different colors, but since there are less than $k$ of them, there
  3902. will be one or more colors left over to use for coloring $v$ in $G$.
  3903. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  3904. less than $k$ from the graph and recursively colors the rest of the
  3905. graph. Upon returning from the recursion, it colors $v$ with one of
  3906. the available colors and returns. \citet{Chaitin:1982vn} augments
  3907. this algorithm to handle spilling as follows. If there are no vertices
  3908. of degree lower than $k$ then pick a vertex at random, spill it,
  3909. remove it from the graph, and proceed recursively to color the rest of
  3910. the graph.
  3911. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  3912. move-related and that don't interfere with each other, a process
  3913. called \emph{coalescing}. While coalescing decreases the number of
  3914. moves, it can make the graph more difficult to
  3915. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  3916. which two variables are merged only if they have fewer than $k$
  3917. neighbors of high degree. \citet{George:1996aa} observe that
  3918. conservative coalescing is sometimes too conservative and make it more
  3919. aggressive by iterating the coalescing with the removal of low-degree
  3920. vertices.
  3921. %
  3922. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  3923. also propose \emph{biased coloring} in which a variable is assigned to
  3924. the same color as another move-related variable if possible, as
  3925. discussed in Section~\ref{sec:move-biasing}.
  3926. %
  3927. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  3928. performs coalescing, graph coloring, and spill code insertion until
  3929. all variables have been assigned a location.
  3930. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  3931. spills variables that don't have to be: a high-degree variable can be
  3932. colorable if many of its neighbors are assigned the same color.
  3933. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  3934. high-degree vertex is not immediately spilled. Instead the decision is
  3935. deferred until after the recursive call, at which point it is apparent
  3936. whether there is actually an available color or not. We observe that
  3937. this algorithm is equivalent to the smallest-last ordering
  3938. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  3939. be registers and the rest to be stack locations.
  3940. %% biased coloring
  3941. Earlier editions of the compiler course at Indiana University
  3942. \citep{Dybvig:2010aa} were based on the algorithm of
  3943. \citet{Briggs:1994kx}.
  3944. The smallest-last ordering algorithm is one of many \emph{greedy}
  3945. coloring algorithms. A greedy coloring algorithm visits all the
  3946. vertices in a particular order and assigns each one the first
  3947. available color. An \emph{offline} greedy algorithm chooses the
  3948. ordering up-front, prior to assigning colors. The algorithm of
  3949. \citet{Chaitin:1981vl} should be considered offline because the vertex
  3950. ordering does not depend on the colors assigned, so the algorithm
  3951. could be split into two phases. Other orderings are possible. For
  3952. example, \citet{Chow:1984ys} order variables according an estimate of
  3953. runtime cost.
  3954. An \emph{online} greedy coloring algorithm uses information about the
  3955. current assignment of colors to influence the order in which the
  3956. remaining vertices are colored. The saturation-based algorithm
  3957. described in this chapter is one such algorithm. We choose to use
  3958. saturation-based coloring is because it is fun to introduce graph
  3959. coloring via Sudoku.
  3960. A register allocator may choose to map each variable to just one
  3961. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  3962. variable to one or more locations. The later can be achieved by
  3963. \emph{live range splitting}, where a variable is replaced by several
  3964. variables that each handle part of its live
  3965. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  3966. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  3967. %% replacement algorithm, bottom-up local
  3968. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  3969. %% Cooper: top-down (priority bassed), bottom-up
  3970. %% top-down
  3971. %% order variables by priority (estimated cost)
  3972. %% caveat: split variables into two groups:
  3973. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  3974. %% color the constrained ones first
  3975. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  3976. %% cite J. Cocke for an algorithm that colors variables
  3977. %% in a high-degree first ordering
  3978. %Register Allocation via Usage Counts, Freiburghouse CACM
  3979. \citet{Palsberg:2007si} observe that many of the interference graphs
  3980. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  3981. that is, every cycle with four or more edges has an edge which is not
  3982. part of the cycle but which connects two vertices on the cycle. Such
  3983. graphs can be optimally colored by the greedy algorithm with a vertex
  3984. ordering determined by maximum cardinality search.
  3985. In situations where compile time is of utmost importance, such as in
  3986. just-in-time compilers, graph coloring algorithms can be too expensive
  3987. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  3988. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3989. \chapter{Booleans and Control Flow}
  3990. \label{ch:Rif}
  3991. \index{subject}{Boolean}
  3992. \index{subject}{control flow}
  3993. \index{subject}{conditional expression}
  3994. The \LangInt{} and \LangVar{} languages only have a single kind of
  3995. value, integers. In this chapter we add a second kind of value, the
  3996. Booleans, to create the \LangIf{} language. The Boolean values
  3997. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  3998. respectively in Racket. The \LangIf{} language includes several
  3999. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4000. \key{<}, etc.) and the conditional \key{if} expression. With the
  4001. addition of \key{if}, programs can have non-trivial control flow which
  4002. impacts \code{explicate-control} and liveness analysis. Also, because
  4003. we now have two kinds of values, we need to handle programs that apply
  4004. an operation to the wrong kind of value, such as \code{(not 1)}.
  4005. There are two language design options for such situations. One option
  4006. is to signal an error and the other is to provide a wider
  4007. interpretation of the operation. The Racket language uses a mixture of
  4008. these two options, depending on the operation and the kind of
  4009. value. For example, the result of \code{(not 1)} in Racket is
  4010. \code{\#f} because Racket treats non-zero integers as if they were
  4011. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4012. error in Racket because \code{car} expects a pair.
  4013. Typed Racket makes similar design choices as Racket, except much of
  4014. the error detection happens at compile time instead of run time. Typed
  4015. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4016. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4017. because Typed Racket expects the type of the argument to be of the
  4018. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4019. The \LangIf{} language performs type checking during compilation like
  4020. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4021. alternative choice, that is, a dynamically typed language like Racket.
  4022. The \LangIf{} language is a subset of Typed Racket; for some
  4023. operations we are more restrictive, for example, rejecting
  4024. \code{(not 1)}.
  4025. This chapter is organized as follows. We begin by defining the syntax
  4026. and interpreter for the \LangIf{} language
  4027. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4028. checking and build a type checker for \LangIf{}
  4029. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4030. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4031. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4032. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4033. discuss how our compiler passes change to accommodate Booleans and
  4034. conditional control flow. There is one new pass, named \code{shrink},
  4035. that translates some operators into others, thereby reducing the
  4036. number of operators that need to be handled in later passes. The
  4037. largest changes occur in \code{explicate-control}, to translate
  4038. \code{if} expressions into control-flow graphs
  4039. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4040. allocation, the liveness analysis now has multiple basic blocks to
  4041. process and there is the interesting question of how to handle
  4042. conditional jumps.
  4043. \section{The \LangIf{} Language}
  4044. \label{sec:lang-if}
  4045. The concrete syntax of the \LangIf{} language is defined in
  4046. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4047. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4048. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4049. \code{\#f}, and the conditional \code{if} expression. We expand the
  4050. operators to include
  4051. \begin{enumerate}
  4052. \item subtraction on integers,
  4053. \item the logical operators \key{and}, \key{or} and \key{not},
  4054. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4055. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4056. comparing integers.
  4057. \end{enumerate}
  4058. We reorganize the abstract syntax for the primitive operations in
  4059. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4060. them. This means that the grammar no longer checks whether the arity
  4061. of an operators matches the number of arguments. That responsibility
  4062. is moved to the type checker for \LangIf{}, which we introduce in
  4063. Section~\ref{sec:type-check-Rif}.
  4064. \begin{figure}[tp]
  4065. \centering
  4066. \fbox{
  4067. \begin{minipage}{0.96\textwidth}
  4068. \[
  4069. \begin{array}{lcl}
  4070. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4071. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4072. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4073. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4074. &\mid& \itm{bool}
  4075. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4076. \mid (\key{not}\;\Exp) \\
  4077. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4078. \LangIfM{} &::=& \Exp
  4079. \end{array}
  4080. \]
  4081. \end{minipage}
  4082. }
  4083. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4084. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  4085. \label{fig:Rif-concrete-syntax}
  4086. \end{figure}
  4087. \begin{figure}[tp]
  4088. \centering
  4089. \fbox{
  4090. \begin{minipage}{0.96\textwidth}
  4091. \[
  4092. \begin{array}{lcl}
  4093. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4094. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4095. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4096. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4097. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4098. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4099. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4100. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4101. \end{array}
  4102. \]
  4103. \end{minipage}
  4104. }
  4105. \caption{The abstract syntax of \LangIf{}.}
  4106. \label{fig:Rif-syntax}
  4107. \end{figure}
  4108. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4109. which inherits from the interpreter for \LangVar{}
  4110. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4111. evaluate to the corresponding Boolean values. The conditional
  4112. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4113. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4114. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4115. operations \code{not} and \code{and} behave as you might expect, but
  4116. note that the \code{and} operation is short-circuiting. That is, given
  4117. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4118. evaluated if $e_1$ evaluates to \code{\#f}.
  4119. With the increase in the number of primitive operations, the
  4120. interpreter would become repetitive without some care. We refactor
  4121. the case for \code{Prim}, moving the code that differs with each
  4122. operation into the \code{interp-op} method shown in in
  4123. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4124. separately because of its short-circuiting behavior.
  4125. \begin{figure}[tbp]
  4126. \begin{lstlisting}
  4127. (define interp-Rif-class
  4128. (class interp-Rvar-class
  4129. (super-new)
  4130. (define/public (interp-op op) ...)
  4131. (define/override ((interp-exp env) e)
  4132. (define recur (interp-exp env))
  4133. (match e
  4134. [(Bool b) b]
  4135. [(If cnd thn els)
  4136. (match (recur cnd)
  4137. [#t (recur thn)]
  4138. [#f (recur els)])]
  4139. [(Prim 'and (list e1 e2))
  4140. (match (recur e1)
  4141. [#t (match (recur e2) [#t #t] [#f #f])]
  4142. [#f #f])]
  4143. [(Prim op args)
  4144. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4145. [else ((super interp-exp env) e)]))
  4146. ))
  4147. (define (interp-Rif p)
  4148. (send (new interp-Rif-class) interp-program p))
  4149. \end{lstlisting}
  4150. \caption{Interpreter for the \LangIf{} language. (See
  4151. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4152. \label{fig:interp-Rif}
  4153. \end{figure}
  4154. \begin{figure}[tbp]
  4155. \begin{lstlisting}
  4156. (define/public (interp-op op)
  4157. (match op
  4158. ['+ fx+]
  4159. ['- fx-]
  4160. ['read read-fixnum]
  4161. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4162. ['or (lambda (v1 v2)
  4163. (cond [(and (boolean? v1) (boolean? v2))
  4164. (or v1 v2)]))]
  4165. ['eq? (lambda (v1 v2)
  4166. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4167. (and (boolean? v1) (boolean? v2))
  4168. (and (vector? v1) (vector? v2)))
  4169. (eq? v1 v2)]))]
  4170. ['< (lambda (v1 v2)
  4171. (cond [(and (fixnum? v1) (fixnum? v2))
  4172. (< v1 v2)]))]
  4173. ['<= (lambda (v1 v2)
  4174. (cond [(and (fixnum? v1) (fixnum? v2))
  4175. (<= v1 v2)]))]
  4176. ['> (lambda (v1 v2)
  4177. (cond [(and (fixnum? v1) (fixnum? v2))
  4178. (> v1 v2)]))]
  4179. ['>= (lambda (v1 v2)
  4180. (cond [(and (fixnum? v1) (fixnum? v2))
  4181. (>= v1 v2)]))]
  4182. [else (error 'interp-op "unknown operator")]))
  4183. \end{lstlisting}
  4184. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4185. \label{fig:interp-op-Rif}
  4186. \end{figure}
  4187. \section{Type Checking \LangIf{} Programs}
  4188. \label{sec:type-check-Rif}
  4189. \index{subject}{type checking}
  4190. \index{subject}{semantic analysis}
  4191. It is helpful to think about type checking in two complementary
  4192. ways. A type checker predicts the type of value that will be produced
  4193. by each expression in the program. For \LangIf{}, we have just two types,
  4194. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4195. \begin{lstlisting}
  4196. (+ 10 (- (+ 12 20)))
  4197. \end{lstlisting}
  4198. produces an \key{Integer} while
  4199. \begin{lstlisting}
  4200. (and (not #f) #t)
  4201. \end{lstlisting}
  4202. produces a \key{Boolean}.
  4203. Another way to think about type checking is that it enforces a set of
  4204. rules about which operators can be applied to which kinds of
  4205. values. For example, our type checker for \LangIf{} signals an error
  4206. for the below expression
  4207. \begin{lstlisting}
  4208. (not (+ 10 (- (+ 12 20))))
  4209. \end{lstlisting}
  4210. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4211. but the type checker enforces the rule that the argument of \code{not}
  4212. must be a \key{Boolean}.
  4213. We implement type checking using classes and methods because they
  4214. provide the open recursion needed to reuse code as we extend the type
  4215. checker in later chapters, analogous to the use of classes and methods
  4216. for the interpreters (Section~\ref{sec:extensible-interp}).
  4217. We separate the type checker for the \LangVar{} fragment into its own
  4218. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4219. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4220. from the type checker for \LangVar{}. These type checkers are in the
  4221. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4222. support code.
  4223. %
  4224. Each type checker is a structurally recursive function over the AST.
  4225. Given an input expression \code{e}, the type checker either signals an
  4226. error or returns an expression and its type (\key{Integer} or
  4227. \key{Boolean}). It returns an expression because there are situations
  4228. in which we want to change or update the expression.
  4229. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4230. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4231. \code{Integer}. To handle variables, the type checker uses the
  4232. environment \code{env} to map variables to types. Consider the case
  4233. for \key{let}. We type check the initializing expression to obtain
  4234. its type \key{T} and then associate type \code{T} with the variable
  4235. \code{x} in the environment used to type check the body of the
  4236. \key{let}. Thus, when the type checker encounters a use of variable
  4237. \code{x}, it can find its type in the environment. Regarding
  4238. primitive operators, we recursively analyze the arguments and then
  4239. invoke \code{type-check-op} to check whether the argument types are
  4240. allowed.
  4241. Several auxiliary methods are used in the type checker. The method
  4242. \code{operator-types} defines a dictionary that maps the operator
  4243. names to their parameter and return types. The \code{type-equal?}
  4244. method determines whether two types are equal, which for now simply
  4245. dispatches to \code{equal?} (deep equality). The
  4246. \code{check-type-equal?} method triggers an error if the two types are
  4247. not equal. The \code{type-check-op} method looks up the operator in
  4248. the \code{operator-types} dictionary and then checks whether the
  4249. argument types are equal to the parameter types. The result is the
  4250. return type of the operator.
  4251. \begin{figure}[tbp]
  4252. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4253. (define type-check-Rvar-class
  4254. (class object%
  4255. (super-new)
  4256. (define/public (operator-types)
  4257. '((+ . ((Integer Integer) . Integer))
  4258. (- . ((Integer) . Integer))
  4259. (read . (() . Integer))))
  4260. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4261. (define/public (check-type-equal? t1 t2 e)
  4262. (unless (type-equal? t1 t2)
  4263. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4264. (define/public (type-check-op op arg-types e)
  4265. (match (dict-ref (operator-types) op)
  4266. [`(,param-types . ,return-type)
  4267. (for ([at arg-types] [pt param-types])
  4268. (check-type-equal? at pt e))
  4269. return-type]
  4270. [else (error 'type-check-op "unrecognized ~a" op)]))
  4271. (define/public (type-check-exp env)
  4272. (lambda (e)
  4273. (match e
  4274. [(Int n) (values (Int n) 'Integer)]
  4275. [(Var x) (values (Var x) (dict-ref env x))]
  4276. [(Let x e body)
  4277. (define-values (e^ Te) ((type-check-exp env) e))
  4278. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4279. (values (Let x e^ b) Tb)]
  4280. [(Prim op es)
  4281. (define-values (new-es ts)
  4282. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4283. (values (Prim op new-es) (type-check-op op ts e))]
  4284. [else (error 'type-check-exp "couldn't match" e)])))
  4285. (define/public (type-check-program e)
  4286. (match e
  4287. [(Program info body)
  4288. (define-values (body^ Tb) ((type-check-exp '()) body))
  4289. (check-type-equal? Tb 'Integer body)
  4290. (Program info body^)]
  4291. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4292. ))
  4293. (define (type-check-Rvar p)
  4294. (send (new type-check-Rvar-class) type-check-program p))
  4295. \end{lstlisting}
  4296. \caption{Type checker for the \LangVar{} language.}
  4297. \label{fig:type-check-Rvar}
  4298. \end{figure}
  4299. \begin{figure}[tbp]
  4300. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4301. (define type-check-Rif-class
  4302. (class type-check-Rvar-class
  4303. (super-new)
  4304. (inherit check-type-equal?)
  4305. (define/override (operator-types)
  4306. (append '((- . ((Integer Integer) . Integer))
  4307. (and . ((Boolean Boolean) . Boolean))
  4308. (or . ((Boolean Boolean) . Boolean))
  4309. (< . ((Integer Integer) . Boolean))
  4310. (<= . ((Integer Integer) . Boolean))
  4311. (> . ((Integer Integer) . Boolean))
  4312. (>= . ((Integer Integer) . Boolean))
  4313. (not . ((Boolean) . Boolean))
  4314. )
  4315. (super operator-types)))
  4316. (define/override (type-check-exp env)
  4317. (lambda (e)
  4318. (match e
  4319. [(Prim 'eq? (list e1 e2))
  4320. (define-values (e1^ T1) ((type-check-exp env) e1))
  4321. (define-values (e2^ T2) ((type-check-exp env) e2))
  4322. (check-type-equal? T1 T2 e)
  4323. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4324. [(Bool b) (values (Bool b) 'Boolean)]
  4325. [(If cnd thn els)
  4326. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4327. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4328. (define-values (els^ Te) ((type-check-exp env) els))
  4329. (check-type-equal? Tc 'Boolean e)
  4330. (check-type-equal? Tt Te e)
  4331. (values (If cnd^ thn^ els^) Te)]
  4332. [else ((super type-check-exp env) e)])))
  4333. ))
  4334. (define (type-check-Rif p)
  4335. (send (new type-check-Rif-class) type-check-program p))
  4336. \end{lstlisting}
  4337. \caption{Type checker for the \LangIf{} language.}
  4338. \label{fig:type-check-Rif}
  4339. \end{figure}
  4340. Next we discuss the type checker for \LangIf{} in
  4341. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4342. two arguments to have the same type. The type of a Boolean constant is
  4343. \code{Boolean}. The condition of an \code{if} must be of
  4344. \code{Boolean} type and the two branches must have the same type. The
  4345. \code{operator-types} function adds dictionary entries for the other
  4346. new operators.
  4347. \begin{exercise}\normalfont
  4348. Create 10 new test programs in \LangIf{}. Half of the programs should
  4349. have a type error. For those programs, create an empty file with the
  4350. same base name but with file extension \code{.tyerr}. For example, if
  4351. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4352. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4353. \code{interp-tests} and \code{compiler-tests} that a type error is
  4354. expected. The other half of the test programs should not have type
  4355. errors.
  4356. In the \code{run-tests.rkt} script, change the second argument of
  4357. \code{interp-tests} and \code{compiler-tests} to
  4358. \code{type-check-Rif}, which causes the type checker to run prior to
  4359. the compiler passes. Temporarily change the \code{passes} to an empty
  4360. list and run the script, thereby checking that the new test programs
  4361. either type check or not as intended.
  4362. \end{exercise}
  4363. \section{The \LangCIf{} Intermediate Language}
  4364. \label{sec:Cif}
  4365. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4366. \LangCIf{} intermediate language. (The concrete syntax is in the
  4367. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4368. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4369. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4370. \key{\#f} to the \Arg{} non-terminal.
  4371. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4372. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4373. statement is a comparison operation and the branches are \code{goto}
  4374. statements, making it straightforward to compile \code{if} statements
  4375. to x86.
  4376. \begin{figure}[tp]
  4377. \fbox{
  4378. \begin{minipage}{0.96\textwidth}
  4379. \small
  4380. \[
  4381. \begin{array}{lcl}
  4382. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4383. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4384. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4385. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4386. &\mid& \UNIOP{\key{'not}}{\Atm}
  4387. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4388. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4389. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4390. \mid \GOTO{\itm{label}} \\
  4391. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4392. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4393. \end{array}
  4394. \]
  4395. \end{minipage}
  4396. }
  4397. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4398. (Figure~\ref{fig:c0-syntax}).}
  4399. \label{fig:c1-syntax}
  4400. \end{figure}
  4401. \section{The \LangXIf{} Language}
  4402. \label{sec:x86-if}
  4403. \index{subject}{x86} To implement the new logical operations, the comparison
  4404. operations, and the \key{if} expression, we need to delve further into
  4405. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4406. define the concrete and abstract syntax for the \LangXIf{} subset
  4407. of x86, which includes instructions for logical operations,
  4408. comparisons, and conditional jumps.
  4409. One challenge is that x86 does not provide an instruction that
  4410. directly implements logical negation (\code{not} in \LangIf{} and
  4411. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4412. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4413. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4414. bit of its arguments, and writes the results into its second argument.
  4415. Recall the truth table for exclusive-or:
  4416. \begin{center}
  4417. \begin{tabular}{l|cc}
  4418. & 0 & 1 \\ \hline
  4419. 0 & 0 & 1 \\
  4420. 1 & 1 & 0
  4421. \end{tabular}
  4422. \end{center}
  4423. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4424. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4425. for the bit $1$, the result is the opposite of the second bit. Thus,
  4426. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4427. the first argument:
  4428. \[
  4429. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4430. \qquad\Rightarrow\qquad
  4431. \begin{array}{l}
  4432. \key{movq}~ \Arg\key{,} \Var\\
  4433. \key{xorq}~ \key{\$1,} \Var
  4434. \end{array}
  4435. \]
  4436. \begin{figure}[tp]
  4437. \fbox{
  4438. \begin{minipage}{0.96\textwidth}
  4439. \[
  4440. \begin{array}{lcl}
  4441. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4442. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4443. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4444. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4445. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4446. \key{subq} \; \Arg\key{,} \Arg \mid
  4447. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4448. && \gray{ \key{callq} \; \itm{label} \mid
  4449. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4450. && \gray{ \itm{label}\key{:}\; \Instr }
  4451. \mid \key{xorq}~\Arg\key{,}~\Arg
  4452. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4453. && \key{set}cc~\Arg
  4454. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4455. \mid \key{j}cc~\itm{label}
  4456. \\
  4457. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  4458. & & \gray{ \key{main:} \; \Instr\ldots }
  4459. \end{array}
  4460. \]
  4461. \end{minipage}
  4462. }
  4463. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4464. \label{fig:x86-1-concrete}
  4465. \end{figure}
  4466. \begin{figure}[tp]
  4467. \fbox{
  4468. \begin{minipage}{0.98\textwidth}
  4469. \small
  4470. \[
  4471. \begin{array}{lcl}
  4472. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4473. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4474. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4475. \mid \BYTEREG{\itm{bytereg}} \\
  4476. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4477. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4478. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4479. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4480. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4481. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4482. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4483. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4484. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4485. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4486. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4487. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4488. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4489. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4490. \end{array}
  4491. \]
  4492. \end{minipage}
  4493. }
  4494. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4495. \label{fig:x86-1}
  4496. \end{figure}
  4497. Next we consider the x86 instructions that are relevant for compiling
  4498. the comparison operations. The \key{cmpq} instruction compares its two
  4499. arguments to determine whether one argument is less than, equal, or
  4500. greater than the other argument. The \key{cmpq} instruction is unusual
  4501. regarding the order of its arguments and where the result is
  4502. placed. The argument order is backwards: if you want to test whether
  4503. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4504. \key{cmpq} is placed in the special EFLAGS register. This register
  4505. cannot be accessed directly but it can be queried by a number of
  4506. instructions, including the \key{set} instruction. The instruction
  4507. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4508. depending on whether the comparison comes out according to the
  4509. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4510. for less-or-equal, \key{g} for greater, \key{ge} for
  4511. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4512. that its destination argument must be single byte register, such as
  4513. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4514. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4515. instruction can be used to move from a single byte register to a
  4516. normal 64-bit register. The abstract syntax for the \code{set}
  4517. instruction differs from the concrete syntax in that it separates the
  4518. instruction name from the condition code.
  4519. The x86 instruction for conditional jump is relevant to the
  4520. compilation of \key{if} expressions. The instruction
  4521. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4522. the instruction after \itm{label} depending on whether the result in
  4523. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4524. jump instruction falls through to the next instruction. Like the
  4525. abstract syntax for \code{set}, the abstract syntax for conditional
  4526. jump separates the instruction name from the condition code. For
  4527. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4528. the conditional jump instruction relies on the EFLAGS register, it is
  4529. common for it to be immediately preceded by a \key{cmpq} instruction
  4530. to set the EFLAGS register.
  4531. \section{Shrink the \LangIf{} Language}
  4532. \label{sec:shrink-Rif}
  4533. The \LangIf{} language includes several operators that are easily
  4534. expressible with other operators. For example, subtraction is
  4535. expressible using addition and negation.
  4536. \[
  4537. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4538. \]
  4539. Several of the comparison operations are expressible using less-than
  4540. and logical negation.
  4541. \[
  4542. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4543. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4544. \]
  4545. The \key{let} is needed in the above translation to ensure that
  4546. expression $e_1$ is evaluated before $e_2$.
  4547. By performing these translations in the front-end of the compiler, the
  4548. later passes of the compiler do not need to deal with these operators,
  4549. making the passes shorter.
  4550. %% On the other hand, sometimes
  4551. %% these translations make it more difficult to generate the most
  4552. %% efficient code with respect to the number of instructions. However,
  4553. %% these differences typically do not affect the number of accesses to
  4554. %% memory, which is the primary factor that determines execution time on
  4555. %% modern computer architectures.
  4556. \begin{exercise}\normalfont
  4557. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4558. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4559. translating them to other constructs in \LangIf{}.
  4560. %
  4561. Create six test programs that involve these operators.
  4562. %
  4563. In the \code{run-tests.rkt} script, add the following entry for
  4564. \code{shrink} to the list of passes (it should be the only pass at
  4565. this point).
  4566. \begin{lstlisting}
  4567. (list "shrink" shrink interp-Rif type-check-Rif)
  4568. \end{lstlisting}
  4569. This instructs \code{interp-tests} to run the intepreter
  4570. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4571. output of \code{shrink}.
  4572. %
  4573. Run the script to test your compiler on all the test programs.
  4574. \end{exercise}
  4575. \section{Uniquify Variables}
  4576. \label{sec:uniquify-Rif}
  4577. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4578. \code{if} expressions.
  4579. \begin{exercise}\normalfont
  4580. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4581. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4582. \begin{lstlisting}
  4583. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4584. \end{lstlisting}
  4585. Run the script to test your compiler.
  4586. \end{exercise}
  4587. \section{Remove Complex Operands}
  4588. \label{sec:remove-complex-opera-Rif}
  4589. The output language for this pass is \LangIfANF{}
  4590. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4591. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4592. \code{If} is not. All three sub-expressions of an \code{If} are
  4593. allowed to be complex expressions but the operands of \code{not} and
  4594. the comparisons must be atoms.
  4595. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4596. \code{rco-atom} functions according to whether the output needs to be
  4597. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4598. Regarding \code{If}, it is particularly important to \textbf{not}
  4599. replace its condition with a temporary variable because that would
  4600. interfere with the generation of high-quality output in the
  4601. \code{explicate-control} pass.
  4602. \begin{figure}[tp]
  4603. \centering
  4604. \fbox{
  4605. \begin{minipage}{0.96\textwidth}
  4606. \[
  4607. \begin{array}{rcl}
  4608. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4609. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4610. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4611. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4612. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4613. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4614. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4615. \end{array}
  4616. \]
  4617. \end{minipage}
  4618. }
  4619. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4620. \label{fig:Rif-anf-syntax}
  4621. \end{figure}
  4622. \begin{exercise}\normalfont
  4623. %
  4624. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4625. and \code{rco-exp} functions in \code{compiler.rkt}.
  4626. %
  4627. Create three new \LangInt{} programs that exercise the interesting
  4628. code in this pass.
  4629. %
  4630. In the \code{run-tests.rkt} script, add the following entry to the
  4631. list of \code{passes} and then run the script to test your compiler.
  4632. \begin{lstlisting}
  4633. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4634. \end{lstlisting}
  4635. \end{exercise}
  4636. \section{Explicate Control}
  4637. \label{sec:explicate-control-Rif}
  4638. Recall that the purpose of \code{explicate-control} is to make the
  4639. order of evaluation explicit in the syntax of the program. With the
  4640. addition of \key{if} this get more interesting.
  4641. As a motivating example, consider the following program that has an
  4642. \key{if} expression nested in the predicate of another \key{if}.
  4643. % cond_test_41.rkt
  4644. \begin{center}
  4645. \begin{minipage}{0.96\textwidth}
  4646. \begin{lstlisting}
  4647. (let ([x (read)])
  4648. (let ([y (read)])
  4649. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4650. (+ y 2)
  4651. (+ y 10))))
  4652. \end{lstlisting}
  4653. \end{minipage}
  4654. \end{center}
  4655. %
  4656. The naive way to compile \key{if} and the comparison would be to
  4657. handle each of them in isolation, regardless of their context. Each
  4658. comparison would be translated into a \key{cmpq} instruction followed
  4659. by a couple instructions to move the result from the EFLAGS register
  4660. into a general purpose register or stack location. Each \key{if} would
  4661. be translated into a \key{cmpq} instruction followed by a conditional
  4662. jump. The generated code for the inner \key{if} in the above example
  4663. would be as follows.
  4664. \begin{center}
  4665. \begin{minipage}{0.96\textwidth}
  4666. \begin{lstlisting}
  4667. ...
  4668. cmpq $1, x ;; (< x 1)
  4669. setl %al
  4670. movzbq %al, tmp
  4671. cmpq $1, tmp ;; (if ...)
  4672. je then_branch_1
  4673. jmp else_branch_1
  4674. ...
  4675. \end{lstlisting}
  4676. \end{minipage}
  4677. \end{center}
  4678. However, if we take context into account we can do better and reduce
  4679. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4680. Our goal will be compile \key{if} expressions so that the relevant
  4681. comparison instruction appears directly before the conditional jump.
  4682. For example, we want to generate the following code for the inner
  4683. \code{if}.
  4684. \begin{center}
  4685. \begin{minipage}{0.96\textwidth}
  4686. \begin{lstlisting}
  4687. ...
  4688. cmpq $1, x
  4689. je then_branch_1
  4690. jmp else_branch_1
  4691. ...
  4692. \end{lstlisting}
  4693. \end{minipage}
  4694. \end{center}
  4695. One way to achieve this is to reorganize the code at the level of
  4696. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4697. the following code.
  4698. \begin{center}
  4699. \begin{minipage}{0.96\textwidth}
  4700. \begin{lstlisting}
  4701. (let ([x (read)])
  4702. (let ([y (read)])
  4703. (if (< x 1)
  4704. (if (eq? x 0)
  4705. (+ y 2)
  4706. (+ y 10))
  4707. (if (eq? x 2)
  4708. (+ y 2)
  4709. (+ y 10)))))
  4710. \end{lstlisting}
  4711. \end{minipage}
  4712. \end{center}
  4713. Unfortunately, this approach duplicates the two branches from the
  4714. outer \code{if} and a compiler must never duplicate code!
  4715. We need a way to perform the above transformation but without
  4716. duplicating code. That is, we need a way for different parts of a
  4717. program to refer to the same piece of code. At the level of x86
  4718. assembly this is straightforward because we can label the code for
  4719. each branch and insert jumps in all the places that need to execute
  4720. the branch. In our intermediate language, we need to move away from
  4721. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4722. particular, we use a standard program representation called a
  4723. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4724. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  4725. labeled sequence of code, called a \emph{basic block}, and each edge
  4726. represents a jump to another block. The \key{CProgram} construct of
  4727. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4728. as an alist mapping labels to basic blocks. Each basic block is
  4729. represented by the $\Tail$ non-terminal.
  4730. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4731. \code{remove-complex-opera*} pass and then the
  4732. \code{explicate-control} pass on the example program. We walk through
  4733. the output program and then discuss the algorithm.
  4734. %
  4735. Following the order of evaluation in the output of
  4736. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4737. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4738. inner \key{if}. In the output of \code{explicate-control}, in the
  4739. block labeled \code{start}, is two assignment statements followed by a
  4740. \code{if} statement that branches to \code{block40} or
  4741. \code{block41}. The blocks associated with those labels contain the
  4742. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4743. respectively. In particular, we start \code{block40} with the
  4744. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4745. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4746. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4747. \code{block41} is similar.
  4748. \begin{figure}[tbp]
  4749. \begin{tabular}{lll}
  4750. \begin{minipage}{0.4\textwidth}
  4751. % cond_test_41.rkt
  4752. \begin{lstlisting}
  4753. (let ([x (read)])
  4754. (let ([y (read)])
  4755. (if (if (< x 1)
  4756. (eq? x 0)
  4757. (eq? x 2))
  4758. (+ y 2)
  4759. (+ y 10))))
  4760. \end{lstlisting}
  4761. \hspace{40pt}$\Downarrow$
  4762. \begin{lstlisting}
  4763. (let ([x (read)])
  4764. (let ([y (read)])
  4765. (if (if (< x 1)
  4766. (eq? x 0)
  4767. (eq? x 2))
  4768. (+ y 2)
  4769. (+ y 10))))
  4770. \end{lstlisting}
  4771. \end{minipage}
  4772. &
  4773. $\Rightarrow$
  4774. &
  4775. \begin{minipage}{0.55\textwidth}
  4776. \begin{lstlisting}
  4777. start:
  4778. x = (read);
  4779. y = (read);
  4780. if (< x 1) goto block40;
  4781. else goto block41;
  4782. block40:
  4783. if (eq? x 0) goto block38;
  4784. else goto block39;
  4785. block41:
  4786. if (eq? x 2) goto block38;
  4787. else goto block39;
  4788. block38:
  4789. return (+ y 2);
  4790. block39:
  4791. return (+ y 10);
  4792. \end{lstlisting}
  4793. \end{minipage}
  4794. \end{tabular}
  4795. \caption{Translation from \LangIf{} to \LangCIf{}
  4796. via the \code{explicate-control}.}
  4797. \label{fig:explicate-control-s1-38}
  4798. \end{figure}
  4799. %% The nice thing about the output of \code{explicate-control} is that
  4800. %% there are no unnecessary comparisons and every comparison is part of a
  4801. %% conditional jump.
  4802. %% The down-side of this output is that it includes
  4803. %% trivial blocks, such as the blocks labeled \code{block92} through
  4804. %% \code{block95}, that only jump to another block. We discuss a solution
  4805. %% to this problem in Section~\ref{sec:opt-jumps}.
  4806. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4807. \code{explicate-control} for \LangVar{} using two mutually recursive
  4808. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4809. former function translates expressions in tail position whereas the
  4810. later function translates expressions on the right-hand-side of a
  4811. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4812. have a new kind of position to deal with: the predicate position of
  4813. the \key{if}. We need another function, \code{explicate-pred}, that
  4814. takes an \LangIf{} expression and two blocks for the then-branch and
  4815. else-branch. The output of \code{explicate-pred} is a block.
  4816. %
  4817. In the following paragraphs we discuss specific cases in the
  4818. \code{explicate-pred} function as well as additions to the
  4819. \code{explicate-tail} and \code{explicate-assign} functions.
  4820. \begin{figure}[tbp]
  4821. \begin{lstlisting}
  4822. (define (explicate-pred cnd thn els)
  4823. (match cnd
  4824. [(Var x) ___]
  4825. [(Let x rhs body) ___]
  4826. [(Prim 'not (list e)) ___]
  4827. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4828. (IfStmt (Prim op arg*) (force (block->goto thn))
  4829. (force (block->goto els)))]
  4830. [(Bool b) (if b thn els)]
  4831. [(If cnd^ thn^ els^) ___]
  4832. [else (error "explicate-pred unhandled case" cnd)]))
  4833. \end{lstlisting}
  4834. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4835. \label{fig:explicate-pred}
  4836. \end{figure}
  4837. The skeleton for the \code{explicate-pred} function is given in
  4838. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4839. that can have type \code{Boolean}. We detail a few cases here and
  4840. leave the rest for the reader. The input to this function is an
  4841. expression and two blocks, \code{thn} and \code{els}, for the two
  4842. branches of the enclosing \key{if}.
  4843. %
  4844. Consider the case for Boolean constants in
  4845. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4846. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  4847. or \code{els} branch depending on whether the constant is true or
  4848. false. This case demonstrates that we sometimes discard the \code{thn}
  4849. or \code{els} blocks that are input to \code{explicate-pred}.
  4850. The case for \key{if} in \code{explicate-pred} is particularly
  4851. illuminating because it deals with the challenges we discussed above
  4852. regarding nested \key{if} expressions
  4853. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4854. \lstinline{els^} branches of the \key{if} inherit their context from
  4855. the current one, that is, predicate context. So you should recursively
  4856. apply \code{explicate-pred} to the \lstinline{thn^} and
  4857. \lstinline{els^} branches. For both of those recursive calls, pass
  4858. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4859. and \code{els} may get used twice, once inside each recursive call. As
  4860. discussed above, to avoid duplicating code, we need to add them to the
  4861. control-flow graph so that we can instead refer to them by name and
  4862. execute them with a \key{goto}. However, as we saw in the cases above
  4863. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4864. get used at all and we don't want to prematurely add them to the
  4865. control-flow graph if they end up being discarded.
  4866. The solution to this conundrum is to use \emph{lazy
  4867. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  4868. adding the blocks to the control-flow graph until the points where we
  4869. know they will be used. Racket provides support for lazy evaluation
  4870. with the
  4871. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4872. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4873. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  4874. evaluation of the expressions is postponed. When \key{(force}
  4875. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  4876. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4877. $e_n$ is cached in the promise and returned. If \code{force} is
  4878. applied again to the same promise, then the cached result is returned.
  4879. If \code{force} is applied to an argument that is not a promise,
  4880. \code{force} simply returns the argument.
  4881. We use lazy evaluation for the input and output blocks of the
  4882. functions \code{explicate-pred} and \code{explicate-assign} and for
  4883. the output block of \code{explicate-tail}. So instead of taking and
  4884. returning blocks, they take and return promises. Furthermore, when we
  4885. come to a situation in which we a block might be used more than once,
  4886. as in the case for \code{if} in \code{explicate-pred}, we transform
  4887. the promise into a new promise that will add the block to the
  4888. control-flow graph and return a \code{goto}. The following auxiliary
  4889. function named \code{block->goto} accomplishes this task. It begins
  4890. with \code{delay} to create a promise. When forced, this promise will
  4891. force the original promise. If that returns a \code{goto} (because the
  4892. block was already added to the control-flow graph), then we return the
  4893. \code{goto}. Otherwise we add the block to the control-flow graph with
  4894. another auxiliary function named \code{add-node}. That function
  4895. returns the label for the new block, which we use to create a
  4896. \code{goto}.
  4897. \begin{lstlisting}
  4898. (define (block->goto block)
  4899. (delay
  4900. (define b (force block))
  4901. (match b
  4902. [(Goto label) (Goto label)]
  4903. [else (Goto (add-node b))])))
  4904. \end{lstlisting}
  4905. Returning to the discussion of \code{explicate-pred}
  4906. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4907. operators. This is one of the base cases of the recursive function so
  4908. we translate the comparison to an \code{if} statement. We apply
  4909. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4910. that will add then to the control-flow graph, which we can immediately
  4911. \code{force} to obtain the two goto's that form the branches of the
  4912. \code{if} statement.
  4913. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4914. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4915. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4916. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4917. %% results from the two recursive calls. We complete the case for
  4918. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4919. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4920. %% the result $B_5$.
  4921. %% \[
  4922. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4923. %% \quad\Rightarrow\quad
  4924. %% B_5
  4925. %% \]
  4926. The \code{explicate-tail} and \code{explicate-assign} functions need
  4927. additional cases for Boolean constants and \key{if}.
  4928. %
  4929. In the cases for \code{if}, the two branches inherit the current
  4930. context, so in \code{explicate-tail} they are in tail position and in
  4931. \code{explicate-assign} they are in assignment position. The
  4932. \code{cont} parameter of \code{explicate-assign} is used in both
  4933. recursive calls, so make sure to use \code{block->goto} on it.
  4934. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4935. %% inherit the current context, so they are in tail position. Thus, the
  4936. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4937. %% \code{explicate-tail}.
  4938. %% %
  4939. %% We need to pass $B_0$ as the accumulator argument for both of these
  4940. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4941. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4942. %% to the control-flow graph and obtain a promised goto $G_0$.
  4943. %% %
  4944. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4945. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4946. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4947. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4948. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4949. %% \[
  4950. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4951. %% \]
  4952. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4953. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4954. %% should not be confused with the labels for the blocks that appear in
  4955. %% the generated code. We initially construct unlabeled blocks; we only
  4956. %% attach labels to blocks when we add them to the control-flow graph, as
  4957. %% we see in the next case.
  4958. %% Next consider the case for \key{if} in the \code{explicate-assign}
  4959. %% function. The context of the \key{if} is an assignment to some
  4960. %% variable $x$ and then the control continues to some promised block
  4961. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  4962. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4963. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4964. %% branches of the \key{if} inherit the current context, so they are in
  4965. %% assignment positions. Let $B_2$ be the result of applying
  4966. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4967. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4968. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4969. %% the result of applying \code{explicate-pred} to the predicate
  4970. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4971. %% translates to the promise $B_4$.
  4972. %% \[
  4973. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4974. %% \]
  4975. %% This completes the description of \code{explicate-control} for \LangIf{}.
  4976. The way in which the \code{shrink} pass transforms logical operations
  4977. such as \code{and} and \code{or} can impact the quality of code
  4978. generated by \code{explicate-control}. For example, consider the
  4979. following program.
  4980. % cond_test_21.rkt
  4981. \begin{lstlisting}
  4982. (if (and (eq? (read) 0) (eq? (read) 1))
  4983. 0
  4984. 42)
  4985. \end{lstlisting}
  4986. The \code{and} operation should transform into something that the
  4987. \code{explicate-pred} function can still analyze and descend through to
  4988. reach the underlying \code{eq?} conditions. Ideally, your
  4989. \code{explicate-control} pass should generate code similar to the
  4990. following for the above program.
  4991. \begin{center}
  4992. \begin{lstlisting}
  4993. start:
  4994. tmp1 = (read);
  4995. if (eq? tmp1 0) goto block40;
  4996. else goto block39;
  4997. block40:
  4998. tmp2 = (read);
  4999. if (eq? tmp2 1) goto block38;
  5000. else goto block39;
  5001. block38:
  5002. return 0;
  5003. block39:
  5004. return 42;
  5005. \end{lstlisting}
  5006. \end{center}
  5007. \begin{exercise}\normalfont
  5008. Implement the pass \code{explicate-control} by adding the cases for
  5009. Boolean constants and \key{if} to the \code{explicate-tail} and
  5010. \code{explicate-assign}. Implement the auxiliary function
  5011. \code{explicate-pred} for predicate contexts.
  5012. %
  5013. Create test cases that exercise all of the new cases in the code for
  5014. this pass.
  5015. %
  5016. Add the following entry to the list of \code{passes} in
  5017. \code{run-tests.rkt} and then run this script to test your compiler.
  5018. \begin{lstlisting}
  5019. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5020. \end{lstlisting}
  5021. \end{exercise}
  5022. \section{Select Instructions}
  5023. \label{sec:select-Rif}
  5024. \index{subject}{instruction selection}
  5025. The \code{select-instructions} pass translate \LangCIf{} to
  5026. \LangXIfVar{}. Recall that we implement this pass using three
  5027. auxiliary functions, one for each of the non-terminals $\Atm$,
  5028. $\Stmt$, and $\Tail$.
  5029. For $\Atm$, we have new cases for the Booleans. We take the usual
  5030. approach of encoding them as integers, with true as 1 and false as 0.
  5031. \[
  5032. \key{\#t} \Rightarrow \key{1}
  5033. \qquad
  5034. \key{\#f} \Rightarrow \key{0}
  5035. \]
  5036. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5037. be implemented in terms of \code{xorq} as we discussed at the
  5038. beginning of this section. Given an assignment
  5039. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5040. if the left-hand side $\itm{var}$ is
  5041. the same as $\Atm$, then just the \code{xorq} suffices.
  5042. \[
  5043. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5044. \quad\Rightarrow\quad
  5045. \key{xorq}~\key{\$}1\key{,}~\Var
  5046. \]
  5047. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5048. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5049. x86. Then we have
  5050. \[
  5051. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5052. \quad\Rightarrow\quad
  5053. \begin{array}{l}
  5054. \key{movq}~\Arg\key{,}~\Var\\
  5055. \key{xorq}~\key{\$}1\key{,}~\Var
  5056. \end{array}
  5057. \]
  5058. Next consider the cases for \code{eq?} and less-than comparison.
  5059. Translating these operations to x86 is slightly involved due to the
  5060. unusual nature of the \key{cmpq} instruction discussed above. We
  5061. recommend translating an assignment from \code{eq?} into the following
  5062. sequence of three instructions. \\
  5063. \begin{tabular}{lll}
  5064. \begin{minipage}{0.4\textwidth}
  5065. \begin{lstlisting}
  5066. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5067. \end{lstlisting}
  5068. \end{minipage}
  5069. &
  5070. $\Rightarrow$
  5071. &
  5072. \begin{minipage}{0.4\textwidth}
  5073. \begin{lstlisting}
  5074. cmpq |$\Arg_2$|, |$\Arg_1$|
  5075. sete %al
  5076. movzbq %al, |$\Var$|
  5077. \end{lstlisting}
  5078. \end{minipage}
  5079. \end{tabular} \\
  5080. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5081. and \key{if} statements. Both are straightforward to translate to
  5082. x86. A \key{goto} becomes a jump instruction.
  5083. \[
  5084. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5085. \]
  5086. An \key{if} statement becomes a compare instruction followed by a
  5087. conditional jump (for the ``then'' branch) and the fall-through is to
  5088. a regular jump (for the ``else'' branch).\\
  5089. \begin{tabular}{lll}
  5090. \begin{minipage}{0.4\textwidth}
  5091. \begin{lstlisting}
  5092. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5093. else goto |$\ell_2$|;
  5094. \end{lstlisting}
  5095. \end{minipage}
  5096. &
  5097. $\Rightarrow$
  5098. &
  5099. \begin{minipage}{0.4\textwidth}
  5100. \begin{lstlisting}
  5101. cmpq |$\Arg_2$|, |$\Arg_1$|
  5102. je |$\ell_1$|
  5103. jmp |$\ell_2$|
  5104. \end{lstlisting}
  5105. \end{minipage}
  5106. \end{tabular} \\
  5107. \begin{exercise}\normalfont
  5108. Expand your \code{select-instructions} pass to handle the new features
  5109. of the \LangIf{} language.
  5110. %
  5111. Add the following entry to the list of \code{passes} in
  5112. \code{run-tests.rkt}
  5113. \begin{lstlisting}
  5114. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5115. \end{lstlisting}
  5116. %
  5117. Run the script to test your compiler on all the test programs.
  5118. \end{exercise}
  5119. \section{Register Allocation}
  5120. \label{sec:register-allocation-Rif}
  5121. \index{subject}{register allocation}
  5122. The changes required for \LangIf{} affect liveness analysis, building the
  5123. interference graph, and assigning homes, but the graph coloring
  5124. algorithm itself does not change.
  5125. \subsection{Liveness Analysis}
  5126. \label{sec:liveness-analysis-Rif}
  5127. \index{subject}{liveness analysis}
  5128. Recall that for \LangVar{} we implemented liveness analysis for a single
  5129. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5130. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5131. produces many basic blocks arranged in a control-flow graph. We
  5132. recommend that you create a new auxiliary function named
  5133. \code{uncover-live-CFG} that applies liveness analysis to a
  5134. control-flow graph.
  5135. The first question we is: what order should we process the basic
  5136. blocks in the control-flow graph? Recall that to perform liveness
  5137. analysis on a basic block we need to know its live-after set. If a
  5138. basic block has no successors (i.e. no out-edges in the control flow
  5139. graph), then it has an empty live-after set and we can immediately
  5140. apply liveness analysis to it. If a basic block has some successors,
  5141. then we need to complete liveness analysis on those blocks first. In
  5142. graph theory, a sequence of nodes is in \emph{topological
  5143. order}\index{subject}{topological order} if each vertex comes before its
  5144. successors. We need the opposite, so we can transpose the graph
  5145. before computing a topological order.
  5146. %
  5147. Use the \code{tsort} and \code{transpose} functions of the Racket
  5148. \code{graph} package to accomplish this.
  5149. %
  5150. As an aside, a topological ordering is only guaranteed to exist if the
  5151. graph does not contain any cycles. That is indeed the case for the
  5152. control-flow graphs that we generate from \LangIf{} programs.
  5153. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5154. learn how to handle cycles in the control-flow graph.
  5155. You'll need to construct a directed graph to represent the
  5156. control-flow graph. Do not use the \code{directed-graph} of the
  5157. \code{graph} package because that only allows at most one edge between
  5158. each pair of vertices, but a control-flow graph may have multiple
  5159. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5160. the support code implements a graph representation that allows
  5161. multiple edges between a pair of vertices.
  5162. The next question is how to analyze jump instructions. Recall that in
  5163. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5164. \code{label->live} that maps each label to the set of live locations
  5165. at the beginning of its block. We use \code{label->live} to determine
  5166. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5167. that we have many basic blocks, \code{label->live} needs to be updated
  5168. as we process the blocks. In particular, after performing liveness
  5169. analysis on a block, we take the live-before set of its first
  5170. instruction and associate that with the block's label in the
  5171. \code{label->live}.
  5172. In \LangXIfVar{} we also have the conditional jump
  5173. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5174. this instruction is particularly interesting because during
  5175. compilation we do not know which way a conditional jump will go. So
  5176. we do not know whether to use the live-before set for the following
  5177. instruction or the live-before set for the $\itm{label}$. However,
  5178. there is no harm to the correctness of the compiler if we classify
  5179. more locations as live than the ones that are truly live during a
  5180. particular execution of the instruction. Thus, we can take the union
  5181. of the live-before sets from the following instruction and from the
  5182. mapping for $\itm{label}$ in \code{label->live}.
  5183. The auxiliary functions for computing the variables in an
  5184. instruction's argument and for computing the variables read-from ($R$)
  5185. or written-to ($W$) by an instruction need to be updated to handle the
  5186. new kinds of arguments and instructions in \LangXIfVar{}.
  5187. \begin{exercise}\normalfont
  5188. Update the \code{uncover-live} pass and implement the
  5189. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5190. to the control-flow graph. Add the following entry to the list of
  5191. \code{passes} in the \code{run-tests.rkt} script.
  5192. \begin{lstlisting}
  5193. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5194. \end{lstlisting}
  5195. \end{exercise}
  5196. \subsection{Build the Interference Graph}
  5197. \label{sec:build-interference-Rif}
  5198. Many of the new instructions in \LangXIfVar{} can be handled in the
  5199. same way as the instructions in \LangXVar{}. Thus, if your code was
  5200. already quite general, it will not need to be changed to handle the
  5201. new instructions. If you code is not general enough, we recommend that
  5202. you change your code to be more general. For example, you can factor
  5203. out the computing of the the read and write sets for each kind of
  5204. instruction into two auxiliary functions.
  5205. Note that the \key{movzbq} instruction requires some special care,
  5206. similar to the \key{movq} instruction. See rule number 1 in
  5207. Section~\ref{sec:build-interference}.
  5208. \begin{exercise}\normalfont
  5209. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5210. following entries to the list of \code{passes} in the
  5211. \code{run-tests.rkt} script.
  5212. \begin{lstlisting}
  5213. (list "build-interference" build-interference interp-pseudo-x86-1)
  5214. (list "allocate-registers" allocate-registers interp-x86-1)
  5215. \end{lstlisting}
  5216. Run the script to test your compiler on all the \LangIf{} test
  5217. programs.
  5218. \end{exercise}
  5219. \section{Patch Instructions}
  5220. The second argument of the \key{cmpq} instruction must not be an
  5221. immediate value (such as an integer). So if you are comparing two
  5222. immediates, we recommend inserting a \key{movq} instruction to put the
  5223. second argument in \key{rax}. Also, recall that instructions may have
  5224. at most one memory reference.
  5225. %
  5226. The second argument of the \key{movzbq} must be a register.
  5227. %
  5228. There are no special restrictions on the jump instructions.
  5229. \begin{exercise}\normalfont
  5230. %
  5231. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5232. %
  5233. Add the following entry to the list of \code{passes} in
  5234. \code{run-tests.rkt} and then run this script to test your compiler.
  5235. \begin{lstlisting}
  5236. (list "patch-instructions" patch-instructions interp-x86-1)
  5237. \end{lstlisting}
  5238. \end{exercise}
  5239. \begin{figure}[tbp]
  5240. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5241. \node (Rif) at (0,2) {\large \LangIf{}};
  5242. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5243. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5244. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5245. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5246. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5247. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5248. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5249. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5250. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5251. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5252. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5253. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5254. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5255. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5256. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5257. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5258. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5259. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5260. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5261. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5262. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5263. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5264. \end{tikzpicture}
  5265. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5266. \label{fig:Rif-passes}
  5267. \end{figure}
  5268. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5269. compilation of \LangIf{}.
  5270. \section{An Example Translation}
  5271. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5272. \LangIf{} translated to x86, showing the results of
  5273. \code{explicate-control}, \code{select-instructions}, and the final
  5274. x86 assembly code.
  5275. \begin{figure}[tbp]
  5276. \begin{tabular}{lll}
  5277. \begin{minipage}{0.4\textwidth}
  5278. % cond_test_20.rkt
  5279. \begin{lstlisting}
  5280. (if (eq? (read) 1) 42 0)
  5281. \end{lstlisting}
  5282. $\Downarrow$
  5283. \begin{lstlisting}
  5284. start:
  5285. tmp7951 = (read);
  5286. if (eq? tmp7951 1)
  5287. goto block7952;
  5288. else
  5289. goto block7953;
  5290. block7952:
  5291. return 42;
  5292. block7953:
  5293. return 0;
  5294. \end{lstlisting}
  5295. $\Downarrow$
  5296. \begin{lstlisting}
  5297. start:
  5298. callq read_int
  5299. movq %rax, tmp7951
  5300. cmpq $1, tmp7951
  5301. je block7952
  5302. jmp block7953
  5303. block7953:
  5304. movq $0, %rax
  5305. jmp conclusion
  5306. block7952:
  5307. movq $42, %rax
  5308. jmp conclusion
  5309. \end{lstlisting}
  5310. \end{minipage}
  5311. &
  5312. $\Rightarrow\qquad$
  5313. \begin{minipage}{0.4\textwidth}
  5314. \begin{lstlisting}
  5315. start:
  5316. callq read_int
  5317. movq %rax, %rcx
  5318. cmpq $1, %rcx
  5319. je block7952
  5320. jmp block7953
  5321. block7953:
  5322. movq $0, %rax
  5323. jmp conclusion
  5324. block7952:
  5325. movq $42, %rax
  5326. jmp conclusion
  5327. .globl main
  5328. main:
  5329. pushq %rbp
  5330. movq %rsp, %rbp
  5331. pushq %r13
  5332. pushq %r12
  5333. pushq %rbx
  5334. pushq %r14
  5335. subq $0, %rsp
  5336. jmp start
  5337. conclusion:
  5338. addq $0, %rsp
  5339. popq %r14
  5340. popq %rbx
  5341. popq %r12
  5342. popq %r13
  5343. popq %rbp
  5344. retq
  5345. \end{lstlisting}
  5346. \end{minipage}
  5347. \end{tabular}
  5348. \caption{Example compilation of an \key{if} expression to x86.}
  5349. \label{fig:if-example-x86}
  5350. \end{figure}
  5351. \section{Challenge: Remove Jumps}
  5352. \label{sec:opt-jumps}
  5353. %% Recall that in the example output of \code{explicate-control} in
  5354. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5355. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5356. %% block. The first goal of this challenge assignment is to remove those
  5357. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5358. %% \code{explicate-control} on the left and shows the result of bypassing
  5359. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5360. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5361. %% \code{block55}. The optimized code on the right of
  5362. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5363. %% \code{then} branch jumping directly to \code{block55}. The story is
  5364. %% similar for the \code{else} branch, as well as for the two branches in
  5365. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5366. %% have been optimized in this way, there are no longer any jumps to
  5367. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5368. %% \begin{figure}[tbp]
  5369. %% \begin{tabular}{lll}
  5370. %% \begin{minipage}{0.4\textwidth}
  5371. %% \begin{lstlisting}
  5372. %% block62:
  5373. %% tmp54 = (read);
  5374. %% if (eq? tmp54 2) then
  5375. %% goto block59;
  5376. %% else
  5377. %% goto block60;
  5378. %% block61:
  5379. %% tmp53 = (read);
  5380. %% if (eq? tmp53 0) then
  5381. %% goto block57;
  5382. %% else
  5383. %% goto block58;
  5384. %% block60:
  5385. %% goto block56;
  5386. %% block59:
  5387. %% goto block55;
  5388. %% block58:
  5389. %% goto block56;
  5390. %% block57:
  5391. %% goto block55;
  5392. %% block56:
  5393. %% return (+ 700 77);
  5394. %% block55:
  5395. %% return (+ 10 32);
  5396. %% start:
  5397. %% tmp52 = (read);
  5398. %% if (eq? tmp52 1) then
  5399. %% goto block61;
  5400. %% else
  5401. %% goto block62;
  5402. %% \end{lstlisting}
  5403. %% \end{minipage}
  5404. %% &
  5405. %% $\Rightarrow$
  5406. %% &
  5407. %% \begin{minipage}{0.55\textwidth}
  5408. %% \begin{lstlisting}
  5409. %% block62:
  5410. %% tmp54 = (read);
  5411. %% if (eq? tmp54 2) then
  5412. %% goto block55;
  5413. %% else
  5414. %% goto block56;
  5415. %% block61:
  5416. %% tmp53 = (read);
  5417. %% if (eq? tmp53 0) then
  5418. %% goto block55;
  5419. %% else
  5420. %% goto block56;
  5421. %% block56:
  5422. %% return (+ 700 77);
  5423. %% block55:
  5424. %% return (+ 10 32);
  5425. %% start:
  5426. %% tmp52 = (read);
  5427. %% if (eq? tmp52 1) then
  5428. %% goto block61;
  5429. %% else
  5430. %% goto block62;
  5431. %% \end{lstlisting}
  5432. %% \end{minipage}
  5433. %% \end{tabular}
  5434. %% \caption{Optimize jumps by removing trivial blocks.}
  5435. %% \label{fig:optimize-jumps}
  5436. %% \end{figure}
  5437. %% The name of this pass is \code{optimize-jumps}. We recommend
  5438. %% implementing this pass in two phases. The first phrase builds a hash
  5439. %% table that maps labels to possibly improved labels. The second phase
  5440. %% changes the target of each \code{goto} to use the improved label. If
  5441. %% the label is for a trivial block, then the hash table should map the
  5442. %% label to the first non-trivial block that can be reached from this
  5443. %% label by jumping through trivial blocks. If the label is for a
  5444. %% non-trivial block, then the hash table should map the label to itself;
  5445. %% we do not want to change jumps to non-trivial blocks.
  5446. %% The first phase can be accomplished by constructing an empty hash
  5447. %% table, call it \code{short-cut}, and then iterating over the control
  5448. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5449. %% then update the hash table, mapping the block's source to the target
  5450. %% of the \code{goto}. Also, the hash table may already have mapped some
  5451. %% labels to the block's source, to you must iterate through the hash
  5452. %% table and update all of those so that they instead map to the target
  5453. %% of the \code{goto}.
  5454. %% For the second phase, we recommend iterating through the $\Tail$ of
  5455. %% each block in the program, updating the target of every \code{goto}
  5456. %% according to the mapping in \code{short-cut}.
  5457. %% \begin{exercise}\normalfont
  5458. %% Implement the \code{optimize-jumps} pass as a transformation from
  5459. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5460. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5461. %% example programs. Then check that your compiler still passes all of
  5462. %% your tests.
  5463. %% \end{exercise}
  5464. There is an opportunity for optimizing jumps that is apparent in the
  5465. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5466. ends with a jump to \code{block7953} and there are no other jumps to
  5467. \code{block7953} in the rest of the program. In this situation we can
  5468. avoid the runtime overhead of this jump by merging \code{block7953}
  5469. into the preceding block, in this case the \code{start} block.
  5470. Figure~\ref{fig:remove-jumps} shows the output of
  5471. \code{select-instructions} on the left and the result of this
  5472. optimization on the right.
  5473. \begin{figure}[tbp]
  5474. \begin{tabular}{lll}
  5475. \begin{minipage}{0.5\textwidth}
  5476. % cond_test_20.rkt
  5477. \begin{lstlisting}
  5478. start:
  5479. callq read_int
  5480. movq %rax, tmp7951
  5481. cmpq $1, tmp7951
  5482. je block7952
  5483. jmp block7953
  5484. block7953:
  5485. movq $0, %rax
  5486. jmp conclusion
  5487. block7952:
  5488. movq $42, %rax
  5489. jmp conclusion
  5490. \end{lstlisting}
  5491. \end{minipage}
  5492. &
  5493. $\Rightarrow\qquad$
  5494. \begin{minipage}{0.4\textwidth}
  5495. \begin{lstlisting}
  5496. start:
  5497. callq read_int
  5498. movq %rax, tmp7951
  5499. cmpq $1, tmp7951
  5500. je block7952
  5501. movq $0, %rax
  5502. jmp conclusion
  5503. block7952:
  5504. movq $42, %rax
  5505. jmp conclusion
  5506. \end{lstlisting}
  5507. \end{minipage}
  5508. \end{tabular}
  5509. \caption{Merging basic blocks by removing unnecessary jumps.}
  5510. \label{fig:remove-jumps}
  5511. \end{figure}
  5512. \begin{exercise}\normalfont
  5513. %
  5514. Implement a pass named \code{remove-jumps} that merges basic blocks
  5515. into their preceding basic block, when there is only one preceding
  5516. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5517. %
  5518. In the \code{run-tests.rkt} script, add the following entry to the
  5519. list of \code{passes} between \code{allocate-registers}
  5520. and \code{patch-instructions}.
  5521. \begin{lstlisting}
  5522. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5523. \end{lstlisting}
  5524. Run this script to test your compiler.
  5525. %
  5526. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5527. blocks on several test programs.
  5528. \end{exercise}
  5529. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5530. \chapter{Tuples and Garbage Collection}
  5531. \label{ch:Rvec}
  5532. \index{subject}{tuple}
  5533. \index{subject}{vector}
  5534. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5535. %% all the IR grammars are spelled out! \\ --Jeremy}
  5536. %% \margincomment{\scriptsize Be more explicit about how to deal with
  5537. %% the root stack. \\ --Jeremy}
  5538. In this chapter we study the implementation of mutable tuples, called
  5539. vectors in Racket. This language feature is the first to use the
  5540. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  5541. tuple is indefinite, that is, a tuple lives forever from the
  5542. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5543. is important to reclaim the space associated with a tuple when it is
  5544. no longer needed, which is why we also study \emph{garbage collection}
  5545. \emph{garbage collection} techniques in this chapter.
  5546. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5547. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5548. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5549. \code{void} value. The reason for including the later is that the
  5550. \code{vector-set!} operation returns a value of type
  5551. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5552. called the \code{Unit} type in the programming languages
  5553. literature. Racket's \code{Void} type is inhabited by a single value
  5554. \code{void} which corresponds to \code{unit} or \code{()} in the
  5555. literature~\citep{Pierce:2002hj}.}.
  5556. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5557. copying live objects back and forth between two halves of the
  5558. heap. The garbage collector requires coordination with the compiler so
  5559. that it can see all of the \emph{root} pointers, that is, pointers in
  5560. registers or on the procedure call stack.
  5561. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5562. discuss all the necessary changes and additions to the compiler
  5563. passes, including a new compiler pass named \code{expose-allocation}.
  5564. \section{The \LangVec{} Language}
  5565. \label{sec:r3}
  5566. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5567. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5568. \LangVec{} language includes three new forms: \code{vector} for creating a
  5569. tuple, \code{vector-ref} for reading an element of a tuple, and
  5570. \code{vector-set!} for writing to an element of a tuple. The program
  5571. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5572. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5573. the 3-tuple, demonstrating that tuples are first-class values. The
  5574. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5575. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5576. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5577. 1-tuple. So the result of the program is \code{42}.
  5578. \begin{figure}[tbp]
  5579. \centering
  5580. \fbox{
  5581. \begin{minipage}{0.96\textwidth}
  5582. \[
  5583. \begin{array}{lcl}
  5584. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5585. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5586. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5587. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5588. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5589. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5590. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5591. \mid \LP\key{not}\;\Exp\RP } \\
  5592. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5593. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5594. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5595. \mid \LP\key{vector-length}\;\Exp\RP \\
  5596. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5597. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5598. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5599. \LangVecM{} &::=& \Exp
  5600. \end{array}
  5601. \]
  5602. \end{minipage}
  5603. }
  5604. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5605. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5606. \label{fig:Rvec-concrete-syntax}
  5607. \end{figure}
  5608. \begin{figure}[tbp]
  5609. \begin{lstlisting}
  5610. (let ([t (vector 40 #t (vector 2))])
  5611. (if (vector-ref t 1)
  5612. (+ (vector-ref t 0)
  5613. (vector-ref (vector-ref t 2) 0))
  5614. 44))
  5615. \end{lstlisting}
  5616. \caption{Example program that creates tuples and reads from them.}
  5617. \label{fig:vector-eg}
  5618. \end{figure}
  5619. \begin{figure}[tp]
  5620. \centering
  5621. \fbox{
  5622. \begin{minipage}{0.96\textwidth}
  5623. \[
  5624. \begin{array}{lcl}
  5625. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5626. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5627. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5628. \mid \BOOL{\itm{bool}}
  5629. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5630. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5631. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5632. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5633. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5634. \end{array}
  5635. \]
  5636. \end{minipage}
  5637. }
  5638. \caption{The abstract syntax of \LangVec{}.}
  5639. \label{fig:Rvec-syntax}
  5640. \end{figure}
  5641. \index{subject}{allocate}
  5642. \index{subject}{heap allocate}
  5643. Tuples are our first encounter with heap-allocated data, which raises
  5644. several interesting issues. First, variable binding performs a
  5645. shallow-copy when dealing with tuples, which means that different
  5646. variables can refer to the same tuple, that is, different variables
  5647. can be \emph{aliases} for the same entity. Consider the following
  5648. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5649. Thus, the mutation through \code{t2} is visible when referencing the
  5650. tuple from \code{t1}, so the result of this program is \code{42}.
  5651. \index{subject}{alias}\index{subject}{mutation}
  5652. \begin{center}
  5653. \begin{minipage}{0.96\textwidth}
  5654. \begin{lstlisting}
  5655. (let ([t1 (vector 3 7)])
  5656. (let ([t2 t1])
  5657. (let ([_ (vector-set! t2 0 42)])
  5658. (vector-ref t1 0))))
  5659. \end{lstlisting}
  5660. \end{minipage}
  5661. \end{center}
  5662. The next issue concerns the lifetime of tuples. Of course, they are
  5663. created by the \code{vector} form, but when does their lifetime end?
  5664. Notice that \LangVec{} does not include an operation for deleting
  5665. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5666. of static scoping. For example, the following program returns
  5667. \code{42} even though the variable \code{w} goes out of scope prior to
  5668. the \code{vector-ref} that reads from the vector it was bound to.
  5669. \begin{center}
  5670. \begin{minipage}{0.96\textwidth}
  5671. \begin{lstlisting}
  5672. (let ([v (vector (vector 44))])
  5673. (let ([x (let ([w (vector 42)])
  5674. (let ([_ (vector-set! v 0 w)])
  5675. 0))])
  5676. (+ x (vector-ref (vector-ref v 0) 0))))
  5677. \end{lstlisting}
  5678. \end{minipage}
  5679. \end{center}
  5680. From the perspective of programmer-observable behavior, tuples live
  5681. forever. Of course, if they really lived forever, then many programs
  5682. would run out of memory.\footnote{The \LangVec{} language does not have
  5683. looping or recursive functions, so it is nigh impossible to write a
  5684. program in \LangVec{} that will run out of memory. However, we add
  5685. recursive functions in the next Chapter!} A Racket implementation
  5686. must therefore perform automatic garbage collection.
  5687. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5688. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5689. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5690. terms of the corresponding operations in Racket. One subtle point is
  5691. that the \code{vector-set!} operation returns the \code{\#<void>}
  5692. value. The \code{\#<void>} value can be passed around just like other
  5693. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5694. compared for equality with another \code{\#<void>} value. However,
  5695. there are no other operations specific to the the \code{\#<void>}
  5696. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5697. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5698. otherwise.
  5699. \begin{figure}[tbp]
  5700. \begin{lstlisting}
  5701. (define interp-Rvec-class
  5702. (class interp-Rif-class
  5703. (super-new)
  5704. (define/override (interp-op op)
  5705. (match op
  5706. ['eq? (lambda (v1 v2)
  5707. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5708. (and (boolean? v1) (boolean? v2))
  5709. (and (vector? v1) (vector? v2))
  5710. (and (void? v1) (void? v2)))
  5711. (eq? v1 v2)]))]
  5712. ['vector vector]
  5713. ['vector-length vector-length]
  5714. ['vector-ref vector-ref]
  5715. ['vector-set! vector-set!]
  5716. [else (super interp-op op)]
  5717. ))
  5718. (define/override ((interp-exp env) e)
  5719. (define recur (interp-exp env))
  5720. (match e
  5721. [(HasType e t) (recur e)]
  5722. [(Void) (void)]
  5723. [else ((super interp-exp env) e)]
  5724. ))
  5725. ))
  5726. (define (interp-Rvec p)
  5727. (send (new interp-Rvec-class) interp-program p))
  5728. \end{lstlisting}
  5729. \caption{Interpreter for the \LangVec{} language.}
  5730. \label{fig:interp-Rvec}
  5731. \end{figure}
  5732. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5733. deserves some explanation. When allocating a vector, we need to know
  5734. which elements of the vector are pointers (i.e. are also vectors). We
  5735. can obtain this information during type checking. The type checker in
  5736. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5737. expression, it also wraps every \key{vector} creation with the form
  5738. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5739. %
  5740. To create the s-expression for the \code{Vector} type in
  5741. Figure~\ref{fig:type-check-Rvec}, we use the
  5742. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5743. operator} \code{,@} to insert the list \code{t*} without its usual
  5744. start and end parentheses. \index{subject}{unquote-slicing}
  5745. \begin{figure}[tp]
  5746. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5747. (define type-check-Rvec-class
  5748. (class type-check-Rif-class
  5749. (super-new)
  5750. (inherit check-type-equal?)
  5751. (define/override (type-check-exp env)
  5752. (lambda (e)
  5753. (define recur (type-check-exp env))
  5754. (match e
  5755. [(Void) (values (Void) 'Void)]
  5756. [(Prim 'vector es)
  5757. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5758. (define t `(Vector ,@t*))
  5759. (values (HasType (Prim 'vector e*) t) t)]
  5760. [(Prim 'vector-ref (list e1 (Int i)))
  5761. (define-values (e1^ t) (recur e1))
  5762. (match t
  5763. [`(Vector ,ts ...)
  5764. (unless (and (0 . <= . i) (i . < . (length ts)))
  5765. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5766. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5767. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5768. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5769. (define-values (e-vec t-vec) (recur e1))
  5770. (define-values (e-arg^ t-arg) (recur arg))
  5771. (match t-vec
  5772. [`(Vector ,ts ...)
  5773. (unless (and (0 . <= . i) (i . < . (length ts)))
  5774. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5775. (check-type-equal? (list-ref ts i) t-arg e)
  5776. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5777. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5778. [(Prim 'vector-length (list e))
  5779. (define-values (e^ t) (recur e))
  5780. (match t
  5781. [`(Vector ,ts ...)
  5782. (values (Prim 'vector-length (list e^)) 'Integer)]
  5783. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5784. [(Prim 'eq? (list arg1 arg2))
  5785. (define-values (e1 t1) (recur arg1))
  5786. (define-values (e2 t2) (recur arg2))
  5787. (match* (t1 t2)
  5788. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5789. [(other wise) (check-type-equal? t1 t2 e)])
  5790. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5791. [(HasType (Prim 'vector es) t)
  5792. ((type-check-exp env) (Prim 'vector es))]
  5793. [(HasType e1 t)
  5794. (define-values (e1^ t^) (recur e1))
  5795. (check-type-equal? t t^ e)
  5796. (values (HasType e1^ t) t)]
  5797. [else ((super type-check-exp env) e)]
  5798. )))
  5799. ))
  5800. (define (type-check-Rvec p)
  5801. (send (new type-check-Rvec-class) type-check-program p))
  5802. \end{lstlisting}
  5803. \caption{Type checker for the \LangVec{} language.}
  5804. \label{fig:type-check-Rvec}
  5805. \end{figure}
  5806. \section{Garbage Collection}
  5807. \label{sec:GC}
  5808. Here we study a relatively simple algorithm for garbage collection
  5809. that is the basis of state-of-the-art garbage
  5810. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5811. particular, we describe a two-space copying
  5812. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5813. perform the
  5814. copy~\citep{Cheney:1970aa}.
  5815. \index{subject}{copying collector}
  5816. \index{subject}{two-space copying collector}
  5817. Figure~\ref{fig:copying-collector} gives a
  5818. coarse-grained depiction of what happens in a two-space collector,
  5819. showing two time steps, prior to garbage collection (on the top) and
  5820. after garbage collection (on the bottom). In a two-space collector,
  5821. the heap is divided into two parts named the FromSpace and the
  5822. ToSpace. Initially, all allocations go to the FromSpace until there is
  5823. not enough room for the next allocation request. At that point, the
  5824. garbage collector goes to work to make more room.
  5825. \index{subject}{ToSpace}
  5826. \index{subject}{FromSpace}
  5827. The garbage collector must be careful not to reclaim tuples that will
  5828. be used by the program in the future. Of course, it is impossible in
  5829. general to predict what a program will do, but we can over approximate
  5830. the will-be-used tuples by preserving all tuples that could be
  5831. accessed by \emph{any} program given the current computer state. A
  5832. program could access any tuple whose address is in a register or on
  5833. the procedure call stack. These addresses are called the \emph{root
  5834. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  5835. transitively reachable from the root set. Thus, it is safe for the
  5836. garbage collector to reclaim the tuples that are not reachable in this
  5837. way.
  5838. So the goal of the garbage collector is twofold:
  5839. \begin{enumerate}
  5840. \item preserve all tuple that are reachable from the root set via a
  5841. path of pointers, that is, the \emph{live} tuples, and
  5842. \item reclaim the memory of everything else, that is, the
  5843. \emph{garbage}.
  5844. \end{enumerate}
  5845. A copying collector accomplishes this by copying all of the live
  5846. objects from the FromSpace into the ToSpace and then performs a sleight
  5847. of hand, treating the ToSpace as the new FromSpace and the old
  5848. FromSpace as the new ToSpace. In the example of
  5849. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5850. root set, one in a register and two on the stack. All of the live
  5851. objects have been copied to the ToSpace (the right-hand side of
  5852. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5853. pointer relationships. For example, the pointer in the register still
  5854. points to a 2-tuple whose first element is a 3-tuple and whose second
  5855. element is a 2-tuple. There are four tuples that are not reachable
  5856. from the root set and therefore do not get copied into the ToSpace.
  5857. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5858. created by a well-typed program in \LangVec{} because it contains a
  5859. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5860. We design the garbage collector to deal with cycles to begin with so
  5861. we will not need to revisit this issue.
  5862. \begin{figure}[tbp]
  5863. \centering
  5864. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5865. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5866. \caption{A copying collector in action.}
  5867. \label{fig:copying-collector}
  5868. \end{figure}
  5869. There are many alternatives to copying collectors (and their bigger
  5870. siblings, the generational collectors) when its comes to garbage
  5871. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5872. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5873. collectors are that allocation is fast (just a comparison and pointer
  5874. increment), there is no fragmentation, cyclic garbage is collected,
  5875. and the time complexity of collection only depends on the amount of
  5876. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5877. main disadvantages of a two-space copying collector is that it uses a
  5878. lot of space and takes a long time to perform the copy, though these
  5879. problems are ameliorated in generational collectors. Racket and
  5880. Scheme programs tend to allocate many small objects and generate a lot
  5881. of garbage, so copying and generational collectors are a good fit.
  5882. Garbage collection is an active research topic, especially concurrent
  5883. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5884. developing new techniques and revisiting old
  5885. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5886. meet every year at the International Symposium on Memory Management to
  5887. present these findings.
  5888. \subsection{Graph Copying via Cheney's Algorithm}
  5889. \label{sec:cheney}
  5890. \index{subject}{Cheney's algorithm}
  5891. Let us take a closer look at the copying of the live objects. The
  5892. allocated objects and pointers can be viewed as a graph and we need to
  5893. copy the part of the graph that is reachable from the root set. To
  5894. make sure we copy all of the reachable vertices in the graph, we need
  5895. an exhaustive graph traversal algorithm, such as depth-first search or
  5896. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5897. such algorithms take into account the possibility of cycles by marking
  5898. which vertices have already been visited, so as to ensure termination
  5899. of the algorithm. These search algorithms also use a data structure
  5900. such as a stack or queue as a to-do list to keep track of the vertices
  5901. that need to be visited. We use breadth-first search and a trick
  5902. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5903. and copying tuples into the ToSpace.
  5904. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5905. copy progresses. The queue is represented by a chunk of contiguous
  5906. memory at the beginning of the ToSpace, using two pointers to track
  5907. the front and the back of the queue. The algorithm starts by copying
  5908. all tuples that are immediately reachable from the root set into the
  5909. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5910. old tuple to indicate that it has been visited. We discuss how this
  5911. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5912. pointers inside the copied tuples in the queue still point back to the
  5913. FromSpace. Once the initial queue has been created, the algorithm
  5914. enters a loop in which it repeatedly processes the tuple at the front
  5915. of the queue and pops it off the queue. To process a tuple, the
  5916. algorithm copies all the tuple that are directly reachable from it to
  5917. the ToSpace, placing them at the back of the queue. The algorithm then
  5918. updates the pointers in the popped tuple so they point to the newly
  5919. copied tuples.
  5920. \begin{figure}[tbp]
  5921. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5922. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5923. \label{fig:cheney}
  5924. \end{figure}
  5925. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5926. tuple whose second element is $42$ to the back of the queue. The other
  5927. pointer goes to a tuple that has already been copied, so we do not
  5928. need to copy it again, but we do need to update the pointer to the new
  5929. location. This can be accomplished by storing a \emph{forwarding
  5930. pointer} to the new location in the old tuple, back when we initially
  5931. copied the tuple into the ToSpace. This completes one step of the
  5932. algorithm. The algorithm continues in this way until the front of the
  5933. queue is empty, that is, until the front catches up with the back.
  5934. \subsection{Data Representation}
  5935. \label{sec:data-rep-gc}
  5936. The garbage collector places some requirements on the data
  5937. representations used by our compiler. First, the garbage collector
  5938. needs to distinguish between pointers and other kinds of data. There
  5939. are several ways to accomplish this.
  5940. \begin{enumerate}
  5941. \item Attached a tag to each object that identifies what type of
  5942. object it is~\citep{McCarthy:1960dz}.
  5943. \item Store different types of objects in different
  5944. regions~\citep{Steele:1977ab}.
  5945. \item Use type information from the program to either generate
  5946. type-specific code for collecting or to generate tables that can
  5947. guide the
  5948. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5949. \end{enumerate}
  5950. Dynamically typed languages, such as Lisp, need to tag objects
  5951. anyways, so option 1 is a natural choice for those languages.
  5952. However, \LangVec{} is a statically typed language, so it would be
  5953. unfortunate to require tags on every object, especially small and
  5954. pervasive objects like integers and Booleans. Option 3 is the
  5955. best-performing choice for statically typed languages, but comes with
  5956. a relatively high implementation complexity. To keep this chapter
  5957. within a 2-week time budget, we recommend a combination of options 1
  5958. and 2, using separate strategies for the stack and the heap.
  5959. Regarding the stack, we recommend using a separate stack for pointers,
  5960. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  5961. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5962. is, when a local variable needs to be spilled and is of type
  5963. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5964. stack instead of the normal procedure call stack. Furthermore, we
  5965. always spill vector-typed variables if they are live during a call to
  5966. the collector, thereby ensuring that no pointers are in registers
  5967. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5968. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5969. the data layout using a root stack. The root stack contains the two
  5970. pointers from the regular stack and also the pointer in the second
  5971. register.
  5972. \begin{figure}[tbp]
  5973. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5974. \caption{Maintaining a root stack to facilitate garbage collection.}
  5975. \label{fig:shadow-stack}
  5976. \end{figure}
  5977. The problem of distinguishing between pointers and other kinds of data
  5978. also arises inside of each tuple on the heap. We solve this problem by
  5979. attaching a tag, an extra 64-bits, to each
  5980. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5981. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5982. that we have drawn the bits in a big-endian way, from right-to-left,
  5983. with bit location 0 (the least significant bit) on the far right,
  5984. which corresponds to the direction of the x86 shifting instructions
  5985. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5986. is dedicated to specifying which elements of the tuple are pointers,
  5987. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5988. indicates there is a pointer and a 0 bit indicates some other kind of
  5989. data. The pointer mask starts at bit location 7. We have limited
  5990. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5991. the pointer mask. The tag also contains two other pieces of
  5992. information. The length of the tuple (number of elements) is stored in
  5993. bits location 1 through 6. Finally, the bit at location 0 indicates
  5994. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5995. value 1, then this tuple has not yet been copied. If the bit has
  5996. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5997. of a pointer are always zero anyways because our tuples are 8-byte
  5998. aligned.)
  5999. \begin{figure}[tbp]
  6000. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6001. \caption{Representation of tuples in the heap.}
  6002. \label{fig:tuple-rep}
  6003. \end{figure}
  6004. \subsection{Implementation of the Garbage Collector}
  6005. \label{sec:organize-gz}
  6006. \index{subject}{prelude}
  6007. An implementation of the copying collector is provided in the
  6008. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6009. interface to the garbage collector that is used by the compiler. The
  6010. \code{initialize} function creates the FromSpace, ToSpace, and root
  6011. stack and should be called in the prelude of the \code{main}
  6012. function. The arguments of \code{initialize} are the root stack size
  6013. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6014. good choice for both. The \code{initialize} function puts the address
  6015. of the beginning of the FromSpace into the global variable
  6016. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6017. the address that is 1-past the last element of the FromSpace. (We use
  6018. half-open intervals to represent chunks of
  6019. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6020. points to the first element of the root stack.
  6021. As long as there is room left in the FromSpace, your generated code
  6022. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6023. %
  6024. The amount of room left in FromSpace is the difference between the
  6025. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6026. function should be called when there is not enough room left in the
  6027. FromSpace for the next allocation. The \code{collect} function takes
  6028. a pointer to the current top of the root stack (one past the last item
  6029. that was pushed) and the number of bytes that need to be
  6030. allocated. The \code{collect} function performs the copying collection
  6031. and leaves the heap in a state such that the next allocation will
  6032. succeed.
  6033. \begin{figure}[tbp]
  6034. \begin{lstlisting}
  6035. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6036. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6037. int64_t* free_ptr;
  6038. int64_t* fromspace_begin;
  6039. int64_t* fromspace_end;
  6040. int64_t** rootstack_begin;
  6041. \end{lstlisting}
  6042. \caption{The compiler's interface to the garbage collector.}
  6043. \label{fig:gc-header}
  6044. \end{figure}
  6045. %% \begin{exercise}
  6046. %% In the file \code{runtime.c} you will find the implementation of
  6047. %% \code{initialize} and a partial implementation of \code{collect}.
  6048. %% The \code{collect} function calls another function, \code{cheney},
  6049. %% to perform the actual copy, and that function is left to the reader
  6050. %% to implement. The following is the prototype for \code{cheney}.
  6051. %% \begin{lstlisting}
  6052. %% static void cheney(int64_t** rootstack_ptr);
  6053. %% \end{lstlisting}
  6054. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6055. %% rootstack (which is an array of pointers). The \code{cheney} function
  6056. %% also communicates with \code{collect} through the global
  6057. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6058. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6059. %% the ToSpace:
  6060. %% \begin{lstlisting}
  6061. %% static int64_t* tospace_begin;
  6062. %% static int64_t* tospace_end;
  6063. %% \end{lstlisting}
  6064. %% The job of the \code{cheney} function is to copy all the live
  6065. %% objects (reachable from the root stack) into the ToSpace, update
  6066. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6067. %% update the root stack so that it points to the objects in the
  6068. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6069. %% and ToSpace.
  6070. %% \end{exercise}
  6071. %% \section{Compiler Passes}
  6072. %% \label{sec:code-generation-gc}
  6073. The introduction of garbage collection has a non-trivial impact on our
  6074. compiler passes. We introduce a new compiler pass named
  6075. \code{expose-allocation}. We make
  6076. significant changes to \code{select-instructions},
  6077. \code{build-interference}, \code{allocate-registers}, and
  6078. \code{print-x86} and make minor changes in several more passes. The
  6079. following program will serve as our running example. It creates two
  6080. tuples, one nested inside the other. Both tuples have length one. The
  6081. program accesses the element in the inner tuple tuple via two vector
  6082. references.
  6083. % tests/s2_17.rkt
  6084. \begin{lstlisting}
  6085. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6086. \end{lstlisting}
  6087. \section{Shrink}
  6088. \label{sec:shrink-Rvec}
  6089. Recall that the \code{shrink} pass translates the primitives operators
  6090. into a smaller set of primitives. Because this pass comes after type
  6091. checking, but before the passes that require the type information in
  6092. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6093. to wrap \code{HasType} around each AST node that it generates.
  6094. \section{Expose Allocation}
  6095. \label{sec:expose-allocation}
  6096. The pass \code{expose-allocation} lowers the \code{vector} creation
  6097. form into a conditional call to the collector followed by the
  6098. allocation. We choose to place the \code{expose-allocation} pass
  6099. before \code{remove-complex-opera*} because the code generated by
  6100. \code{expose-allocation} contains complex operands. We also place
  6101. \code{expose-allocation} before \code{explicate-control} because
  6102. \code{expose-allocation} introduces new variables using \code{let},
  6103. but \code{let} is gone after \code{explicate-control}.
  6104. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6105. extends \LangVec{} with the three new forms that we use in the translation
  6106. of the \code{vector} form.
  6107. \[
  6108. \begin{array}{lcl}
  6109. \Exp &::=& \cdots
  6110. \mid (\key{collect} \,\itm{int})
  6111. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6112. \mid (\key{global-value} \,\itm{name})
  6113. \end{array}
  6114. \]
  6115. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6116. $n$ bytes. It will become a call to the \code{collect} function in
  6117. \code{runtime.c} in \code{select-instructions}. The
  6118. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6119. \index{subject}{allocate}
  6120. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6121. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6122. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6123. a global variable, such as \code{free\_ptr}.
  6124. In the following, we show the transformation for the \code{vector}
  6125. form into 1) a sequence of let-bindings for the initializing
  6126. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6127. \code{allocate}, and 4) the initialization of the vector. In the
  6128. following, \itm{len} refers to the length of the vector and
  6129. \itm{bytes} is how many total bytes need to be allocated for the
  6130. vector, which is 8 for the tag plus \itm{len} times 8.
  6131. \begin{lstlisting}
  6132. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6133. |$\Longrightarrow$|
  6134. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6135. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6136. (global-value fromspace_end))
  6137. (void)
  6138. (collect |\itm{bytes}|))])
  6139. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6140. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6141. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6142. |$v$|) ... )))) ...)
  6143. \end{lstlisting}
  6144. In the above, we suppressed all of the \code{has-type} forms in the
  6145. output for the sake of readability. The placement of the initializing
  6146. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6147. sequence of \code{vector-set!} is important, as those expressions may
  6148. trigger garbage collection and we cannot have an allocated but
  6149. uninitialized tuple on the heap during a collection.
  6150. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6151. \code{expose-allocation} pass on our running example.
  6152. \begin{figure}[tbp]
  6153. % tests/s2_17.rkt
  6154. \begin{lstlisting}
  6155. (vector-ref
  6156. (vector-ref
  6157. (let ([vecinit7976
  6158. (let ([vecinit7972 42])
  6159. (let ([collectret7974
  6160. (if (< (+ (global-value free_ptr) 16)
  6161. (global-value fromspace_end))
  6162. (void)
  6163. (collect 16)
  6164. )])
  6165. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6166. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6167. alloc7971)
  6168. )
  6169. )
  6170. )
  6171. ])
  6172. (let ([collectret7978
  6173. (if (< (+ (global-value free_ptr) 16)
  6174. (global-value fromspace_end))
  6175. (void)
  6176. (collect 16)
  6177. )])
  6178. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6179. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6180. alloc7975)
  6181. )
  6182. )
  6183. )
  6184. 0)
  6185. 0)
  6186. \end{lstlisting}
  6187. \caption{Output of the \code{expose-allocation} pass, minus
  6188. all of the \code{has-type} forms.}
  6189. \label{fig:expose-alloc-output}
  6190. \end{figure}
  6191. \section{Remove Complex Operands}
  6192. \label{sec:remove-complex-opera-Rvec}
  6193. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6194. should all be treated as complex operands.
  6195. %% A new case for
  6196. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6197. %% handled carefully to prevent the \code{Prim} node from being separated
  6198. %% from its enclosing \code{HasType}.
  6199. Figure~\ref{fig:Rvec-anf-syntax}
  6200. shows the grammar for the output language \LangVecANF{} of this
  6201. pass, which is \LangVec{} in administrative normal form.
  6202. \begin{figure}[tp]
  6203. \centering
  6204. \fbox{
  6205. \begin{minipage}{0.96\textwidth}
  6206. \small
  6207. \[
  6208. \begin{array}{rcl}
  6209. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6210. \mid \VOID{} \\
  6211. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6212. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6213. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6214. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6215. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6216. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6217. \mid \LP\key{GlobalValue}~\Var\RP\\
  6218. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6219. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6220. \end{array}
  6221. \]
  6222. \end{minipage}
  6223. }
  6224. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6225. \label{fig:Rvec-anf-syntax}
  6226. \end{figure}
  6227. \section{Explicate Control and the \LangCVec{} language}
  6228. \label{sec:explicate-control-r3}
  6229. \begin{figure}[tp]
  6230. \fbox{
  6231. \begin{minipage}{0.96\textwidth}
  6232. \small
  6233. \[
  6234. \begin{array}{lcl}
  6235. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6236. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6237. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6238. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6239. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6240. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6241. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6242. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6243. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6244. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6245. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6246. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6247. \mid \GOTO{\itm{label}} } \\
  6248. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6249. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6250. \end{array}
  6251. \]
  6252. \end{minipage}
  6253. }
  6254. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6255. (Figure~\ref{fig:c1-syntax}).}
  6256. \label{fig:c2-syntax}
  6257. \end{figure}
  6258. The output of \code{explicate-control} is a program in the
  6259. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6260. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6261. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6262. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6263. \key{vector-set!}, and \key{global-value} expressions and the
  6264. \code{collect} statement. The \code{explicate-control} pass can treat
  6265. these new forms much like the other expression forms that we've
  6266. already encoutered.
  6267. \section{Select Instructions and the \LangXGlobal{} Language}
  6268. \label{sec:select-instructions-gc}
  6269. \index{subject}{instruction selection}
  6270. %% void (rep as zero)
  6271. %% allocate
  6272. %% collect (callq collect)
  6273. %% vector-ref
  6274. %% vector-set!
  6275. %% global (postpone)
  6276. In this pass we generate x86 code for most of the new operations that
  6277. were needed to compile tuples, including \code{Allocate},
  6278. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6279. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6280. the later has a different concrete syntax (see
  6281. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6282. \index{subject}{x86}
  6283. The \code{vector-ref} and \code{vector-set!} forms translate into
  6284. \code{movq} instructions. (The plus one in the offset is to get past
  6285. the tag at the beginning of the tuple representation.)
  6286. \begin{lstlisting}
  6287. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6288. |$\Longrightarrow$|
  6289. movq |$\itm{vec}'$|, %r11
  6290. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6291. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6292. |$\Longrightarrow$|
  6293. movq |$\itm{vec}'$|, %r11
  6294. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6295. movq $0, |$\itm{lhs'}$|
  6296. \end{lstlisting}
  6297. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6298. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6299. register \code{r11} ensures that offset expression
  6300. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6301. removing \code{r11} from consideration by the register allocating.
  6302. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6303. \code{rax}. Then the generated code for \code{vector-set!} would be
  6304. \begin{lstlisting}
  6305. movq |$\itm{vec}'$|, %rax
  6306. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6307. movq $0, |$\itm{lhs}'$|
  6308. \end{lstlisting}
  6309. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6310. \code{patch-instructions} would insert a move through \code{rax}
  6311. as follows.
  6312. \begin{lstlisting}
  6313. movq |$\itm{vec}'$|, %rax
  6314. movq |$\itm{arg}'$|, %rax
  6315. movq %rax, |$8(n+1)$|(%rax)
  6316. movq $0, |$\itm{lhs}'$|
  6317. \end{lstlisting}
  6318. But the above sequence of instructions does not work because we're
  6319. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6320. $\itm{arg}'$) at the same time!
  6321. We compile the \code{allocate} form to operations on the
  6322. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6323. is the next free address in the FromSpace, so we copy it into
  6324. \code{r11} and then move it forward by enough space for the tuple
  6325. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6326. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6327. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6328. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6329. tag is organized. We recommend using the Racket operations
  6330. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6331. during compilation. The type annotation in the \code{vector} form is
  6332. used to determine the pointer mask region of the tag.
  6333. \begin{lstlisting}
  6334. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6335. |$\Longrightarrow$|
  6336. movq free_ptr(%rip), %r11
  6337. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6338. movq $|$\itm{tag}$|, 0(%r11)
  6339. movq %r11, |$\itm{lhs}'$|
  6340. \end{lstlisting}
  6341. The \code{collect} form is compiled to a call to the \code{collect}
  6342. function in the runtime. The arguments to \code{collect} are 1) the
  6343. top of the root stack and 2) the number of bytes that need to be
  6344. allocated. We use another dedicated register, \code{r15}, to
  6345. store the pointer to the top of the root stack. So \code{r15} is not
  6346. available for use by the register allocator.
  6347. \begin{lstlisting}
  6348. (collect |$\itm{bytes}$|)
  6349. |$\Longrightarrow$|
  6350. movq %r15, %rdi
  6351. movq $|\itm{bytes}|, %rsi
  6352. callq collect
  6353. \end{lstlisting}
  6354. \begin{figure}[tp]
  6355. \fbox{
  6356. \begin{minipage}{0.96\textwidth}
  6357. \[
  6358. \begin{array}{lcl}
  6359. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6360. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  6361. & & \gray{ \key{main:} \; \Instr\ldots }
  6362. \end{array}
  6363. \]
  6364. \end{minipage}
  6365. }
  6366. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6367. \label{fig:x86-2-concrete}
  6368. \end{figure}
  6369. \begin{figure}[tp]
  6370. \fbox{
  6371. \begin{minipage}{0.96\textwidth}
  6372. \small
  6373. \[
  6374. \begin{array}{lcl}
  6375. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6376. \mid \BYTEREG{\Reg}} \\
  6377. &\mid& (\key{Global}~\Var) \\
  6378. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6379. \end{array}
  6380. \]
  6381. \end{minipage}
  6382. }
  6383. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6384. \label{fig:x86-2}
  6385. \end{figure}
  6386. The concrete and abstract syntax of the \LangXGlobal{} language is
  6387. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6388. differs from \LangXIf{} just in the addition of the form for global
  6389. variables.
  6390. %
  6391. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6392. \code{select-instructions} pass on the running example.
  6393. \begin{figure}[tbp]
  6394. \centering
  6395. % tests/s2_17.rkt
  6396. \begin{minipage}[t]{0.5\textwidth}
  6397. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6398. block35:
  6399. movq free_ptr(%rip), alloc9024
  6400. addq $16, free_ptr(%rip)
  6401. movq alloc9024, %r11
  6402. movq $131, 0(%r11)
  6403. movq alloc9024, %r11
  6404. movq vecinit9025, 8(%r11)
  6405. movq $0, initret9026
  6406. movq alloc9024, %r11
  6407. movq 8(%r11), tmp9034
  6408. movq tmp9034, %r11
  6409. movq 8(%r11), %rax
  6410. jmp conclusion
  6411. block36:
  6412. movq $0, collectret9027
  6413. jmp block35
  6414. block38:
  6415. movq free_ptr(%rip), alloc9020
  6416. addq $16, free_ptr(%rip)
  6417. movq alloc9020, %r11
  6418. movq $3, 0(%r11)
  6419. movq alloc9020, %r11
  6420. movq vecinit9021, 8(%r11)
  6421. movq $0, initret9022
  6422. movq alloc9020, vecinit9025
  6423. movq free_ptr(%rip), tmp9031
  6424. movq tmp9031, tmp9032
  6425. addq $16, tmp9032
  6426. movq fromspace_end(%rip), tmp9033
  6427. cmpq tmp9033, tmp9032
  6428. jl block36
  6429. jmp block37
  6430. block37:
  6431. movq %r15, %rdi
  6432. movq $16, %rsi
  6433. callq 'collect
  6434. jmp block35
  6435. block39:
  6436. movq $0, collectret9023
  6437. jmp block38
  6438. \end{lstlisting}
  6439. \end{minipage}
  6440. \begin{minipage}[t]{0.45\textwidth}
  6441. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6442. start:
  6443. movq $42, vecinit9021
  6444. movq free_ptr(%rip), tmp9028
  6445. movq tmp9028, tmp9029
  6446. addq $16, tmp9029
  6447. movq fromspace_end(%rip), tmp9030
  6448. cmpq tmp9030, tmp9029
  6449. jl block39
  6450. jmp block40
  6451. block40:
  6452. movq %r15, %rdi
  6453. movq $16, %rsi
  6454. callq 'collect
  6455. jmp block38
  6456. \end{lstlisting}
  6457. \end{minipage}
  6458. \caption{Output of the \code{select-instructions} pass.}
  6459. \label{fig:select-instr-output-gc}
  6460. \end{figure}
  6461. \clearpage
  6462. \section{Register Allocation}
  6463. \label{sec:reg-alloc-gc}
  6464. \index{subject}{register allocation}
  6465. As discussed earlier in this chapter, the garbage collector needs to
  6466. access all the pointers in the root set, that is, all variables that
  6467. are vectors. It will be the responsibility of the register allocator
  6468. to make sure that:
  6469. \begin{enumerate}
  6470. \item the root stack is used for spilling vector-typed variables, and
  6471. \item if a vector-typed variable is live during a call to the
  6472. collector, it must be spilled to ensure it is visible to the
  6473. collector.
  6474. \end{enumerate}
  6475. The later responsibility can be handled during construction of the
  6476. interference graph, by adding interference edges between the call-live
  6477. vector-typed variables and all the callee-saved registers. (They
  6478. already interfere with the caller-saved registers.) The type
  6479. information for variables is in the \code{Program} form, so we
  6480. recommend adding another parameter to the \code{build-interference}
  6481. function to communicate this alist.
  6482. The spilling of vector-typed variables to the root stack can be
  6483. handled after graph coloring, when choosing how to assign the colors
  6484. (integers) to registers and stack locations. The \code{Program} output
  6485. of this pass changes to also record the number of spills to the root
  6486. stack.
  6487. % build-interference
  6488. %
  6489. % callq
  6490. % extra parameter for var->type assoc. list
  6491. % update 'program' and 'if'
  6492. % allocate-registers
  6493. % allocate spilled vectors to the rootstack
  6494. % don't change color-graph
  6495. \section{Print x86}
  6496. \label{sec:print-x86-gc}
  6497. \index{subject}{prelude}\index{subject}{conclusion}
  6498. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6499. \code{print-x86} pass on the running example. In the prelude and
  6500. conclusion of the \code{main} function, we treat the root stack very
  6501. much like the regular stack in that we move the root stack pointer
  6502. (\code{r15}) to make room for the spills to the root stack, except
  6503. that the root stack grows up instead of down. For the running
  6504. example, there was just one spill so we increment \code{r15} by 8
  6505. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6506. One issue that deserves special care is that there may be a call to
  6507. \code{collect} prior to the initializing assignments for all the
  6508. variables in the root stack. We do not want the garbage collector to
  6509. accidentally think that some uninitialized variable is a pointer that
  6510. needs to be followed. Thus, we zero-out all locations on the root
  6511. stack in the prelude of \code{main}. In
  6512. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6513. %
  6514. \lstinline{movq $0, (%r15)}
  6515. %
  6516. accomplishes this task. The garbage collector tests each root to see
  6517. if it is null prior to dereferencing it.
  6518. \begin{figure}[htbp]
  6519. \begin{minipage}[t]{0.5\textwidth}
  6520. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6521. block35:
  6522. movq free_ptr(%rip), %rcx
  6523. addq $16, free_ptr(%rip)
  6524. movq %rcx, %r11
  6525. movq $131, 0(%r11)
  6526. movq %rcx, %r11
  6527. movq -8(%r15), %rax
  6528. movq %rax, 8(%r11)
  6529. movq $0, %rdx
  6530. movq %rcx, %r11
  6531. movq 8(%r11), %rcx
  6532. movq %rcx, %r11
  6533. movq 8(%r11), %rax
  6534. jmp conclusion
  6535. block36:
  6536. movq $0, %rcx
  6537. jmp block35
  6538. block38:
  6539. movq free_ptr(%rip), %rcx
  6540. addq $16, free_ptr(%rip)
  6541. movq %rcx, %r11
  6542. movq $3, 0(%r11)
  6543. movq %rcx, %r11
  6544. movq %rbx, 8(%r11)
  6545. movq $0, %rdx
  6546. movq %rcx, -8(%r15)
  6547. movq free_ptr(%rip), %rcx
  6548. addq $16, %rcx
  6549. movq fromspace_end(%rip), %rdx
  6550. cmpq %rdx, %rcx
  6551. jl block36
  6552. movq %r15, %rdi
  6553. movq $16, %rsi
  6554. callq collect
  6555. jmp block35
  6556. block39:
  6557. movq $0, %rcx
  6558. jmp block38
  6559. \end{lstlisting}
  6560. \end{minipage}
  6561. \begin{minipage}[t]{0.45\textwidth}
  6562. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6563. start:
  6564. movq $42, %rbx
  6565. movq free_ptr(%rip), %rdx
  6566. addq $16, %rdx
  6567. movq fromspace_end(%rip), %rcx
  6568. cmpq %rcx, %rdx
  6569. jl block39
  6570. movq %r15, %rdi
  6571. movq $16, %rsi
  6572. callq collect
  6573. jmp block38
  6574. .globl main
  6575. main:
  6576. pushq %rbp
  6577. movq %rsp, %rbp
  6578. pushq %r13
  6579. pushq %r12
  6580. pushq %rbx
  6581. pushq %r14
  6582. subq $0, %rsp
  6583. movq $16384, %rdi
  6584. movq $16384, %rsi
  6585. callq initialize
  6586. movq rootstack_begin(%rip), %r15
  6587. movq $0, (%r15)
  6588. addq $8, %r15
  6589. jmp start
  6590. conclusion:
  6591. subq $8, %r15
  6592. addq $0, %rsp
  6593. popq %r14
  6594. popq %rbx
  6595. popq %r12
  6596. popq %r13
  6597. popq %rbp
  6598. retq
  6599. \end{lstlisting}
  6600. \end{minipage}
  6601. \caption{Output of the \code{print-x86} pass.}
  6602. \label{fig:print-x86-output-gc}
  6603. \end{figure}
  6604. \begin{figure}[p]
  6605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6606. \node (Rvec) at (0,2) {\large \LangVec{}};
  6607. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6608. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6609. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6610. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6611. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6612. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6613. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6614. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6615. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6616. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6617. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6618. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6619. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6620. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6621. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6622. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6623. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6624. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6625. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6626. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6627. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6628. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6629. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6630. \end{tikzpicture}
  6631. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6632. \label{fig:Rvec-passes}
  6633. \end{figure}
  6634. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6635. for the compilation of \LangVec{}.
  6636. \section{Challenge: Simple Structures}
  6637. \label{sec:simple-structures}
  6638. \index{subject}{struct}
  6639. \index{subject}{structure}
  6640. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6641. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6642. Recall that a \code{struct} in Typed Racket is a user-defined data
  6643. type that contains named fields and that is heap allocated, similar to
  6644. a vector. The following is an example of a structure definition, in
  6645. this case the definition of a \code{point} type.
  6646. \begin{lstlisting}
  6647. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6648. \end{lstlisting}
  6649. \begin{figure}[tbp]
  6650. \centering
  6651. \fbox{
  6652. \begin{minipage}{0.96\textwidth}
  6653. \[
  6654. \begin{array}{lcl}
  6655. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6656. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6657. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6658. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6659. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6660. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6661. \mid (\key{and}\;\Exp\;\Exp)
  6662. \mid (\key{or}\;\Exp\;\Exp)
  6663. \mid (\key{not}\;\Exp) } \\
  6664. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6665. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6666. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6667. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6668. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6669. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6670. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6671. \LangStruct{} &::=& \Def \ldots \; \Exp
  6672. \end{array}
  6673. \]
  6674. \end{minipage}
  6675. }
  6676. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6677. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6678. \label{fig:r3s-concrete-syntax}
  6679. \end{figure}
  6680. An instance of a structure is created using function call syntax, with
  6681. the name of the structure in the function position:
  6682. \begin{lstlisting}
  6683. (point 7 12)
  6684. \end{lstlisting}
  6685. Function-call syntax is also used to read the value in a field of a
  6686. structure. The function name is formed by the structure name, a dash,
  6687. and the field name. The following example uses \code{point-x} and
  6688. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6689. instances.
  6690. \begin{center}
  6691. \begin{lstlisting}
  6692. (let ([pt1 (point 7 12)])
  6693. (let ([pt2 (point 4 3)])
  6694. (+ (- (point-x pt1) (point-x pt2))
  6695. (- (point-y pt1) (point-y pt2)))))
  6696. \end{lstlisting}
  6697. \end{center}
  6698. Similarly, to write to a field of a structure, use its set function,
  6699. whose name starts with \code{set-}, followed by the structure name,
  6700. then a dash, then the field name, and concluded with an exclamation
  6701. mark. The following example uses \code{set-point-x!} to change the
  6702. \code{x} field from \code{7} to \code{42}.
  6703. \begin{center}
  6704. \begin{lstlisting}
  6705. (let ([pt (point 7 12)])
  6706. (let ([_ (set-point-x! pt 42)])
  6707. (point-x pt)))
  6708. \end{lstlisting}
  6709. \end{center}
  6710. \begin{exercise}\normalfont
  6711. Extend your compiler with support for simple structures, compiling
  6712. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6713. structures and test your compiler.
  6714. \end{exercise}
  6715. \section{Challenge: Generational Collection}
  6716. The copying collector described in Section~\ref{sec:GC} can incur
  6717. significant runtime overhead because the call to \code{collect} takes
  6718. time proportional to all of the live data. One way to reduce this
  6719. overhead is to reduce how much data is inspected in each call to
  6720. \code{collect}. In particular, researchers have observed that recently
  6721. allocated data is more likely to become garbage then data that has
  6722. survived one or more previous calls to \code{collect}. This insight
  6723. motivated the creation of \emph{generational garbage collectors}
  6724. \index{subject}{generational garbage collector} that
  6725. 1) segregates data according to its age into two or more generations,
  6726. 2) allocates less space for younger generations, so collecting them is
  6727. faster, and more space for the older generations, and 3) performs
  6728. collection on the younger generations more frequently then for older
  6729. generations~\citep{Wilson:1992fk}.
  6730. For this challenge assignment, the goal is to adapt the copying
  6731. collector implemented in \code{runtime.c} to use two generations, one
  6732. for young data and one for old data. Each generation consists of a
  6733. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6734. \code{collect} function to use the two generations.
  6735. \begin{enumerate}
  6736. \item Copy the young generation's FromSpace to its ToSpace then switch
  6737. the role of the ToSpace and FromSpace
  6738. \item If there is enough space for the requested number of bytes in
  6739. the young FromSpace, then return from \code{collect}.
  6740. \item If there is not enough space in the young FromSpace for the
  6741. requested bytes, then move the data from the young generation to the
  6742. old one with the following steps:
  6743. \begin{enumerate}
  6744. \item If there is enough room in the old FromSpace, copy the young
  6745. FromSpace to the old FromSpace and then return.
  6746. \item If there is not enough room in the old FromSpace, then collect
  6747. the old generation by copying the old FromSpace to the old ToSpace
  6748. and swap the roles of the old FromSpace and ToSpace.
  6749. \item If there is enough room now, copy the young FromSpace to the
  6750. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6751. and ToSpace for the old generation. Copy the young FromSpace and
  6752. the old FromSpace into the larger FromSpace for the old
  6753. generation and then return.
  6754. \end{enumerate}
  6755. \end{enumerate}
  6756. We recommend that you generalize the \code{cheney} function so that it
  6757. can be used for all the copies mentioned above: between the young
  6758. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6759. between the young FromSpace and old FromSpace. This can be
  6760. accomplished by adding parameters to \code{cheney} that replace its
  6761. use of the global variables \code{fromspace\_begin},
  6762. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6763. Note that the collection of the young generation does not traverse the
  6764. old generation. This introduces a potential problem: there may be
  6765. young data that is only reachable through pointers in the old
  6766. generation. If these pointers are not taken into account, the
  6767. collector could throw away young data that is live! One solution,
  6768. called \emph{pointer recording}, is to maintain a set of all the
  6769. pointers from the old generation into the new generation and consider
  6770. this set as part of the root set. To maintain this set, the compiler
  6771. must insert extra instructions around every \code{vector-set!}. If the
  6772. vector being modified is in the old generation, and if the value being
  6773. written is a pointer into the new generation, than that pointer must
  6774. be added to the set. Also, if the value being overwritten was a
  6775. pointer into the new generation, then that pointer should be removed
  6776. from the set.
  6777. \begin{exercise}\normalfont
  6778. Adapt the \code{collect} function in \code{runtime.c} to implement
  6779. generational garbage collection, as outlined in this section.
  6780. Update the code generation for \code{vector-set!} to implement
  6781. pointer recording. Make sure that your new compiler and runtime
  6782. passes your test suite.
  6783. \end{exercise}
  6784. % Further Reading
  6785. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6786. \chapter{Functions}
  6787. \label{ch:Rfun}
  6788. \index{subject}{function}
  6789. This chapter studies the compilation of functions similar to those
  6790. found in the C language. This corresponds to a subset of Typed Racket
  6791. in which only top-level function definitions are allowed. This kind of
  6792. function is an important stepping stone to implementing
  6793. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6794. is the topic of Chapter~\ref{ch:Rlam}.
  6795. \section{The \LangFun{} Language}
  6796. The concrete and abstract syntax for function definitions and function
  6797. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6798. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6799. \LangFun{} begin with zero or more function definitions. The function
  6800. names from these definitions are in-scope for the entire program,
  6801. including all other function definitions (so the ordering of function
  6802. definitions does not matter). The concrete syntax for function
  6803. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  6804. where the first expression must
  6805. evaluate to a function and the rest are the arguments.
  6806. The abstract syntax for function application is
  6807. $\APPLY{\Exp}{\Exp\ldots}$.
  6808. %% The syntax for function application does not include an explicit
  6809. %% keyword, which is error prone when using \code{match}. To alleviate
  6810. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6811. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6812. Functions are first-class in the sense that a function pointer
  6813. \index{subject}{function pointer} is data and can be stored in memory or passed
  6814. as a parameter to another function. Thus, we introduce a function
  6815. type, written
  6816. \begin{lstlisting}
  6817. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6818. \end{lstlisting}
  6819. for a function whose $n$ parameters have the types $\Type_1$ through
  6820. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6821. these functions (with respect to Racket functions) is that they are
  6822. not lexically scoped. That is, the only external entities that can be
  6823. referenced from inside a function body are other globally-defined
  6824. functions. The syntax of \LangFun{} prevents functions from being nested
  6825. inside each other.
  6826. \begin{figure}[tp]
  6827. \centering
  6828. \fbox{
  6829. \begin{minipage}{0.96\textwidth}
  6830. \small
  6831. \[
  6832. \begin{array}{lcl}
  6833. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6834. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6835. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6836. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6837. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6838. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6839. \mid (\key{and}\;\Exp\;\Exp)
  6840. \mid (\key{or}\;\Exp\;\Exp)
  6841. \mid (\key{not}\;\Exp)} \\
  6842. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6843. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6844. (\key{vector-ref}\;\Exp\;\Int)} \\
  6845. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6846. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6847. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6848. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6849. \LangFunM{} &::=& \Def \ldots \; \Exp
  6850. \end{array}
  6851. \]
  6852. \end{minipage}
  6853. }
  6854. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6855. \label{fig:Rfun-concrete-syntax}
  6856. \end{figure}
  6857. \begin{figure}[tp]
  6858. \centering
  6859. \fbox{
  6860. \begin{minipage}{0.96\textwidth}
  6861. \small
  6862. \[
  6863. \begin{array}{lcl}
  6864. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6865. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6866. &\mid& \gray{ \BOOL{\itm{bool}}
  6867. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6868. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6869. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6870. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6871. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6872. \end{array}
  6873. \]
  6874. \end{minipage}
  6875. }
  6876. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6877. \label{fig:Rfun-syntax}
  6878. \end{figure}
  6879. The program in Figure~\ref{fig:Rfun-function-example} is a
  6880. representative example of defining and using functions in \LangFun{}. We
  6881. define a function \code{map-vec} that applies some other function
  6882. \code{f} to both elements of a vector and returns a new
  6883. vector containing the results. We also define a function \code{add1}.
  6884. The program applies
  6885. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6886. \code{(vector 1 42)}, from which we return the \code{42}.
  6887. \begin{figure}[tbp]
  6888. \begin{lstlisting}
  6889. (define (map-vec [f : (Integer -> Integer)]
  6890. [v : (Vector Integer Integer)])
  6891. : (Vector Integer Integer)
  6892. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6893. (define (add1 [x : Integer]) : Integer
  6894. (+ x 1))
  6895. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6896. \end{lstlisting}
  6897. \caption{Example of using functions in \LangFun{}.}
  6898. \label{fig:Rfun-function-example}
  6899. \end{figure}
  6900. The definitional interpreter for \LangFun{} is in
  6901. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6902. responsible for setting up the mutual recursion between the top-level
  6903. function definitions. We use the classic back-patching \index{subject}{back-patching}
  6904. approach that uses mutable variables and makes two passes over the function
  6905. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6906. top-level environment using a mutable cons cell for each function
  6907. definition. Note that the \code{lambda} value for each function is
  6908. incomplete; it does not yet include the environment. Once the
  6909. top-level environment is constructed, we then iterate over it and
  6910. update the \code{lambda} values to use the top-level environment.
  6911. \begin{figure}[tp]
  6912. \begin{lstlisting}
  6913. (define interp-Rfun-class
  6914. (class interp-Rvec-class
  6915. (super-new)
  6916. (define/override ((interp-exp env) e)
  6917. (define recur (interp-exp env))
  6918. (match e
  6919. [(Var x) (unbox (dict-ref env x))]
  6920. [(Let x e body)
  6921. (define new-env (dict-set env x (box (recur e))))
  6922. ((interp-exp new-env) body)]
  6923. [(Apply fun args)
  6924. (define fun-val (recur fun))
  6925. (define arg-vals (for/list ([e args]) (recur e)))
  6926. (match fun-val
  6927. [`(function (,xs ...) ,body ,fun-env)
  6928. (define params-args (for/list ([x xs] [arg arg-vals])
  6929. (cons x (box arg))))
  6930. (define new-env (append params-args fun-env))
  6931. ((interp-exp new-env) body)]
  6932. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6933. [else ((super interp-exp env) e)]
  6934. ))
  6935. (define/public (interp-def d)
  6936. (match d
  6937. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6938. (cons f (box `(function ,xs ,body ())))]))
  6939. (define/override (interp-program p)
  6940. (match p
  6941. [(ProgramDefsExp info ds body)
  6942. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6943. (for/list ([f (in-dict-values top-level)])
  6944. (set-box! f (match (unbox f)
  6945. [`(function ,xs ,body ())
  6946. `(function ,xs ,body ,top-level)])))
  6947. ((interp-exp top-level) body))]))
  6948. ))
  6949. (define (interp-Rfun p)
  6950. (send (new interp-Rfun-class) interp-program p))
  6951. \end{lstlisting}
  6952. \caption{Interpreter for the \LangFun{} language.}
  6953. \label{fig:interp-Rfun}
  6954. \end{figure}
  6955. %\margincomment{TODO: explain type checker}
  6956. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  6957. \begin{figure}[tp]
  6958. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6959. (define type-check-Rfun-class
  6960. (class type-check-Rvec-class
  6961. (super-new)
  6962. (inherit check-type-equal?)
  6963. (define/public (type-check-apply env e es)
  6964. (define-values (e^ ty) ((type-check-exp env) e))
  6965. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6966. ((type-check-exp env) e)))
  6967. (match ty
  6968. [`(,ty^* ... -> ,rt)
  6969. (for ([arg-ty ty*] [param-ty ty^*])
  6970. (check-type-equal? arg-ty param-ty (Apply e es)))
  6971. (values e^ e* rt)]))
  6972. (define/override (type-check-exp env)
  6973. (lambda (e)
  6974. (match e
  6975. [(FunRef f)
  6976. (values (FunRef f) (dict-ref env f))]
  6977. [(Apply e es)
  6978. (define-values (e^ es^ rt) (type-check-apply env e es))
  6979. (values (Apply e^ es^) rt)]
  6980. [(Call e es)
  6981. (define-values (e^ es^ rt) (type-check-apply env e es))
  6982. (values (Call e^ es^) rt)]
  6983. [else ((super type-check-exp env) e)])))
  6984. (define/public (type-check-def env)
  6985. (lambda (e)
  6986. (match e
  6987. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6988. (define new-env (append (map cons xs ps) env))
  6989. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6990. (check-type-equal? ty^ rt body)
  6991. (Def f p:t* rt info body^)])))
  6992. (define/public (fun-def-type d)
  6993. (match d
  6994. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6995. (define/override (type-check-program e)
  6996. (match e
  6997. [(ProgramDefsExp info ds body)
  6998. (define new-env (for/list ([d ds])
  6999. (cons (Def-name d) (fun-def-type d))))
  7000. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7001. (define-values (body^ ty) ((type-check-exp new-env) body))
  7002. (check-type-equal? ty 'Integer body)
  7003. (ProgramDefsExp info ds^ body^)]))))
  7004. (define (type-check-Rfun p)
  7005. (send (new type-check-Rfun-class) type-check-program p))
  7006. \end{lstlisting}
  7007. \caption{Type checker for the \LangFun{} language.}
  7008. \label{fig:type-check-Rfun}
  7009. \end{figure}
  7010. \section{Functions in x86}
  7011. \label{sec:fun-x86}
  7012. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  7013. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7014. %% \margincomment{\tiny Talk about the return address on the
  7015. %% stack and what callq and retq does.\\ --Jeremy }
  7016. The x86 architecture provides a few features to support the
  7017. implementation of functions. We have already seen that x86 provides
  7018. labels so that one can refer to the location of an instruction, as is
  7019. needed for jump instructions. Labels can also be used to mark the
  7020. beginning of the instructions for a function. Going further, we can
  7021. obtain the address of a label by using the \key{leaq} instruction and
  7022. PC-relative addressing. For example, the following puts the
  7023. address of the \code{add1} label into the \code{rbx} register.
  7024. \begin{lstlisting}
  7025. leaq add1(%rip), %rbx
  7026. \end{lstlisting}
  7027. The instruction pointer register \key{rip} (aka. the program counter
  7028. \index{subject}{program counter}) always points to the next instruction to be
  7029. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7030. linker computes the distance $d$ between the address of \code{add1}
  7031. and where the \code{rip} would be at that moment and then changes
  7032. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7033. the address of \code{add1}.
  7034. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7035. jump to a function whose location is given by a label. To support
  7036. function calls in this chapter we instead will be jumping to a
  7037. function whose location is given by an address in a register, that is,
  7038. we need to make an \emph{indirect function call}. The x86 syntax for
  7039. this is a \code{callq} instruction but with an asterisk before the
  7040. register name.\index{subject}{indirect function call}
  7041. \begin{lstlisting}
  7042. callq *%rbx
  7043. \end{lstlisting}
  7044. \subsection{Calling Conventions}
  7045. \index{subject}{calling conventions}
  7046. The \code{callq} instruction provides partial support for implementing
  7047. functions: it pushes the return address on the stack and it jumps to
  7048. the target. However, \code{callq} does not handle
  7049. \begin{enumerate}
  7050. \item parameter passing,
  7051. \item pushing frames on the procedure call stack and popping them off,
  7052. or
  7053. \item determining how registers are shared by different functions.
  7054. \end{enumerate}
  7055. Regarding (1) parameter passing, recall that the following six
  7056. registers are used to pass arguments to a function, in this order.
  7057. \begin{lstlisting}
  7058. rdi rsi rdx rcx r8 r9
  7059. \end{lstlisting}
  7060. If there are
  7061. more than six arguments, then the convention is to use space on the
  7062. frame of the caller for the rest of the arguments. However, to ease
  7063. the implementation of efficient tail calls
  7064. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7065. arguments.
  7066. %
  7067. Also recall that the register \code{rax} is for the return value of
  7068. the function.
  7069. \index{subject}{prelude}\index{subject}{conclusion}
  7070. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  7071. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  7072. the stack grows down, with each function call using a chunk of space
  7073. called a frame. The caller sets the stack pointer, register
  7074. \code{rsp}, to the last data item in its frame. The callee must not
  7075. change anything in the caller's frame, that is, anything that is at or
  7076. above the stack pointer. The callee is free to use locations that are
  7077. below the stack pointer.
  7078. Recall that we are storing variables of vector type on the root stack.
  7079. So the prelude needs to move the root stack pointer \code{r15} up and
  7080. the conclusion needs to move the root stack pointer back down. Also,
  7081. the prelude must initialize to \code{0} this frame's slots in the root
  7082. stack to signal to the garbage collector that those slots do not yet
  7083. contain a pointer to a vector. Otherwise the garbage collector will
  7084. interpret the garbage bits in those slots as memory addresses and try
  7085. to traverse them, causing serious mayhem!
  7086. Regarding (3) the sharing of registers between different functions,
  7087. recall from Section~\ref{sec:calling-conventions} that the registers
  7088. are divided into two groups, the caller-saved registers and the
  7089. callee-saved registers. The caller should assume that all the
  7090. caller-saved registers get overwritten with arbitrary values by the
  7091. callee. That is why we recommend in
  7092. Section~\ref{sec:calling-conventions} that variables that are live
  7093. during a function call should not be assigned to caller-saved
  7094. registers.
  7095. On the flip side, if the callee wants to use a callee-saved register,
  7096. the callee must save the contents of those registers on their stack
  7097. frame and then put them back prior to returning to the caller. That
  7098. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7099. the register allocator assigns a variable to a callee-saved register,
  7100. then the prelude of the \code{main} function must save that register
  7101. to the stack and the conclusion of \code{main} must restore it. This
  7102. recommendation now generalizes to all functions.
  7103. Also recall that the base pointer, register \code{rbp}, is used as a
  7104. point-of-reference within a frame, so that each local variable can be
  7105. accessed at a fixed offset from the base pointer
  7106. (Section~\ref{sec:x86}).
  7107. %
  7108. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7109. and callee frames.
  7110. \begin{figure}[tbp]
  7111. \centering
  7112. \begin{tabular}{r|r|l|l} \hline
  7113. Caller View & Callee View & Contents & Frame \\ \hline
  7114. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7115. 0(\key{\%rbp}) & & old \key{rbp} \\
  7116. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7117. \ldots & & \ldots \\
  7118. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7119. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7120. \ldots & & \ldots \\
  7121. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7122. %% & & \\
  7123. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7124. %% & \ldots & \ldots \\
  7125. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7126. \hline
  7127. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7128. & 0(\key{\%rbp}) & old \key{rbp} \\
  7129. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7130. & \ldots & \ldots \\
  7131. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7132. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7133. & \ldots & \ldots \\
  7134. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7135. \end{tabular}
  7136. \caption{Memory layout of caller and callee frames.}
  7137. \label{fig:call-frames}
  7138. \end{figure}
  7139. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7140. %% local variables and for storing the values of callee-saved registers
  7141. %% (we shall refer to all of these collectively as ``locals''), and that
  7142. %% at the beginning of a function we move the stack pointer \code{rsp}
  7143. %% down to make room for them.
  7144. %% We recommend storing the local variables
  7145. %% first and then the callee-saved registers, so that the local variables
  7146. %% can be accessed using \code{rbp} the same as before the addition of
  7147. %% functions.
  7148. %% To make additional room for passing arguments, we shall
  7149. %% move the stack pointer even further down. We count how many stack
  7150. %% arguments are needed for each function call that occurs inside the
  7151. %% body of the function and find their maximum. Adding this number to the
  7152. %% number of locals gives us how much the \code{rsp} should be moved at
  7153. %% the beginning of the function. In preparation for a function call, we
  7154. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7155. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7156. %% so on.
  7157. %% Upon calling the function, the stack arguments are retrieved by the
  7158. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7159. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7160. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7161. %% the layout of the caller and callee frames. Notice how important it is
  7162. %% that we correctly compute the maximum number of arguments needed for
  7163. %% function calls; if that number is too small then the arguments and
  7164. %% local variables will smash into each other!
  7165. \subsection{Efficient Tail Calls}
  7166. \label{sec:tail-call}
  7167. In general, the amount of stack space used by a program is determined
  7168. by the longest chain of nested function calls. That is, if function
  7169. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7170. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7171. $n$ can grow quite large in the case of recursive or mutually
  7172. recursive functions. However, in some cases we can arrange to use only
  7173. constant space, i.e. $O(1)$, instead of $O(n)$.
  7174. If a function call is the last action in a function body, then that
  7175. call is said to be a \emph{tail call}\index{subject}{tail call}.
  7176. For example, in the following
  7177. program, the recursive call to \code{tail-sum} is a tail call.
  7178. \begin{center}
  7179. \begin{lstlisting}
  7180. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7181. (if (eq? n 0)
  7182. r
  7183. (tail-sum (- n 1) (+ n r))))
  7184. (+ (tail-sum 5 0) 27)
  7185. \end{lstlisting}
  7186. \end{center}
  7187. At a tail call, the frame of the caller is no longer needed, so we
  7188. can pop the caller's frame before making the tail call. With this
  7189. approach, a recursive function that only makes tail calls will only
  7190. use $O(1)$ stack space. Functional languages like Racket typically
  7191. rely heavily on recursive functions, so they typically guarantee that
  7192. all tail calls will be optimized in this way.
  7193. \index{subject}{frame}
  7194. However, some care is needed with regards to argument passing in tail
  7195. calls. As mentioned above, for arguments beyond the sixth, the
  7196. convention is to use space in the caller's frame for passing
  7197. arguments. But for a tail call we pop the caller's frame and can no
  7198. longer use it. Another alternative is to use space in the callee's
  7199. frame for passing arguments. However, this option is also problematic
  7200. because the caller and callee's frame overlap in memory. As we begin
  7201. to copy the arguments from their sources in the caller's frame, the
  7202. target locations in the callee's frame might overlap with the sources
  7203. for later arguments! We solve this problem by not using the stack for
  7204. passing more than six arguments but instead using the heap, as we
  7205. describe in the Section~\ref{sec:limit-functions-r4}.
  7206. As mentioned above, for a tail call we pop the caller's frame prior to
  7207. making the tail call. The instructions for popping a frame are the
  7208. instructions that we usually place in the conclusion of a
  7209. function. Thus, we also need to place such code immediately before
  7210. each tail call. These instructions include restoring the callee-saved
  7211. registers, so it is good that the argument passing registers are all
  7212. caller-saved registers.
  7213. One last note regarding which instruction to use to make the tail
  7214. call. When the callee is finished, it should not return to the current
  7215. function, but it should return to the function that called the current
  7216. one. Thus, the return address that is already on the stack is the
  7217. right one, and we should not use \key{callq} to make the tail call, as
  7218. that would unnecessarily overwrite the return address. Instead we can
  7219. simply use the \key{jmp} instruction. Like the indirect function call,
  7220. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  7221. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7222. jump target because the preceding conclusion overwrites just about
  7223. everything else.
  7224. \begin{lstlisting}
  7225. jmp *%rax
  7226. \end{lstlisting}
  7227. \section{Shrink \LangFun{}}
  7228. \label{sec:shrink-r4}
  7229. The \code{shrink} pass performs a minor modification to ease the
  7230. later passes. This pass introduces an explicit \code{main} function
  7231. and changes the top \code{ProgramDefsExp} form to
  7232. \code{ProgramDefs} as follows.
  7233. \begin{lstlisting}
  7234. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7235. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7236. \end{lstlisting}
  7237. where $\itm{mainDef}$ is
  7238. \begin{lstlisting}
  7239. (Def 'main '() 'Integer '() |$\Exp'$|)
  7240. \end{lstlisting}
  7241. \section{Reveal Functions and the \LangFunRef{} language}
  7242. \label{sec:reveal-functions-r4}
  7243. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7244. respect: it conflates the use of function names and local
  7245. variables. This is a problem because we need to compile the use of a
  7246. function name differently than the use of a local variable; we need to
  7247. use \code{leaq} to convert the function name (a label in x86) to an
  7248. address in a register. Thus, it is a good idea to create a new pass
  7249. that changes function references from just a symbol $f$ to
  7250. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7251. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7252. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7253. \begin{figure}[tp]
  7254. \centering
  7255. \fbox{
  7256. \begin{minipage}{0.96\textwidth}
  7257. \[
  7258. \begin{array}{lcl}
  7259. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7260. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7261. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7262. \end{array}
  7263. \]
  7264. \end{minipage}
  7265. }
  7266. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7267. (Figure~\ref{fig:Rfun-syntax}).}
  7268. \label{fig:f1-syntax}
  7269. \end{figure}
  7270. %% Distinguishing between calls in tail position and non-tail position
  7271. %% requires the pass to have some notion of context. We recommend using
  7272. %% two mutually recursive functions, one for processing expressions in
  7273. %% tail position and another for the rest.
  7274. Placing this pass after \code{uniquify} will make sure that there are
  7275. no local variables and functions that share the same name. On the
  7276. other hand, \code{reveal-functions} needs to come before the
  7277. \code{explicate-control} pass because that pass helps us compile
  7278. \code{FunRef} forms into assignment statements.
  7279. \section{Limit Functions}
  7280. \label{sec:limit-functions-r4}
  7281. Recall that we wish to limit the number of function parameters to six
  7282. so that we do not need to use the stack for argument passing, which
  7283. makes it easier to implement efficient tail calls. However, because
  7284. the input language \LangFun{} supports arbitrary numbers of function
  7285. arguments, we have some work to do!
  7286. This pass transforms functions and function calls that involve more
  7287. than six arguments to pass the first five arguments as usual, but it
  7288. packs the rest of the arguments into a vector and passes it as the
  7289. sixth argument.
  7290. Each function definition with too many parameters is transformed as
  7291. follows.
  7292. \begin{lstlisting}
  7293. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7294. |$\Rightarrow$|
  7295. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7296. \end{lstlisting}
  7297. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7298. the occurrences of the later parameters with vector references.
  7299. \begin{lstlisting}
  7300. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7301. \end{lstlisting}
  7302. For function calls with too many arguments, the \code{limit-functions}
  7303. pass transforms them in the following way.
  7304. \begin{tabular}{lll}
  7305. \begin{minipage}{0.2\textwidth}
  7306. \begin{lstlisting}
  7307. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7308. \end{lstlisting}
  7309. \end{minipage}
  7310. &
  7311. $\Rightarrow$
  7312. &
  7313. \begin{minipage}{0.4\textwidth}
  7314. \begin{lstlisting}
  7315. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7316. \end{lstlisting}
  7317. \end{minipage}
  7318. \end{tabular}
  7319. \section{Remove Complex Operands}
  7320. \label{sec:rco-r4}
  7321. The primary decisions to make for this pass is whether to classify
  7322. \code{FunRef} and \code{Apply} as either atomic or complex
  7323. expressions. Recall that a simple expression will eventually end up as
  7324. just an immediate argument of an x86 instruction. Function
  7325. application will be translated to a sequence of instructions, so
  7326. \code{Apply} must be classified as complex expression.
  7327. On the other hand, the arguments of \code{Apply} should be
  7328. atomic expressions.
  7329. %
  7330. Regarding \code{FunRef}, as discussed above, the function label needs
  7331. to be converted to an address using the \code{leaq} instruction. Thus,
  7332. even though \code{FunRef} seems rather simple, it needs to be
  7333. classified as a complex expression so that we generate an assignment
  7334. statement with a left-hand side that can serve as the target of the
  7335. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7336. output language \LangFunANF{} of this pass.
  7337. \begin{figure}[tp]
  7338. \centering
  7339. \fbox{
  7340. \begin{minipage}{0.96\textwidth}
  7341. \small
  7342. \[
  7343. \begin{array}{rcl}
  7344. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7345. \mid \VOID{} } \\
  7346. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7347. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7348. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7349. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7350. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7351. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7352. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7353. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7354. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7355. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7356. \end{array}
  7357. \]
  7358. \end{minipage}
  7359. }
  7360. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7361. \label{fig:Rfun-anf-syntax}
  7362. \end{figure}
  7363. \section{Explicate Control and the \LangCFun{} language}
  7364. \label{sec:explicate-control-r4}
  7365. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7366. output of \key{explicate-control}. (The concrete syntax is given in
  7367. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7368. functions for assignment and tail contexts should be updated with
  7369. cases for \code{Apply} and \code{FunRef} and the function for
  7370. predicate context should be updated for \code{Apply} but not
  7371. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7372. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7373. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7374. defining a new auxiliary function for processing function definitions.
  7375. This code is similar to the case for \code{Program} in \LangVec{}. The
  7376. top-level \code{explicate-control} function that handles the
  7377. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7378. all the function definitions.
  7379. \begin{figure}[tp]
  7380. \fbox{
  7381. \begin{minipage}{0.96\textwidth}
  7382. \small
  7383. \[
  7384. \begin{array}{lcl}
  7385. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7386. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7387. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7388. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7389. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7390. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7391. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7392. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7393. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7394. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7395. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7396. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7397. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7398. \mid \GOTO{\itm{label}} } \\
  7399. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7400. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7401. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7402. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7403. \end{array}
  7404. \]
  7405. \end{minipage}
  7406. }
  7407. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7408. \label{fig:c3-syntax}
  7409. \end{figure}
  7410. \section{Select Instructions and the \LangXIndCall{} Language}
  7411. \label{sec:select-r4}
  7412. \index{subject}{instruction selection}
  7413. The output of select instructions is a program in the \LangXIndCall{}
  7414. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7415. \index{subject}{x86}
  7416. \begin{figure}[tp]
  7417. \fbox{
  7418. \begin{minipage}{0.96\textwidth}
  7419. \small
  7420. \[
  7421. \begin{array}{lcl}
  7422. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7423. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7424. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7425. \Instr &::=& \ldots
  7426. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7427. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7428. \Block &::= & \Instr\ldots \\
  7429. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7430. \LangXIndCallM{} &::= & \Def\ldots
  7431. \end{array}
  7432. \]
  7433. \end{minipage}
  7434. }
  7435. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7436. \label{fig:x86-3-concrete}
  7437. \end{figure}
  7438. \begin{figure}[tp]
  7439. \fbox{
  7440. \begin{minipage}{0.96\textwidth}
  7441. \small
  7442. \[
  7443. \begin{array}{lcl}
  7444. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7445. \mid \BYTEREG{\Reg} } \\
  7446. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7447. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7448. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7449. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7450. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7451. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7452. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7453. \end{array}
  7454. \]
  7455. \end{minipage}
  7456. }
  7457. \caption{The abstract syntax of \LangXIndCall{} (extends
  7458. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7459. \label{fig:x86-3}
  7460. \end{figure}
  7461. An assignment of a function reference to a variable becomes a
  7462. load-effective-address instruction as follows: \\
  7463. \begin{tabular}{lcl}
  7464. \begin{minipage}{0.35\textwidth}
  7465. \begin{lstlisting}
  7466. |$\itm{lhs}$| = (fun-ref |$f$|);
  7467. \end{lstlisting}
  7468. \end{minipage}
  7469. &
  7470. $\Rightarrow$\qquad\qquad
  7471. &
  7472. \begin{minipage}{0.3\textwidth}
  7473. \begin{lstlisting}
  7474. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7475. \end{lstlisting}
  7476. \end{minipage}
  7477. \end{tabular} \\
  7478. Regarding function definitions, we need to remove the parameters and
  7479. instead perform parameter passing using the conventions discussed in
  7480. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7481. registers. We recommend turning the parameters into local variables
  7482. and generating instructions at the beginning of the function to move
  7483. from the argument passing registers to these local variables.
  7484. \begin{lstlisting}
  7485. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7486. |$\Rightarrow$|
  7487. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7488. \end{lstlisting}
  7489. The $G'$ control-flow graph is the same as $G$ except that the
  7490. \code{start} block is modified to add the instructions for moving from
  7491. the argument registers to the parameter variables. So the \code{start}
  7492. block of $G$ shown on the left is changed to the code on the right.
  7493. \begin{center}
  7494. \begin{minipage}{0.3\textwidth}
  7495. \begin{lstlisting}
  7496. start:
  7497. |$\itm{instr}_1$|
  7498. |$\vdots$|
  7499. |$\itm{instr}_n$|
  7500. \end{lstlisting}
  7501. \end{minipage}
  7502. $\Rightarrow$
  7503. \begin{minipage}{0.3\textwidth}
  7504. \begin{lstlisting}
  7505. start:
  7506. movq %rdi, |$x_1$|
  7507. movq %rsi, |$x_2$|
  7508. |$\vdots$|
  7509. |$\itm{instr}_1$|
  7510. |$\vdots$|
  7511. |$\itm{instr}_n$|
  7512. \end{lstlisting}
  7513. \end{minipage}
  7514. \end{center}
  7515. By changing the parameters to local variables, we are giving the
  7516. register allocator control over which registers or stack locations to
  7517. use for them. If you implemented the move-biasing challenge
  7518. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7519. assign the parameter variables to the corresponding argument register,
  7520. in which case the \code{patch-instructions} pass will remove the
  7521. \code{movq} instruction. This happens in the example translation in
  7522. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7523. the \code{add} function.
  7524. %
  7525. Also, note that the register allocator will perform liveness analysis
  7526. on this sequence of move instructions and build the interference
  7527. graph. So, for example, $x_1$ will be marked as interfering with
  7528. \code{rsi} and that will prevent the assignment of $x_1$ to
  7529. \code{rsi}, which is good, because that would overwrite the argument
  7530. that needs to move into $x_2$.
  7531. Next, consider the compilation of function calls. In the mirror image
  7532. of handling the parameters of function definitions, the arguments need
  7533. to be moved to the argument passing registers. The function call
  7534. itself is performed with an indirect function call. The return value
  7535. from the function is stored in \code{rax}, so it needs to be moved
  7536. into the \itm{lhs}.
  7537. \begin{lstlisting}
  7538. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7539. |$\Rightarrow$|
  7540. movq |$\itm{arg}_1$|, %rdi
  7541. movq |$\itm{arg}_2$|, %rsi
  7542. |$\vdots$|
  7543. callq *|\itm{fun}|
  7544. movq %rax, |\itm{lhs}|
  7545. \end{lstlisting}
  7546. The \code{IndirectCallq} AST node includes an integer for the arity of
  7547. the function, i.e., the number of parameters. That information is
  7548. useful in the \code{uncover-live} pass for determining which
  7549. argument-passing registers are potentially read during the call.
  7550. For tail calls, the parameter passing is the same as non-tail calls:
  7551. generate instructions to move the arguments into to the argument
  7552. passing registers. After that we need to pop the frame from the
  7553. procedure call stack. However, we do not yet know how big the frame
  7554. is; that gets determined during register allocation. So instead of
  7555. generating those instructions here, we invent a new instruction that
  7556. means ``pop the frame and then do an indirect jump'', which we name
  7557. \code{TailJmp}. The abstract syntax for this instruction includes an
  7558. argument that specifies where to jump and an integer that represents
  7559. the arity of the function being called.
  7560. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7561. using the label \code{start} for the initial block of a program, and
  7562. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7563. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7564. can be compiled to an assignment to \code{rax} followed by a jump to
  7565. \code{conclusion}. With the addition of function definitions, we will
  7566. have a starting block and conclusion for each function, but their
  7567. labels need to be unique. We recommend prepending the function's name
  7568. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7569. labels. (Alternatively, one could \code{gensym} labels for the start
  7570. and conclusion and store them in the $\itm{info}$ field of the
  7571. function definition.)
  7572. \section{Register Allocation}
  7573. \label{sec:register-allocation-r4}
  7574. \subsection{Liveness Analysis}
  7575. \label{sec:liveness-analysis-r4}
  7576. \index{subject}{liveness analysis}
  7577. %% The rest of the passes need only minor modifications to handle the new
  7578. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7579. %% \code{leaq}.
  7580. The \code{IndirectCallq} instruction should be treated like
  7581. \code{Callq} regarding its written locations $W$, in that they should
  7582. include all the caller-saved registers. Recall that the reason for
  7583. that is to force call-live variables to be assigned to callee-saved
  7584. registers or to be spilled to the stack.
  7585. Regarding the set of read locations $R$ the arity field of
  7586. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7587. argument-passing registers should be considered as read by those
  7588. instructions.
  7589. \subsection{Build Interference Graph}
  7590. \label{sec:build-interference-r4}
  7591. With the addition of function definitions, we compute an interference
  7592. graph for each function (not just one for the whole program).
  7593. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7594. spill vector-typed variables that are live during a call to the
  7595. \code{collect}. With the addition of functions to our language, we
  7596. need to revisit this issue. Many functions perform allocation and
  7597. therefore have calls to the collector inside of them. Thus, we should
  7598. not only spill a vector-typed variable when it is live during a call
  7599. to \code{collect}, but we should spill the variable if it is live
  7600. during any function call. Thus, in the \code{build-interference} pass,
  7601. we recommend adding interference edges between call-live vector-typed
  7602. variables and the callee-saved registers (in addition to the usual
  7603. addition of edges between call-live variables and the caller-saved
  7604. registers).
  7605. \subsection{Allocate Registers}
  7606. The primary change to the \code{allocate-registers} pass is adding an
  7607. auxiliary function for handling definitions (the \Def{} non-terminal
  7608. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7609. logic is the same as described in
  7610. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7611. allocation is performed many times, once for each function definition,
  7612. instead of just once for the whole program.
  7613. \section{Patch Instructions}
  7614. In \code{patch-instructions}, you should deal with the x86
  7615. idiosyncrasy that the destination argument of \code{leaq} must be a
  7616. register. Additionally, you should ensure that the argument of
  7617. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7618. code generation more convenient, because we trample many registers
  7619. before the tail call (as explained in the next section).
  7620. \section{Print x86}
  7621. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7622. \code{IndirectCallq} are straightforward: output their concrete
  7623. syntax.
  7624. \begin{lstlisting}
  7625. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7626. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7627. \end{lstlisting}
  7628. The \code{TailJmp} node requires a bit work. A straightforward
  7629. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7630. before the jump we need to pop the current frame. This sequence of
  7631. instructions is the same as the code for the conclusion of a function,
  7632. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7633. Regarding function definitions, you will need to generate a prelude
  7634. and conclusion for each one. This code is similar to the prelude and
  7635. conclusion that you generated for the \code{main} function in
  7636. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7637. should carry out the following steps.
  7638. \begin{enumerate}
  7639. \item Start with \code{.global} and \code{.align} directives followed
  7640. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7641. example.)
  7642. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7643. pointer.
  7644. \item Push to the stack all of the callee-saved registers that were
  7645. used for register allocation.
  7646. \item Move the stack pointer \code{rsp} down by the size of the stack
  7647. frame for this function, which depends on the number of regular
  7648. spills. (Aligned to 16 bytes.)
  7649. \item Move the root stack pointer \code{r15} up by the size of the
  7650. root-stack frame for this function, which depends on the number of
  7651. spilled vectors. \label{root-stack-init}
  7652. \item Initialize to zero all of the entries in the root-stack frame.
  7653. \item Jump to the start block.
  7654. \end{enumerate}
  7655. The prelude of the \code{main} function has one additional task: call
  7656. the \code{initialize} function to set up the garbage collector and
  7657. move the value of the global \code{rootstack\_begin} in
  7658. \code{r15}. This should happen before step \ref{root-stack-init}
  7659. above, which depends on \code{r15}.
  7660. The conclusion of every function should do the following.
  7661. \begin{enumerate}
  7662. \item Move the stack pointer back up by the size of the stack frame
  7663. for this function.
  7664. \item Restore the callee-saved registers by popping them from the
  7665. stack.
  7666. \item Move the root stack pointer back down by the size of the
  7667. root-stack frame for this function.
  7668. \item Restore \code{rbp} by popping it from the stack.
  7669. \item Return to the caller with the \code{retq} instruction.
  7670. \end{enumerate}
  7671. \begin{exercise}\normalfont
  7672. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7673. Create 5 new programs that use functions, including examples that pass
  7674. functions and return functions from other functions, recursive
  7675. functions, functions that create vectors, and functions that make tail
  7676. calls. Test your compiler on these new programs and all of your
  7677. previously created test programs.
  7678. \end{exercise}
  7679. \begin{figure}[tbp]
  7680. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7681. \node (Rfun) at (0,2) {\large \LangFun{}};
  7682. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7683. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7684. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7685. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7686. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7687. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7688. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7689. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7690. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7691. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7692. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7693. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7694. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7695. \path[->,bend left=15] (Rfun) edge [above] node
  7696. {\ttfamily\footnotesize shrink} (Rfun-1);
  7697. \path[->,bend left=15] (Rfun-1) edge [above] node
  7698. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7699. \path[->,bend left=15] (Rfun-2) edge [right] node
  7700. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7701. \path[->,bend left=15] (F1-1) edge [below] node
  7702. {\ttfamily\footnotesize limit-functions} (F1-2);
  7703. \path[->,bend right=15] (F1-2) edge [above] node
  7704. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7705. \path[->,bend right=15] (F1-3) edge [above] node
  7706. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7707. \path[->,bend left=15] (F1-4) edge [right] node
  7708. {\ttfamily\footnotesize explicate-control} (C3-2);
  7709. \path[->,bend right=15] (C3-2) edge [left] node
  7710. {\ttfamily\footnotesize select-instr.} (x86-2);
  7711. \path[->,bend left=15] (x86-2) edge [left] node
  7712. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7713. \path[->,bend right=15] (x86-2-1) edge [below] node
  7714. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7715. \path[->,bend right=15] (x86-2-2) edge [left] node
  7716. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7717. \path[->,bend left=15] (x86-3) edge [above] node
  7718. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7719. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7720. \end{tikzpicture}
  7721. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7722. \label{fig:Rfun-passes}
  7723. \end{figure}
  7724. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7725. compiling \LangFun{} to x86.
  7726. \section{An Example Translation}
  7727. \label{sec:functions-example}
  7728. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7729. function in \LangFun{} to x86. The figure also includes the results of the
  7730. \code{explicate-control} and \code{select-instructions} passes.
  7731. \begin{figure}[htbp]
  7732. \begin{tabular}{ll}
  7733. \begin{minipage}{0.5\textwidth}
  7734. % s3_2.rkt
  7735. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7736. (define (add [x : Integer] [y : Integer])
  7737. : Integer
  7738. (+ x y))
  7739. (add 40 2)
  7740. \end{lstlisting}
  7741. $\Downarrow$
  7742. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7743. (define (add86 [x87 : Integer]
  7744. [y88 : Integer]) : Integer
  7745. add86start:
  7746. return (+ x87 y88);
  7747. )
  7748. (define (main) : Integer ()
  7749. mainstart:
  7750. tmp89 = (fun-ref add86);
  7751. (tail-call tmp89 40 2)
  7752. )
  7753. \end{lstlisting}
  7754. \end{minipage}
  7755. &
  7756. $\Rightarrow$
  7757. \begin{minipage}{0.5\textwidth}
  7758. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7759. (define (add86) : Integer
  7760. add86start:
  7761. movq %rdi, x87
  7762. movq %rsi, y88
  7763. movq x87, %rax
  7764. addq y88, %rax
  7765. jmp add11389conclusion
  7766. )
  7767. (define (main) : Integer
  7768. mainstart:
  7769. leaq (fun-ref add86), tmp89
  7770. movq $40, %rdi
  7771. movq $2, %rsi
  7772. tail-jmp tmp89
  7773. )
  7774. \end{lstlisting}
  7775. $\Downarrow$
  7776. \end{minipage}
  7777. \end{tabular}
  7778. \begin{tabular}{ll}
  7779. \begin{minipage}{0.3\textwidth}
  7780. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7781. .globl add86
  7782. .align 16
  7783. add86:
  7784. pushq %rbp
  7785. movq %rsp, %rbp
  7786. jmp add86start
  7787. add86start:
  7788. movq %rdi, %rax
  7789. addq %rsi, %rax
  7790. jmp add86conclusion
  7791. add86conclusion:
  7792. popq %rbp
  7793. retq
  7794. \end{lstlisting}
  7795. \end{minipage}
  7796. &
  7797. \begin{minipage}{0.5\textwidth}
  7798. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7799. .globl main
  7800. .align 16
  7801. main:
  7802. pushq %rbp
  7803. movq %rsp, %rbp
  7804. movq $16384, %rdi
  7805. movq $16384, %rsi
  7806. callq initialize
  7807. movq rootstack_begin(%rip), %r15
  7808. jmp mainstart
  7809. mainstart:
  7810. leaq add86(%rip), %rcx
  7811. movq $40, %rdi
  7812. movq $2, %rsi
  7813. movq %rcx, %rax
  7814. popq %rbp
  7815. jmp *%rax
  7816. mainconclusion:
  7817. popq %rbp
  7818. retq
  7819. \end{lstlisting}
  7820. \end{minipage}
  7821. \end{tabular}
  7822. \caption{Example compilation of a simple function to x86.}
  7823. \label{fig:add-fun}
  7824. \end{figure}
  7825. % Challenge idea: inlining! (simple version)
  7826. % Further Reading
  7827. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7828. \chapter{Lexically Scoped Functions}
  7829. \label{ch:Rlam}
  7830. \index{subject}{lambda}
  7831. \index{subject}{lexical scoping}
  7832. This chapter studies lexically scoped functions as they appear in
  7833. functional languages such as Racket. By lexical scoping we mean that a
  7834. function's body may refer to variables whose binding site is outside
  7835. of the function, in an enclosing scope.
  7836. %
  7837. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7838. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7839. \key{lambda} form. The body of the \key{lambda}, refers to three
  7840. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7841. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7842. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7843. parameter of function \code{f}. The \key{lambda} is returned from the
  7844. function \code{f}. The main expression of the program includes two
  7845. calls to \code{f} with different arguments for \code{x}, first
  7846. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7847. to variables \code{g} and \code{h}. Even though these two functions
  7848. were created by the same \code{lambda}, they are really different
  7849. functions because they use different values for \code{x}. Applying
  7850. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7851. \code{15} produces \code{22}. The result of this program is \code{42}.
  7852. \begin{figure}[btp]
  7853. % s4_6.rkt
  7854. \begin{lstlisting}
  7855. (define (f [x : Integer]) : (Integer -> Integer)
  7856. (let ([y 4])
  7857. (lambda: ([z : Integer]) : Integer
  7858. (+ x (+ y z)))))
  7859. (let ([g (f 5)])
  7860. (let ([h (f 3)])
  7861. (+ (g 11) (h 15))))
  7862. \end{lstlisting}
  7863. \caption{Example of a lexically scoped function.}
  7864. \label{fig:lexical-scoping}
  7865. \end{figure}
  7866. The approach that we take for implementing lexically scoped
  7867. functions is to compile them into top-level function definitions,
  7868. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7869. provide special treatment for variable occurrences such as \code{x}
  7870. and \code{y} in the body of the \code{lambda} of
  7871. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7872. refer to variables defined outside of it. To identify such variable
  7873. occurrences, we review the standard notion of free variable.
  7874. \begin{definition}
  7875. A variable is \emph{free in expression} $e$ if the variable occurs
  7876. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  7877. variable}
  7878. \end{definition}
  7879. For example, in the expression \code{(+ x (+ y z))} the variables
  7880. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7881. only \code{x} and \code{y} are free in the following expression
  7882. because \code{z} is bound by the \code{lambda}.
  7883. \begin{lstlisting}
  7884. (lambda: ([z : Integer]) : Integer
  7885. (+ x (+ y z)))
  7886. \end{lstlisting}
  7887. So the free variables of a \code{lambda} are the ones that will need
  7888. special treatment. We need to arrange for some way to transport, at
  7889. runtime, the values of those variables from the point where the
  7890. \code{lambda} was created to the point where the \code{lambda} is
  7891. applied. An efficient solution to the problem, due to
  7892. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7893. free variables together with the function pointer for the lambda's
  7894. code, an arrangement called a \emph{flat closure} (which we shorten to
  7895. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  7896. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7897. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7898. pointers. The function pointer resides at index $0$ and the
  7899. values for the free variables will fill in the rest of the vector.
  7900. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7901. how closures work. It's a three-step dance. The program first calls
  7902. function \code{f}, which creates a closure for the \code{lambda}. The
  7903. closure is a vector whose first element is a pointer to the top-level
  7904. function that we will generate for the \code{lambda}, the second
  7905. element is the value of \code{x}, which is \code{5}, and the third
  7906. element is \code{4}, the value of \code{y}. The closure does not
  7907. contain an element for \code{z} because \code{z} is not a free
  7908. variable of the \code{lambda}. Creating the closure is step 1 of the
  7909. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7910. shown in Figure~\ref{fig:closures}.
  7911. %
  7912. The second call to \code{f} creates another closure, this time with
  7913. \code{3} in the second slot (for \code{x}). This closure is also
  7914. returned from \code{f} but bound to \code{h}, which is also shown in
  7915. Figure~\ref{fig:closures}.
  7916. \begin{figure}[tbp]
  7917. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7918. \caption{Example closure representation for the \key{lambda}'s
  7919. in Figure~\ref{fig:lexical-scoping}.}
  7920. \label{fig:closures}
  7921. \end{figure}
  7922. Continuing with the example, consider the application of \code{g} to
  7923. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7924. obtain the function pointer in the first element of the closure and
  7925. call it, passing in the closure itself and then the regular arguments,
  7926. in this case \code{11}. This technique for applying a closure is step
  7927. 2 of the dance.
  7928. %
  7929. But doesn't this \code{lambda} only take 1 argument, for parameter
  7930. \code{z}? The third and final step of the dance is generating a
  7931. top-level function for a \code{lambda}. We add an additional
  7932. parameter for the closure and we insert a \code{let} at the beginning
  7933. of the function for each free variable, to bind those variables to the
  7934. appropriate elements from the closure parameter.
  7935. %
  7936. This three-step dance is known as \emph{closure conversion}. We
  7937. discuss the details of closure conversion in
  7938. Section~\ref{sec:closure-conversion} and the code generated from the
  7939. example in Section~\ref{sec:example-lambda}. But first we define the
  7940. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7941. \section{The \LangLam{} Language}
  7942. \label{sec:r5}
  7943. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7944. functions and lexical scoping, is defined in
  7945. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7946. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7947. syntax for function application.
  7948. \begin{figure}[tp]
  7949. \centering
  7950. \fbox{
  7951. \begin{minipage}{0.96\textwidth}
  7952. \small
  7953. \[
  7954. \begin{array}{lcl}
  7955. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7956. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7957. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7958. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7959. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7960. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7961. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7962. \mid (\key{and}\;\Exp\;\Exp)
  7963. \mid (\key{or}\;\Exp\;\Exp)
  7964. \mid (\key{not}\;\Exp) } \\
  7965. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7966. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7967. (\key{vector-ref}\;\Exp\;\Int)} \\
  7968. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7969. \mid (\Exp \; \Exp\ldots) } \\
  7970. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7971. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7972. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7973. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  7974. \end{array}
  7975. \]
  7976. \end{minipage}
  7977. }
  7978. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  7979. with \key{lambda}.}
  7980. \label{fig:Rlam-concrete-syntax}
  7981. \end{figure}
  7982. \begin{figure}[tp]
  7983. \centering
  7984. \fbox{
  7985. \begin{minipage}{0.96\textwidth}
  7986. \small
  7987. \[
  7988. \begin{array}{lcl}
  7989. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7990. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7991. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7992. &\mid& \gray{ \BOOL{\itm{bool}}
  7993. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7994. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7995. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7996. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7997. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7998. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7999. \end{array}
  8000. \]
  8001. \end{minipage}
  8002. }
  8003. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8004. \label{fig:Rlam-syntax}
  8005. \end{figure}
  8006. \index{subject}{interpreter}
  8007. \label{sec:interp-Rlambda}
  8008. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8009. \LangLam{}. The case for \key{lambda} saves the current environment
  8010. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8011. the environment from the \key{lambda}, the \code{lam-env}, when
  8012. interpreting the body of the \key{lambda}. The \code{lam-env}
  8013. environment is extended with the mapping of parameters to argument
  8014. values.
  8015. \begin{figure}[tbp]
  8016. \begin{lstlisting}
  8017. (define interp-Rlambda-class
  8018. (class interp-Rfun-class
  8019. (super-new)
  8020. (define/override (interp-op op)
  8021. (match op
  8022. ['procedure-arity
  8023. (lambda (v)
  8024. (match v
  8025. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8026. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8027. [else (super interp-op op)]))
  8028. (define/override ((interp-exp env) e)
  8029. (define recur (interp-exp env))
  8030. (match e
  8031. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8032. `(function ,xs ,body ,env)]
  8033. [else ((super interp-exp env) e)]))
  8034. ))
  8035. (define (interp-Rlambda p)
  8036. (send (new interp-Rlambda-class) interp-program p))
  8037. \end{lstlisting}
  8038. \caption{Interpreter for \LangLam{}.}
  8039. \label{fig:interp-Rlambda}
  8040. \end{figure}
  8041. \label{sec:type-check-r5}
  8042. \index{subject}{type checking}
  8043. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8044. \key{lambda} form. The body of the \key{lambda} is checked in an
  8045. environment that includes the current environment (because it is
  8046. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8047. require the body's type to match the declared return type.
  8048. \begin{figure}[tbp]
  8049. \begin{lstlisting}
  8050. (define (type-check-Rlambda env)
  8051. (lambda (e)
  8052. (match e
  8053. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8054. (define-values (new-body bodyT)
  8055. ((type-check-exp (append (map cons xs Ts) env)) body))
  8056. (define ty `(,@Ts -> ,rT))
  8057. (cond
  8058. [(equal? rT bodyT)
  8059. (values (HasType (Lambda params rT new-body) ty) ty)]
  8060. [else
  8061. (error "mismatch in return type" bodyT rT)])]
  8062. ...
  8063. )))
  8064. \end{lstlisting}
  8065. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8066. \label{fig:type-check-Rlambda}
  8067. \end{figure}
  8068. \section{Reveal Functions and the $F_2$ language}
  8069. \label{sec:reveal-functions-r5}
  8070. To support the \code{procedure-arity} operator we need to communicate
  8071. the arity of a function to the point of closure creation. We can
  8072. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8073. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8074. output of this pass is the language $F_2$, whose syntax is defined in
  8075. Figure~\ref{fig:f2-syntax}.
  8076. \begin{figure}[tp]
  8077. \centering
  8078. \fbox{
  8079. \begin{minipage}{0.96\textwidth}
  8080. \[
  8081. \begin{array}{lcl}
  8082. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8083. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8084. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8085. \end{array}
  8086. \]
  8087. \end{minipage}
  8088. }
  8089. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8090. (Figure~\ref{fig:Rlam-syntax}).}
  8091. \label{fig:f2-syntax}
  8092. \end{figure}
  8093. \section{Closure Conversion}
  8094. \label{sec:closure-conversion}
  8095. \index{subject}{closure conversion}
  8096. The compiling of lexically-scoped functions into top-level function
  8097. definitions is accomplished in the pass \code{convert-to-closures}
  8098. that comes after \code{reveal-functions} and before
  8099. \code{limit-functions}.
  8100. As usual, we implement the pass as a recursive function over the
  8101. AST. All of the action is in the cases for \key{Lambda} and
  8102. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8103. that creates a closure, that is, a vector whose first element is a
  8104. function pointer and the rest of the elements are the free variables
  8105. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8106. using \code{vector} so that we can distinguish closures from vectors
  8107. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8108. the generated code below, the \itm{name} is a unique symbol generated
  8109. to identify the function and the \itm{arity} is the number of
  8110. parameters (the length of \itm{ps}).
  8111. \begin{lstlisting}
  8112. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8113. |$\Rightarrow$|
  8114. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8115. \end{lstlisting}
  8116. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8117. create a top-level function definition for each \key{Lambda}, as
  8118. shown below.\\
  8119. \begin{minipage}{0.8\textwidth}
  8120. \begin{lstlisting}
  8121. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8122. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8123. ...
  8124. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8125. |\itm{body'}|)...))
  8126. \end{lstlisting}
  8127. \end{minipage}\\
  8128. The \code{clos} parameter refers to the closure. Translate the type
  8129. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8130. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8131. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8132. underscore \code{\_} is a dummy type that we use because it is rather
  8133. difficult to give a type to the function in the closure's
  8134. type.\footnote{To give an accurate type to a closure, we would need to
  8135. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8136. The dummy type is considered to be equal to any other type during type
  8137. checking. The sequence of \key{Let} forms bind the free variables to
  8138. their values obtained from the closure.
  8139. Closure conversion turns functions into vectors, so the type
  8140. annotations in the program must also be translated. We recommend
  8141. defining a auxiliary recursive function for this purpose. Function
  8142. types should be translated as follows.
  8143. \begin{lstlisting}
  8144. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8145. |$\Rightarrow$|
  8146. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8147. \end{lstlisting}
  8148. The above type says that the first thing in the vector is a function
  8149. pointer. The first parameter of the function pointer is a vector (a
  8150. closure) and the rest of the parameters are the ones from the original
  8151. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8152. the closure omits the types of the free variables because 1) those
  8153. types are not available in this context and 2) we do not need them in
  8154. the code that is generated for function application.
  8155. We transform function application into code that retrieves the
  8156. function pointer from the closure and then calls the function, passing
  8157. in the closure as the first argument. We bind $e'$ to a temporary
  8158. variable to avoid code duplication.
  8159. \begin{lstlisting}
  8160. (Apply |$e$| |\itm{es}|)
  8161. |$\Rightarrow$|
  8162. (Let |\itm{tmp}| |$e'$|
  8163. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8164. \end{lstlisting}
  8165. There is also the question of what to do with references top-level
  8166. function definitions. To maintain a uniform translation of function
  8167. application, we turn function references into closures.
  8168. \begin{tabular}{lll}
  8169. \begin{minipage}{0.3\textwidth}
  8170. \begin{lstlisting}
  8171. (FunRefArity |$f$| |$n$|)
  8172. \end{lstlisting}
  8173. \end{minipage}
  8174. &
  8175. $\Rightarrow$
  8176. &
  8177. \begin{minipage}{0.5\textwidth}
  8178. \begin{lstlisting}
  8179. (Closure |$n$| (FunRef |$f$|) '())
  8180. \end{lstlisting}
  8181. \end{minipage}
  8182. \end{tabular} \\
  8183. %
  8184. The top-level function definitions need to be updated as well to take
  8185. an extra closure parameter.
  8186. \section{An Example Translation}
  8187. \label{sec:example-lambda}
  8188. Figure~\ref{fig:lexical-functions-example} shows the result of
  8189. \code{reveal-functions} and \code{convert-to-closures} for the example
  8190. program demonstrating lexical scoping that we discussed at the
  8191. beginning of this chapter.
  8192. \begin{figure}[tbp]
  8193. \begin{minipage}{0.8\textwidth}
  8194. % tests/lambda_test_6.rkt
  8195. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8196. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8197. (let ([y8 4])
  8198. (lambda: ([z9 : Integer]) : Integer
  8199. (+ x7 (+ y8 z9)))))
  8200. (define (main) : Integer
  8201. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8202. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8203. (+ (g0 11) (h1 15)))))
  8204. \end{lstlisting}
  8205. $\Rightarrow$
  8206. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8207. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8208. (let ([y8 4])
  8209. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8210. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8211. (let ([x7 (vector-ref fvs3 1)])
  8212. (let ([y8 (vector-ref fvs3 2)])
  8213. (+ x7 (+ y8 z9)))))
  8214. (define (main) : Integer
  8215. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8216. ((vector-ref clos5 0) clos5 5))])
  8217. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8218. ((vector-ref clos6 0) clos6 3))])
  8219. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8220. \end{lstlisting}
  8221. \end{minipage}
  8222. \caption{Example of closure conversion.}
  8223. \label{fig:lexical-functions-example}
  8224. \end{figure}
  8225. \begin{exercise}\normalfont
  8226. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8227. Create 5 new programs that use \key{lambda} functions and make use of
  8228. lexical scoping. Test your compiler on these new programs and all of
  8229. your previously created test programs.
  8230. \end{exercise}
  8231. \section{Expose Allocation}
  8232. \label{sec:expose-allocation-r5}
  8233. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8234. that allocates and initializes a vector, similar to the translation of
  8235. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8236. The only difference is replacing the use of
  8237. \ALLOC{\itm{len}}{\itm{type}} with
  8238. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8239. \section{Explicate Control and \LangCLam{}}
  8240. \label{sec:explicate-r5}
  8241. The output language of \code{explicate-control} is \LangCLam{} whose
  8242. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8243. difference with respect to \LangCFun{} is the addition of the
  8244. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8245. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8246. similar to the handling of other expressions such as primitive
  8247. operators.
  8248. \begin{figure}[tp]
  8249. \fbox{
  8250. \begin{minipage}{0.96\textwidth}
  8251. \small
  8252. \[
  8253. \begin{array}{lcl}
  8254. \Exp &::= & \ldots
  8255. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8256. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8257. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8258. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8259. \mid \GOTO{\itm{label}} } \\
  8260. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8261. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8262. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8263. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8264. \end{array}
  8265. \]
  8266. \end{minipage}
  8267. }
  8268. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8269. \label{fig:c4-syntax}
  8270. \end{figure}
  8271. \section{Select Instructions}
  8272. \label{sec:select-instructions-Rlambda}
  8273. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8274. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8275. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8276. that you should place the \itm{arity} in the tag that is stored at
  8277. position $0$ of the vector. Recall that in
  8278. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8279. was not used. We store the arity in the $5$ bits starting at position
  8280. $58$.
  8281. Compile the \code{procedure-arity} operator into a sequence of
  8282. instructions that access the tag from position $0$ of the vector and
  8283. extract the $5$-bits starting at position $58$ from the tag.
  8284. \begin{figure}[p]
  8285. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8286. \node (Rfun) at (0,2) {\large \LangFun{}};
  8287. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8288. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8289. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8290. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8291. \node (F1-3) at (6,0) {\large $F_1$};
  8292. \node (F1-4) at (3,0) {\large $F_1$};
  8293. \node (F1-5) at (0,0) {\large $F_1$};
  8294. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8295. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8296. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8297. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8298. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8299. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8300. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8301. \path[->,bend left=15] (Rfun) edge [above] node
  8302. {\ttfamily\footnotesize shrink} (Rfun-2);
  8303. \path[->,bend left=15] (Rfun-2) edge [above] node
  8304. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8305. \path[->,bend left=15] (Rfun-3) edge [right] node
  8306. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8307. \path[->,bend left=15] (F1-1) edge [below] node
  8308. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8309. \path[->,bend right=15] (F1-2) edge [above] node
  8310. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8311. \path[->,bend right=15] (F1-3) edge [above] node
  8312. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8313. \path[->,bend right=15] (F1-4) edge [above] node
  8314. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8315. \path[->,bend right=15] (F1-5) edge [right] node
  8316. {\ttfamily\footnotesize explicate-control} (C3-2);
  8317. \path[->,bend left=15] (C3-2) edge [left] node
  8318. {\ttfamily\footnotesize select-instr.} (x86-2);
  8319. \path[->,bend right=15] (x86-2) edge [left] node
  8320. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8321. \path[->,bend right=15] (x86-2-1) edge [below] node
  8322. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8323. \path[->,bend right=15] (x86-2-2) edge [left] node
  8324. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8325. \path[->,bend left=15] (x86-3) edge [above] node
  8326. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8327. \path[->,bend left=15] (x86-4) edge [right] node
  8328. {\ttfamily\footnotesize print-x86} (x86-5);
  8329. \end{tikzpicture}
  8330. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8331. functions.}
  8332. \label{fig:Rlambda-passes}
  8333. \end{figure}
  8334. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8335. for the compilation of \LangLam{}.
  8336. \clearpage
  8337. \section{Challenge: Optimize Closures}
  8338. \label{sec:optimize-closures}
  8339. In this chapter we compiled lexically-scoped functions into a
  8340. relatively efficient representation: flat closures. However, even this
  8341. representation comes with some overhead. For example, consider the
  8342. following program with a function \code{tail-sum} that does not have
  8343. any free variables and where all the uses of \code{tail-sum} are in
  8344. applications where we know that only \code{tail-sum} is being applied
  8345. (and not any other functions).
  8346. \begin{center}
  8347. \begin{minipage}{0.95\textwidth}
  8348. \begin{lstlisting}
  8349. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8350. (if (eq? n 0)
  8351. r
  8352. (tail-sum (- n 1) (+ n r))))
  8353. (+ (tail-sum 5 0) 27)
  8354. \end{lstlisting}
  8355. \end{minipage}
  8356. \end{center}
  8357. As described in this chapter, we uniformly apply closure conversion to
  8358. all functions, obtaining the following output for this program.
  8359. \begin{center}
  8360. \begin{minipage}{0.95\textwidth}
  8361. \begin{lstlisting}
  8362. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8363. (if (eq? n2 0)
  8364. r3
  8365. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8366. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8367. (define (main) : Integer
  8368. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8369. ((vector-ref clos6 0) clos6 5 0)) 27))
  8370. \end{lstlisting}
  8371. \end{minipage}
  8372. \end{center}
  8373. In the previous Chapter, there would be no allocation in the program
  8374. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8375. the above program allocates memory for each \code{closure} and the
  8376. calls to \code{tail-sum} are indirect. These two differences incur
  8377. considerable overhead in a program such as this one, where the
  8378. allocations and indirect calls occur inside a tight loop.
  8379. One might think that this problem is trivial to solve: can't we just
  8380. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8381. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8382. e'_n$)} instead of treating it like a call to a closure? We would
  8383. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8384. %
  8385. However, this problem is not so trivial because a global function may
  8386. ``escape'' and become involved in applications that also involve
  8387. closures. Consider the following example in which the application
  8388. \code{(f 41)} needs to be compiled into a closure application, because
  8389. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8390. function might also get bound to \code{f}.
  8391. \begin{lstlisting}
  8392. (define (add1 [x : Integer]) : Integer
  8393. (+ x 1))
  8394. (let ([y (read)])
  8395. (let ([f (if (eq? (read) 0)
  8396. add1
  8397. (lambda: ([x : Integer]) : Integer (- x y)))])
  8398. (f 41)))
  8399. \end{lstlisting}
  8400. If a global function name is used in any way other than as the
  8401. operator in a direct call, then we say that the function
  8402. \emph{escapes}. If a global function does not escape, then we do not
  8403. need to perform closure conversion on the function.
  8404. \begin{exercise}\normalfont
  8405. Implement an auxiliary function for detecting which global
  8406. functions escape. Using that function, implement an improved version
  8407. of closure conversion that does not apply closure conversion to
  8408. global functions that do not escape but instead compiles them as
  8409. regular functions. Create several new test cases that check whether
  8410. you properly detect whether global functions escape or not.
  8411. \end{exercise}
  8412. So far we have reduced the overhead of calling global functions, but
  8413. it would also be nice to reduce the overhead of calling a
  8414. \code{lambda} when we can determine at compile time which
  8415. \code{lambda} will be called. We refer to such calls as \emph{known
  8416. calls}. Consider the following example in which a \code{lambda} is
  8417. bound to \code{f} and then applied.
  8418. \begin{lstlisting}
  8419. (let ([y (read)])
  8420. (let ([f (lambda: ([x : Integer]) : Integer
  8421. (+ x y))])
  8422. (f 21)))
  8423. \end{lstlisting}
  8424. Closure conversion compiles \code{(f 21)} into an indirect call:
  8425. \begin{lstlisting}
  8426. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8427. (let ([y2 (vector-ref fvs6 1)])
  8428. (+ x3 y2)))
  8429. (define (main) : Integer
  8430. (let ([y2 (read)])
  8431. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8432. ((vector-ref f4 0) f4 21))))
  8433. \end{lstlisting}
  8434. but we can instead compile the application \code{(f 21)} into a direct call
  8435. to \code{lambda5}:
  8436. \begin{lstlisting}
  8437. (define (main) : Integer
  8438. (let ([y2 (read)])
  8439. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8440. ((fun-ref lambda5) f4 21))))
  8441. \end{lstlisting}
  8442. The problem of determining which lambda will be called from a
  8443. particular application is quite challenging in general and the topic
  8444. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8445. following exercise we recommend that you compile an application to a
  8446. direct call when the operator is a variable and the variable is
  8447. \code{let}-bound to a closure. This can be accomplished by maintaining
  8448. an environment mapping \code{let}-bound variables to function names.
  8449. Extend the environment whenever you encounter a closure on the
  8450. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8451. to the name of the global function for the closure. This pass should
  8452. come after closure conversion.
  8453. \begin{exercise}\normalfont
  8454. Implement a compiler pass, named \code{optimize-known-calls}, that
  8455. compiles known calls into direct calls. Verify that your compiler is
  8456. successful in this regard on several example programs.
  8457. \end{exercise}
  8458. These exercises only scratches the surface of optimizing of
  8459. closures. A good next step for the interested reader is to look at the
  8460. work of \citet{Keep:2012ab}.
  8461. \section{Further Reading}
  8462. The notion of lexically scoped anonymous functions predates modern
  8463. computers by about a decade. They were invented by
  8464. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8465. foundation for logic. Anonymous functions were included in the
  8466. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8467. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8468. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8469. compile Scheme programs. However, environments were represented as
  8470. linked lists, so variable lookup was linear in the size of the
  8471. environment. In this chapter we represent environments using flat
  8472. closures, which were invented by
  8473. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8474. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8475. closures, variable lookup is constant time but the time to create a
  8476. closure is proportional to the number of its free variables. Flat
  8477. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8478. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8479. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8480. \chapter{Dynamic Typing}
  8481. \label{ch:Rdyn}
  8482. \index{subject}{dynamic typing}
  8483. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8484. typed language that is a subset of Racket. This is in contrast to the
  8485. previous chapters, which have studied the compilation of Typed
  8486. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8487. expression may produce a value of a different type each time it is
  8488. executed. Consider the following example with a conditional \code{if}
  8489. expression that may return a Boolean or an integer depending on the
  8490. input to the program.
  8491. % part of dynamic_test_25.rkt
  8492. \begin{lstlisting}
  8493. (not (if (eq? (read) 1) #f 0))
  8494. \end{lstlisting}
  8495. Languages that allow expressions to produce different kinds of values
  8496. are called \emph{polymorphic}, a word composed of the Greek roots
  8497. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8498. are several kinds of polymorphism in programming languages, such as
  8499. subtype polymorphism and parametric
  8500. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8501. study in this chapter does not have a special name but it is the kind
  8502. that arises in dynamically typed languages.
  8503. Another characteristic of dynamically typed languages is that
  8504. primitive operations, such as \code{not}, are often defined to operate
  8505. on many different types of values. In fact, in Racket, the \code{not}
  8506. operator produces a result for any kind of value: given \code{\#f} it
  8507. returns \code{\#t} and given anything else it returns \code{\#f}.
  8508. Furthermore, even when primitive operations restrict their inputs to
  8509. values of a certain type, this restriction is enforced at runtime
  8510. instead of during compilation. For example, the following vector
  8511. reference results in a run-time contract violation because the index
  8512. must be in integer, not a Boolean such as \code{\#t}.
  8513. \begin{lstlisting}
  8514. (vector-ref (vector 42) #t)
  8515. \end{lstlisting}
  8516. \begin{figure}[tp]
  8517. \centering
  8518. \fbox{
  8519. \begin{minipage}{0.97\textwidth}
  8520. \[
  8521. \begin{array}{rcl}
  8522. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8523. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8524. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8525. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8526. &\mid& \key{\#t} \mid \key{\#f}
  8527. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8528. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8529. \mid \CUNIOP{\key{not}}{\Exp} \\
  8530. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8531. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8532. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8533. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8534. &\mid& \LP\Exp \; \Exp\ldots\RP
  8535. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8536. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8537. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8538. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8539. \LangDynM{} &::=& \Def\ldots\; \Exp
  8540. \end{array}
  8541. \]
  8542. \end{minipage}
  8543. }
  8544. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8545. \label{fig:r7-concrete-syntax}
  8546. \end{figure}
  8547. \begin{figure}[tp]
  8548. \centering
  8549. \fbox{
  8550. \begin{minipage}{0.96\textwidth}
  8551. \small
  8552. \[
  8553. \begin{array}{lcl}
  8554. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8555. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8556. &\mid& \BOOL{\itm{bool}}
  8557. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8558. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8559. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8560. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8561. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8562. \end{array}
  8563. \]
  8564. \end{minipage}
  8565. }
  8566. \caption{The abstract syntax of \LangDyn{}.}
  8567. \label{fig:r7-syntax}
  8568. \end{figure}
  8569. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8570. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8571. \ref{fig:r7-syntax}.
  8572. %
  8573. There is no type checker for \LangDyn{} because it is not a statically
  8574. typed language (it's dynamically typed!).
  8575. The definitional interpreter for \LangDyn{} is presented in
  8576. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8577. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8578. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8579. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8580. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  8581. value} that combines an underlying value with a tag that identifies
  8582. what kind of value it is. We define the following struct
  8583. to represented tagged values.
  8584. \begin{lstlisting}
  8585. (struct Tagged (value tag) #:transparent)
  8586. \end{lstlisting}
  8587. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8588. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8589. but don't always capture all the information that a type does. For
  8590. example, a vector of type \code{(Vector Any Any)} is tagged with
  8591. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8592. is tagged with \code{Procedure}.
  8593. Next consider the match case for \code{vector-ref}. The
  8594. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8595. is used to ensure that the first argument is a vector and the second
  8596. is an integer. If they are not, a \code{trapped-error} is raised.
  8597. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8598. interpreter raises a \code{trapped-error} error, the compiled code
  8599. must also signal an error by exiting with return code \code{255}. A
  8600. \code{trapped-error} is also raised if the index is not less than
  8601. length of the vector.
  8602. \begin{figure}[tbp]
  8603. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8604. (define ((interp-Rdyn-exp env) ast)
  8605. (define recur (interp-Rdyn-exp env))
  8606. (match ast
  8607. [(Var x) (lookup x env)]
  8608. [(Int n) (Tagged n 'Integer)]
  8609. [(Bool b) (Tagged b 'Boolean)]
  8610. [(Lambda xs rt body)
  8611. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8612. [(Prim 'vector es)
  8613. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8614. [(Prim 'vector-ref (list e1 e2))
  8615. (define vec (recur e1)) (define i (recur e2))
  8616. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8617. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8618. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8619. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8620. [(Prim 'vector-set! (list e1 e2 e3))
  8621. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8622. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8623. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8624. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8625. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8626. (Tagged (void) 'Void)]
  8627. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8628. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8629. [(Prim 'or (list e1 e2))
  8630. (define v1 (recur e1))
  8631. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8632. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8633. [(Prim op (list e1))
  8634. #:when (set-member? type-predicates op)
  8635. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8636. [(Prim op es)
  8637. (define args (map recur es))
  8638. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8639. (unless (for/or ([expected-tags (op-tags op)])
  8640. (equal? expected-tags tags))
  8641. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8642. (tag-value
  8643. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8644. [(If q t f)
  8645. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8646. [(Apply f es)
  8647. (define new-f (recur f)) (define args (map recur es))
  8648. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8649. (match f-val
  8650. [`(function ,xs ,body ,lam-env)
  8651. (unless (eq? (length xs) (length args))
  8652. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8653. (define new-env (append (map cons xs args) lam-env))
  8654. ((interp-Rdyn-exp new-env) body)]
  8655. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8656. \end{lstlisting}
  8657. \caption{Interpreter for the \LangDyn{} language.}
  8658. \label{fig:interp-Rdyn}
  8659. \end{figure}
  8660. \begin{figure}[tbp]
  8661. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8662. (define (interp-op op)
  8663. (match op
  8664. ['+ fx+]
  8665. ['- fx-]
  8666. ['read read-fixnum]
  8667. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8668. ['< (lambda (v1 v2)
  8669. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8670. ['<= (lambda (v1 v2)
  8671. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8672. ['> (lambda (v1 v2)
  8673. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8674. ['>= (lambda (v1 v2)
  8675. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8676. ['boolean? boolean?]
  8677. ['integer? fixnum?]
  8678. ['void? void?]
  8679. ['vector? vector?]
  8680. ['vector-length vector-length]
  8681. ['procedure? (match-lambda
  8682. [`(functions ,xs ,body ,env) #t] [else #f])]
  8683. [else (error 'interp-op "unknown operator" op)]))
  8684. (define (op-tags op)
  8685. (match op
  8686. ['+ '((Integer Integer))]
  8687. ['- '((Integer Integer) (Integer))]
  8688. ['read '(())]
  8689. ['not '((Boolean))]
  8690. ['< '((Integer Integer))]
  8691. ['<= '((Integer Integer))]
  8692. ['> '((Integer Integer))]
  8693. ['>= '((Integer Integer))]
  8694. ['vector-length '((Vector))]))
  8695. (define type-predicates
  8696. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8697. (define (tag-value v)
  8698. (cond [(boolean? v) (Tagged v 'Boolean)]
  8699. [(fixnum? v) (Tagged v 'Integer)]
  8700. [(procedure? v) (Tagged v 'Procedure)]
  8701. [(vector? v) (Tagged v 'Vector)]
  8702. [(void? v) (Tagged v 'Void)]
  8703. [else (error 'tag-value "unidentified value ~a" v)]))
  8704. (define (check-tag val expected ast)
  8705. (define tag (Tagged-tag val))
  8706. (unless (eq? tag expected)
  8707. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8708. \end{lstlisting}
  8709. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8710. \label{fig:interp-Rdyn-aux}
  8711. \end{figure}
  8712. \clearpage
  8713. \section{Representation of Tagged Values}
  8714. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8715. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8716. values at the bit level. Because almost every operation in \LangDyn{}
  8717. involves manipulating tagged values, the representation must be
  8718. efficient. Recall that all of our values are 64 bits. We shall steal
  8719. the 3 right-most bits to encode the tag. We use $001$ to identify
  8720. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8721. and $101$ for the void value. We define the following auxiliary
  8722. function for mapping types to tag codes.
  8723. \begin{align*}
  8724. \itm{tagof}(\key{Integer}) &= 001 \\
  8725. \itm{tagof}(\key{Boolean}) &= 100 \\
  8726. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8727. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8728. \itm{tagof}(\key{Void}) &= 101
  8729. \end{align*}
  8730. This stealing of 3 bits comes at some price: our integers are reduced
  8731. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8732. affect vectors and procedures because those values are addresses, and
  8733. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8734. they are always $000$. Thus, we do not lose information by overwriting
  8735. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8736. to recover the original address.
  8737. To make tagged values into first-class entities, we can give them a
  8738. type, called \code{Any}, and define operations such as \code{Inject}
  8739. and \code{Project} for creating and using them, yielding the \LangAny{}
  8740. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8741. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8742. in greater detail.
  8743. \section{The \LangAny{} Language}
  8744. \label{sec:Rany-lang}
  8745. \begin{figure}[tp]
  8746. \centering
  8747. \fbox{
  8748. \begin{minipage}{0.96\textwidth}
  8749. \small
  8750. \[
  8751. \begin{array}{lcl}
  8752. \Type &::= & \ldots \mid \key{Any} \\
  8753. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8754. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8755. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8756. \mid \code{procedure?} \mid \code{void?} \\
  8757. \Exp &::=& \ldots
  8758. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8759. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8760. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8761. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8762. \end{array}
  8763. \]
  8764. \end{minipage}
  8765. }
  8766. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8767. \label{fig:Rany-syntax}
  8768. \end{figure}
  8769. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8770. (The concrete syntax of \LangAny{} is in the Appendix,
  8771. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8772. converts the value produced by expression $e$ of type $T$ into a
  8773. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8774. produced by expression $e$ into a value of type $T$ or else halts the
  8775. program if the type tag is not equivalent to $T$.
  8776. %
  8777. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8778. restricted to a flat type $\FType$, which simplifies the
  8779. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8780. The \code{any-vector} operators adapt the vector operations so that
  8781. they can be applied to a value of type \code{Any}. They also
  8782. generalize the vector operations in that the index is not restricted
  8783. to be a literal integer in the grammar but is allowed to be any
  8784. expression.
  8785. The type predicates such as \key{boolean?} expect their argument to
  8786. produce a tagged value; they return \key{\#t} if the tag corresponds
  8787. to the predicate and they return \key{\#f} otherwise.
  8788. The type checker for \LangAny{} is shown in
  8789. Figures~\ref{fig:type-check-Rany-part-1} and
  8790. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8791. Figure~\ref{fig:type-check-Rany-aux}.
  8792. %
  8793. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8794. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8795. in Figure~\ref{fig:apply-project}.
  8796. \begin{figure}[btp]
  8797. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8798. (define type-check-Rany-class
  8799. (class type-check-Rlambda-class
  8800. (super-new)
  8801. (inherit check-type-equal?)
  8802. (define/override (type-check-exp env)
  8803. (lambda (e)
  8804. (define recur (type-check-exp env))
  8805. (match e
  8806. [(Inject e1 ty)
  8807. (unless (flat-ty? ty)
  8808. (error 'type-check "may only inject from flat type, not ~a" ty))
  8809. (define-values (new-e1 e-ty) (recur e1))
  8810. (check-type-equal? e-ty ty e)
  8811. (values (Inject new-e1 ty) 'Any)]
  8812. [(Project e1 ty)
  8813. (unless (flat-ty? ty)
  8814. (error 'type-check "may only project to flat type, not ~a" ty))
  8815. (define-values (new-e1 e-ty) (recur e1))
  8816. (check-type-equal? e-ty 'Any e)
  8817. (values (Project new-e1 ty) ty)]
  8818. [(Prim 'any-vector-length (list e1))
  8819. (define-values (e1^ t1) (recur e1))
  8820. (check-type-equal? t1 'Any e)
  8821. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8822. [(Prim 'any-vector-ref (list e1 e2))
  8823. (define-values (e1^ t1) (recur e1))
  8824. (define-values (e2^ t2) (recur e2))
  8825. (check-type-equal? t1 'Any e)
  8826. (check-type-equal? t2 'Integer e)
  8827. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8828. [(Prim 'any-vector-set! (list e1 e2 e3))
  8829. (define-values (e1^ t1) (recur e1))
  8830. (define-values (e2^ t2) (recur e2))
  8831. (define-values (e3^ t3) (recur e3))
  8832. (check-type-equal? t1 'Any e)
  8833. (check-type-equal? t2 'Integer e)
  8834. (check-type-equal? t3 'Any e)
  8835. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8836. \end{lstlisting}
  8837. \caption{Type checker for the \LangAny{} language, part 1.}
  8838. \label{fig:type-check-Rany-part-1}
  8839. \end{figure}
  8840. \begin{figure}[btp]
  8841. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8842. [(ValueOf e ty)
  8843. (define-values (new-e e-ty) (recur e))
  8844. (values (ValueOf new-e ty) ty)]
  8845. [(Prim pred (list e1))
  8846. #:when (set-member? (type-predicates) pred)
  8847. (define-values (new-e1 e-ty) (recur e1))
  8848. (check-type-equal? e-ty 'Any e)
  8849. (values (Prim pred (list new-e1)) 'Boolean)]
  8850. [(If cnd thn els)
  8851. (define-values (cnd^ Tc) (recur cnd))
  8852. (define-values (thn^ Tt) (recur thn))
  8853. (define-values (els^ Te) (recur els))
  8854. (check-type-equal? Tc 'Boolean cnd)
  8855. (check-type-equal? Tt Te e)
  8856. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8857. [(Exit) (values (Exit) '_)]
  8858. [(Prim 'eq? (list arg1 arg2))
  8859. (define-values (e1 t1) (recur arg1))
  8860. (define-values (e2 t2) (recur arg2))
  8861. (match* (t1 t2)
  8862. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8863. [(other wise) (check-type-equal? t1 t2 e)])
  8864. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8865. [else ((super type-check-exp env) e)])))
  8866. ))
  8867. \end{lstlisting}
  8868. \caption{Type checker for the \LangAny{} language, part 2.}
  8869. \label{fig:type-check-Rany-part-2}
  8870. \end{figure}
  8871. \begin{figure}[tbp]
  8872. \begin{lstlisting}
  8873. (define/override (operator-types)
  8874. (append
  8875. '((integer? . ((Any) . Boolean))
  8876. (vector? . ((Any) . Boolean))
  8877. (procedure? . ((Any) . Boolean))
  8878. (void? . ((Any) . Boolean))
  8879. (tag-of-any . ((Any) . Integer))
  8880. (make-any . ((_ Integer) . Any))
  8881. )
  8882. (super operator-types)))
  8883. (define/public (type-predicates)
  8884. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8885. (define/public (combine-types t1 t2)
  8886. (match (list t1 t2)
  8887. [(list '_ t2) t2]
  8888. [(list t1 '_) t1]
  8889. [(list `(Vector ,ts1 ...)
  8890. `(Vector ,ts2 ...))
  8891. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8892. (combine-types t1 t2)))]
  8893. [(list `(,ts1 ... -> ,rt1)
  8894. `(,ts2 ... -> ,rt2))
  8895. `(,@(for/list ([t1 ts1] [t2 ts2])
  8896. (combine-types t1 t2))
  8897. -> ,(combine-types rt1 rt2))]
  8898. [else t1]))
  8899. (define/public (flat-ty? ty)
  8900. (match ty
  8901. [(or `Integer `Boolean '_ `Void) #t]
  8902. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8903. [`(,ts ... -> ,rt)
  8904. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8905. [else #f]))
  8906. \end{lstlisting}
  8907. \caption{Auxiliary methods for type checking \LangAny{}.}
  8908. \label{fig:type-check-Rany-aux}
  8909. \end{figure}
  8910. \begin{figure}[btp]
  8911. \begin{lstlisting}
  8912. (define interp-Rany-class
  8913. (class interp-Rlambda-class
  8914. (super-new)
  8915. (define/override (interp-op op)
  8916. (match op
  8917. ['boolean? (match-lambda
  8918. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8919. [else #f])]
  8920. ['integer? (match-lambda
  8921. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8922. [else #f])]
  8923. ['vector? (match-lambda
  8924. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8925. [else #f])]
  8926. ['procedure? (match-lambda
  8927. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8928. [else #f])]
  8929. ['eq? (match-lambda*
  8930. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8931. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8932. [ls (apply (super interp-op op) ls)])]
  8933. ['any-vector-ref (lambda (v i)
  8934. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8935. ['any-vector-set! (lambda (v i a)
  8936. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8937. ['any-vector-length (lambda (v)
  8938. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8939. [else (super interp-op op)]))
  8940. (define/override ((interp-exp env) e)
  8941. (define recur (interp-exp env))
  8942. (match e
  8943. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8944. [(Project e ty2) (apply-project (recur e) ty2)]
  8945. [else ((super interp-exp env) e)]))
  8946. ))
  8947. (define (interp-Rany p)
  8948. (send (new interp-Rany-class) interp-program p))
  8949. \end{lstlisting}
  8950. \caption{Interpreter for \LangAny{}.}
  8951. \label{fig:interp-Rany}
  8952. \end{figure}
  8953. \begin{figure}[tbp]
  8954. \begin{lstlisting}
  8955. (define/public (apply-inject v tg) (Tagged v tg))
  8956. (define/public (apply-project v ty2)
  8957. (define tag2 (any-tag ty2))
  8958. (match v
  8959. [(Tagged v1 tag1)
  8960. (cond
  8961. [(eq? tag1 tag2)
  8962. (match ty2
  8963. [`(Vector ,ts ...)
  8964. (define l1 ((interp-op 'vector-length) v1))
  8965. (cond
  8966. [(eq? l1 (length ts)) v1]
  8967. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8968. l1 (length ts))])]
  8969. [`(,ts ... -> ,rt)
  8970. (match v1
  8971. [`(function ,xs ,body ,env)
  8972. (cond [(eq? (length xs) (length ts)) v1]
  8973. [else
  8974. (error 'apply-project "arity mismatch ~a != ~a"
  8975. (length xs) (length ts))])]
  8976. [else (error 'apply-project "expected function not ~a" v1)])]
  8977. [else v1])]
  8978. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8979. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8980. \end{lstlisting}
  8981. \caption{Auxiliary functions for injection and projection.}
  8982. \label{fig:apply-project}
  8983. \end{figure}
  8984. \clearpage
  8985. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  8986. \label{sec:compile-r7}
  8987. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  8988. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  8989. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  8990. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  8991. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  8992. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  8993. the Boolean \code{\#t}, which must be injected to produce an
  8994. expression of type \key{Any}.
  8995. %
  8996. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  8997. addition, is representative of compilation for many primitive
  8998. operations: the arguments have type \key{Any} and must be projected to
  8999. \key{Integer} before the addition can be performed.
  9000. The compilation of \key{lambda} (third row of
  9001. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9002. produce type annotations: we simply use \key{Any}.
  9003. %
  9004. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9005. has to account for some differences in behavior between \LangDyn{} and
  9006. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9007. kind of values can be used in various places. For example, the
  9008. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9009. the arguments need not be of the same type (in that case the
  9010. result is \code{\#f}).
  9011. \begin{figure}[btp]
  9012. \centering
  9013. \begin{tabular}{|lll|} \hline
  9014. \begin{minipage}{0.27\textwidth}
  9015. \begin{lstlisting}
  9016. #t
  9017. \end{lstlisting}
  9018. \end{minipage}
  9019. &
  9020. $\Rightarrow$
  9021. &
  9022. \begin{minipage}{0.65\textwidth}
  9023. \begin{lstlisting}
  9024. (inject #t Boolean)
  9025. \end{lstlisting}
  9026. \end{minipage}
  9027. \\[2ex]\hline
  9028. \begin{minipage}{0.27\textwidth}
  9029. \begin{lstlisting}
  9030. (+ |$e_1$| |$e_2$|)
  9031. \end{lstlisting}
  9032. \end{minipage}
  9033. &
  9034. $\Rightarrow$
  9035. &
  9036. \begin{minipage}{0.65\textwidth}
  9037. \begin{lstlisting}
  9038. (inject
  9039. (+ (project |$e'_1$| Integer)
  9040. (project |$e'_2$| Integer))
  9041. Integer)
  9042. \end{lstlisting}
  9043. \end{minipage}
  9044. \\[2ex]\hline
  9045. \begin{minipage}{0.27\textwidth}
  9046. \begin{lstlisting}
  9047. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9048. \end{lstlisting}
  9049. \end{minipage}
  9050. &
  9051. $\Rightarrow$
  9052. &
  9053. \begin{minipage}{0.65\textwidth}
  9054. \begin{lstlisting}
  9055. (inject
  9056. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9057. (Any|$\ldots$|Any -> Any))
  9058. \end{lstlisting}
  9059. \end{minipage}
  9060. \\[2ex]\hline
  9061. \begin{minipage}{0.27\textwidth}
  9062. \begin{lstlisting}
  9063. (|$e_0$| |$e_1 \ldots e_n$|)
  9064. \end{lstlisting}
  9065. \end{minipage}
  9066. &
  9067. $\Rightarrow$
  9068. &
  9069. \begin{minipage}{0.65\textwidth}
  9070. \begin{lstlisting}
  9071. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9072. \end{lstlisting}
  9073. \end{minipage}
  9074. \\[2ex]\hline
  9075. \begin{minipage}{0.27\textwidth}
  9076. \begin{lstlisting}
  9077. (vector-ref |$e_1$| |$e_2$|)
  9078. \end{lstlisting}
  9079. \end{minipage}
  9080. &
  9081. $\Rightarrow$
  9082. &
  9083. \begin{minipage}{0.65\textwidth}
  9084. \begin{lstlisting}
  9085. (any-vector-ref |$e_1'$| |$e_2'$|)
  9086. \end{lstlisting}
  9087. \end{minipage}
  9088. \\[2ex]\hline
  9089. \begin{minipage}{0.27\textwidth}
  9090. \begin{lstlisting}
  9091. (if |$e_1$| |$e_2$| |$e_3$|)
  9092. \end{lstlisting}
  9093. \end{minipage}
  9094. &
  9095. $\Rightarrow$
  9096. &
  9097. \begin{minipage}{0.65\textwidth}
  9098. \begin{lstlisting}
  9099. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9100. \end{lstlisting}
  9101. \end{minipage}
  9102. \\[2ex]\hline
  9103. \begin{minipage}{0.27\textwidth}
  9104. \begin{lstlisting}
  9105. (eq? |$e_1$| |$e_2$|)
  9106. \end{lstlisting}
  9107. \end{minipage}
  9108. &
  9109. $\Rightarrow$
  9110. &
  9111. \begin{minipage}{0.65\textwidth}
  9112. \begin{lstlisting}
  9113. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9114. \end{lstlisting}
  9115. \end{minipage}
  9116. \\[2ex]\hline
  9117. \begin{minipage}{0.27\textwidth}
  9118. \begin{lstlisting}
  9119. (not |$e_1$|)
  9120. \end{lstlisting}
  9121. \end{minipage}
  9122. &
  9123. $\Rightarrow$
  9124. &
  9125. \begin{minipage}{0.65\textwidth}
  9126. \begin{lstlisting}
  9127. (if (eq? |$e'_1$| (inject #f Boolean))
  9128. (inject #t Boolean) (inject #f Boolean))
  9129. \end{lstlisting}
  9130. \end{minipage}
  9131. \\[2ex]\hline
  9132. \end{tabular}
  9133. \caption{Cast Insertion}
  9134. \label{fig:compile-r7-Rany}
  9135. \end{figure}
  9136. \section{Reveal Casts}
  9137. \label{sec:reveal-casts-Rany}
  9138. % TODO: define R'_6
  9139. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9140. into an \code{if} expression that checks whether the value's tag
  9141. matches the target type; if it does, the value is converted to a value
  9142. of the target type by removing the tag; if it does not, the program
  9143. exits. To perform these actions we need a new primitive operation,
  9144. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9145. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9146. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9147. underlying value from a tagged value. The \code{ValueOf} form
  9148. includes the type for the underlying value which is used by the type
  9149. checker. Finally, the \code{Exit} form ends the execution of the
  9150. program.
  9151. If the target type of the projection is \code{Boolean} or
  9152. \code{Integer}, then \code{Project} can be translated as follows.
  9153. \begin{center}
  9154. \begin{minipage}{1.0\textwidth}
  9155. \begin{lstlisting}
  9156. (Project |$e$| |$\FType$|)
  9157. |$\Rightarrow$|
  9158. (Let |$\itm{tmp}$| |$e'$|
  9159. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9160. (Int |$\itm{tagof}(\FType)$|)))
  9161. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9162. (Exit)))
  9163. \end{lstlisting}
  9164. \end{minipage}
  9165. \end{center}
  9166. If the target type of the projection is a vector or function type,
  9167. then there is a bit more work to do. For vectors, check that the
  9168. length of the vector type matches the length of the vector (using the
  9169. \code{vector-length} primitive). For functions, check that the number
  9170. of parameters in the function type matches the function's arity (using
  9171. \code{procedure-arity}).
  9172. Regarding \code{inject}, we recommend compiling it to a slightly
  9173. lower-level primitive operation named \code{make-any}. This operation
  9174. takes a tag instead of a type.
  9175. \begin{center}
  9176. \begin{minipage}{1.0\textwidth}
  9177. \begin{lstlisting}
  9178. (Inject |$e$| |$\FType$|)
  9179. |$\Rightarrow$|
  9180. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9181. \end{lstlisting}
  9182. \end{minipage}
  9183. \end{center}
  9184. The type predicates (\code{boolean?}, etc.) can be translated into
  9185. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9186. translation of \code{Project}.
  9187. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9188. combine the projection action with the vector operation. Also, the
  9189. read and write operations allow arbitrary expressions for the index so
  9190. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9191. cannot guarantee that the index is within bounds. Thus, we insert code
  9192. to perform bounds checking at runtime. The translation for
  9193. \code{any-vector-ref} is as follows and the other two operations are
  9194. translated in a similar way.
  9195. \begin{lstlisting}
  9196. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9197. |$\Rightarrow$|
  9198. (Let |$v$| |$e'_1$|
  9199. (Let |$i$| |$e'_2$|
  9200. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9201. (If (Prim '< (list (Var |$i$|)
  9202. (Prim 'any-vector-length (list (Var |$v$|)))))
  9203. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9204. (Exit))))
  9205. \end{lstlisting}
  9206. \section{Remove Complex Operands}
  9207. \label{sec:rco-Rany}
  9208. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9209. The subexpression of \code{ValueOf} must be atomic.
  9210. \section{Explicate Control and \LangCAny{}}
  9211. \label{sec:explicate-Rany}
  9212. The output of \code{explicate-control} is the \LangCAny{} language whose
  9213. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9214. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9215. expression becomes a $\Tail$. Also, note that the index argument of
  9216. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9217. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9218. \begin{figure}[tp]
  9219. \fbox{
  9220. \begin{minipage}{0.96\textwidth}
  9221. \small
  9222. \[
  9223. \begin{array}{lcl}
  9224. \Exp &::= & \ldots
  9225. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9226. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9227. &\mid& \VALUEOF{\Exp}{\FType} \\
  9228. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9229. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9230. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9231. \mid \GOTO{\itm{label}} } \\
  9232. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9233. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9234. \mid \LP\key{Exit}\RP \\
  9235. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9236. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9237. \end{array}
  9238. \]
  9239. \end{minipage}
  9240. }
  9241. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9242. \label{fig:c5-syntax}
  9243. \end{figure}
  9244. \section{Select Instructions}
  9245. \label{sec:select-Rany}
  9246. In the \code{select-instructions} pass we translate the primitive
  9247. operations on the \code{Any} type to x86 instructions that involve
  9248. manipulating the 3 tag bits of the tagged value.
  9249. \paragraph{Make-any}
  9250. We recommend compiling the \key{make-any} primitive as follows if the
  9251. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9252. shifts the destination to the left by the number of bits specified its
  9253. source argument (in this case $3$, the length of the tag) and it
  9254. preserves the sign of the integer. We use the \key{orq} instruction to
  9255. combine the tag and the value to form the tagged value. \\
  9256. \begin{lstlisting}
  9257. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9258. |$\Rightarrow$|
  9259. movq |$e'$|, |\itm{lhs'}|
  9260. salq $3, |\itm{lhs'}|
  9261. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9262. \end{lstlisting}
  9263. The instruction selection for vectors and procedures is different
  9264. because their is no need to shift them to the left. The rightmost 3
  9265. bits are already zeros as described at the beginning of this
  9266. chapter. So we just combine the value and the tag using \key{orq}. \\
  9267. \begin{lstlisting}
  9268. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9269. |$\Rightarrow$|
  9270. movq |$e'$|, |\itm{lhs'}|
  9271. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9272. \end{lstlisting}
  9273. \paragraph{Tag-of-any}
  9274. Recall that the \code{tag-of-any} operation extracts the type tag from
  9275. a value of type \code{Any}. The type tag is the bottom three bits, so
  9276. we obtain the tag by taking the bitwise-and of the value with $111$
  9277. ($7$ in decimal).
  9278. \begin{lstlisting}
  9279. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9280. |$\Rightarrow$|
  9281. movq |$e'$|, |\itm{lhs'}|
  9282. andq $7, |\itm{lhs'}|
  9283. \end{lstlisting}
  9284. \paragraph{ValueOf}
  9285. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9286. depending on whether the type $T$ is a pointer (vector or procedure)
  9287. or not (Integer or Boolean). The following shows the instruction
  9288. selection for Integer and Boolean. We produce an untagged value by
  9289. shifting it to the right by 3 bits.
  9290. \begin{lstlisting}
  9291. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9292. |$\Rightarrow$|
  9293. movq |$e'$|, |\itm{lhs'}|
  9294. sarq $3, |\itm{lhs'}|
  9295. \end{lstlisting}
  9296. %
  9297. In the case for vectors and procedures, there is no need to
  9298. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9299. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9300. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9301. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9302. then apply \code{andq} with the tagged value to get the desired
  9303. result. \\
  9304. \begin{lstlisting}
  9305. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9306. |$\Rightarrow$|
  9307. movq $|$-8$|, |\itm{lhs'}|
  9308. andq |$e'$|, |\itm{lhs'}|
  9309. \end{lstlisting}
  9310. %% \paragraph{Type Predicates} We leave it to the reader to
  9311. %% devise a sequence of instructions to implement the type predicates
  9312. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9313. \paragraph{Any-vector-length}
  9314. \begin{lstlisting}
  9315. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9316. |$\Longrightarrow$|
  9317. movq |$\neg 111$|, %r11
  9318. andq |$a_1'$|, %r11
  9319. movq 0(%r11), %r11
  9320. andq $126, %r11
  9321. sarq $1, %r11
  9322. movq %r11, |$\itm{lhs'}$|
  9323. \end{lstlisting}
  9324. \paragraph{Any-vector-ref}
  9325. The index may be an arbitrary atom so instead of computing the offset
  9326. at compile time, instructions need to be generated to compute the
  9327. offset at runtime as follows. Note the use of the new instruction
  9328. \code{imulq}.
  9329. \begin{center}
  9330. \begin{minipage}{0.96\textwidth}
  9331. \begin{lstlisting}
  9332. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9333. |$\Longrightarrow$|
  9334. movq |$\neg 111$|, %r11
  9335. andq |$a_1'$|, %r11
  9336. movq |$a_2'$|, %rax
  9337. addq $1, %rax
  9338. imulq $8, %rax
  9339. addq %rax, %r11
  9340. movq 0(%r11) |$\itm{lhs'}$|
  9341. \end{lstlisting}
  9342. \end{minipage}
  9343. \end{center}
  9344. \paragraph{Any-vector-set!}
  9345. The code generation for \code{any-vector-set!} is similar to the other
  9346. \code{any-vector} operations.
  9347. \section{Register Allocation for \LangAny{}}
  9348. \label{sec:register-allocation-Rany}
  9349. \index{subject}{register allocation}
  9350. There is an interesting interaction between tagged values and garbage
  9351. collection that has an impact on register allocation. A variable of
  9352. type \code{Any} might refer to a vector and therefore it might be a
  9353. root that needs to be inspected and copied during garbage
  9354. collection. Thus, we need to treat variables of type \code{Any} in a
  9355. similar way to variables of type \code{Vector} for purposes of
  9356. register allocation. In particular,
  9357. \begin{itemize}
  9358. \item If a variable of type \code{Any} is live during a function call,
  9359. then it must be spilled. This can be accomplished by changing
  9360. \code{build-interference} to mark all variables of type \code{Any}
  9361. that are live after a \code{callq} as interfering with all the
  9362. registers.
  9363. \item If a variable of type \code{Any} is spilled, it must be spilled
  9364. to the root stack instead of the normal procedure call stack.
  9365. \end{itemize}
  9366. Another concern regarding the root stack is that the garbage collector
  9367. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9368. tagged value that points to a tuple, and (3) a tagged value that is
  9369. not a tuple. We enable this differentiation by choosing not to use the
  9370. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9371. reserved for identifying plain old pointers to tuples. That way, if
  9372. one of the first three bits is set, then we have a tagged value and
  9373. inspecting the tag can differentiation between vectors ($010$) and the
  9374. other kinds of values.
  9375. \begin{exercise}\normalfont
  9376. Expand your compiler to handle \LangAny{} as discussed in the last few
  9377. sections. Create 5 new programs that use the \code{Any} type and the
  9378. new operations (\code{inject}, \code{project}, \code{boolean?},
  9379. etc.). Test your compiler on these new programs and all of your
  9380. previously created test programs.
  9381. \end{exercise}
  9382. \begin{exercise}\normalfont
  9383. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9384. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9385. by removing type annotations. Add 5 more tests programs that
  9386. specifically rely on the language being dynamically typed. That is,
  9387. they should not be legal programs in a statically typed language, but
  9388. nevertheless, they should be valid \LangDyn{} programs that run to
  9389. completion without error.
  9390. \end{exercise}
  9391. \begin{figure}[p]
  9392. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9393. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9394. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9395. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9396. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9397. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9398. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9399. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9400. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9401. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9402. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9403. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9404. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9405. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9406. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9407. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9408. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9409. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9410. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9411. \path[->,bend left=15] (Rfun) edge [above] node
  9412. {\ttfamily\footnotesize shrink} (Rfun-2);
  9413. \path[->,bend left=15] (Rfun-2) edge [above] node
  9414. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9415. \path[->,bend left=15] (Rfun-3) edge [above] node
  9416. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9417. \path[->,bend right=15] (Rfun-4) edge [left] node
  9418. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9419. \path[->,bend left=15] (Rfun-5) edge [above] node
  9420. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9421. \path[->,bend left=15] (Rfun-6) edge [left] node
  9422. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9423. \path[->,bend left=15] (Rfun-7) edge [below] node
  9424. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9425. \path[->,bend right=15] (F1-2) edge [above] node
  9426. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9427. \path[->,bend right=15] (F1-3) edge [above] node
  9428. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9429. \path[->,bend right=15] (F1-4) edge [above] node
  9430. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9431. \path[->,bend right=15] (F1-5) edge [right] node
  9432. {\ttfamily\footnotesize explicate-control} (C3-2);
  9433. \path[->,bend left=15] (C3-2) edge [left] node
  9434. {\ttfamily\footnotesize select-instr.} (x86-2);
  9435. \path[->,bend right=15] (x86-2) edge [left] node
  9436. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9437. \path[->,bend right=15] (x86-2-1) edge [below] node
  9438. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9439. \path[->,bend right=15] (x86-2-2) edge [left] node
  9440. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9441. \path[->,bend left=15] (x86-3) edge [above] node
  9442. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9443. \path[->,bend left=15] (x86-4) edge [right] node
  9444. {\ttfamily\footnotesize print-x86} (x86-5);
  9445. \end{tikzpicture}
  9446. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9447. \label{fig:Rdyn-passes}
  9448. \end{figure}
  9449. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9450. for the compilation of \LangDyn{}.
  9451. % Further Reading
  9452. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9453. \chapter{Loops and Assignment}
  9454. \label{ch:Rwhile}
  9455. % TODO: define R'_8
  9456. % TODO: multi-graph
  9457. In this chapter we study two features that are the hallmarks of
  9458. imperative programming languages: loops and assignments to local
  9459. variables. The following example demonstrates these new features by
  9460. computing the sum of the first five positive integers.
  9461. % similar to loop_test_1.rkt
  9462. \begin{lstlisting}
  9463. (let ([sum 0])
  9464. (let ([i 5])
  9465. (begin
  9466. (while (> i 0)
  9467. (begin
  9468. (set! sum (+ sum i))
  9469. (set! i (- i 1))))
  9470. sum)))
  9471. \end{lstlisting}
  9472. The \code{while} loop consists of a condition and a body.
  9473. %
  9474. The \code{set!} consists of a variable and a right-hand-side expression.
  9475. %
  9476. The primary purpose of both the \code{while} loop and \code{set!} is
  9477. to cause side effects, so it is convenient to also include in a
  9478. language feature for sequencing side effects: the \code{begin}
  9479. expression. It consists of one or more subexpressions that are
  9480. evaluated left-to-right.
  9481. \section{The \LangLoop{} Language}
  9482. \begin{figure}[tp]
  9483. \centering
  9484. \fbox{
  9485. \begin{minipage}{0.96\textwidth}
  9486. \small
  9487. \[
  9488. \begin{array}{lcl}
  9489. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9490. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9491. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9492. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9493. \mid (\key{and}\;\Exp\;\Exp)
  9494. \mid (\key{or}\;\Exp\;\Exp)
  9495. \mid (\key{not}\;\Exp) } \\
  9496. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9497. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9498. (\key{vector-ref}\;\Exp\;\Int)} \\
  9499. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9500. \mid (\Exp \; \Exp\ldots) } \\
  9501. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9502. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9503. &\mid& \CSETBANG{\Var}{\Exp}
  9504. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9505. \mid \CWHILE{\Exp}{\Exp} \\
  9506. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9507. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  9508. \end{array}
  9509. \]
  9510. \end{minipage}
  9511. }
  9512. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9513. \label{fig:Rwhile-concrete-syntax}
  9514. \end{figure}
  9515. \begin{figure}[tp]
  9516. \centering
  9517. \fbox{
  9518. \begin{minipage}{0.96\textwidth}
  9519. \small
  9520. \[
  9521. \begin{array}{lcl}
  9522. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9523. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9524. &\mid& \gray{ \BOOL{\itm{bool}}
  9525. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9526. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9527. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9528. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9529. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9530. \mid \WHILE{\Exp}{\Exp} \\
  9531. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9532. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9533. \end{array}
  9534. \]
  9535. \end{minipage}
  9536. }
  9537. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9538. \label{fig:Rwhile-syntax}
  9539. \end{figure}
  9540. The concrete syntax of \LangLoop{} is defined in
  9541. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9542. in Figure~\ref{fig:Rwhile-syntax}.
  9543. %
  9544. The definitional interpreter for \LangLoop{} is shown in
  9545. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9546. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9547. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9548. support assignment to variables and to make their lifetimes indefinite
  9549. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9550. box the value that is bound to each variable (in \code{Let}) and
  9551. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9552. the value.
  9553. %
  9554. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9555. variable in the environment to obtain a boxed value and then we change
  9556. it using \code{set-box!} to the result of evaluating the right-hand
  9557. side. The result value of a \code{SetBang} is \code{void}.
  9558. %
  9559. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9560. if the result is true, 2) evaluate the body.
  9561. The result value of a \code{while} loop is also \code{void}.
  9562. %
  9563. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9564. subexpressions \itm{es} for their effects and then evaluates
  9565. and returns the result from \itm{body}.
  9566. \begin{figure}[tbp]
  9567. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9568. (define interp-Rwhile-class
  9569. (class interp-Rany-class
  9570. (super-new)
  9571. (define/override ((interp-exp env) e)
  9572. (define recur (interp-exp env))
  9573. (match e
  9574. [(SetBang x rhs)
  9575. (set-box! (lookup x env) (recur rhs))]
  9576. [(WhileLoop cnd body)
  9577. (define (loop)
  9578. (cond [(recur cnd) (recur body) (loop)]
  9579. [else (void)]))
  9580. (loop)]
  9581. [(Begin es body)
  9582. (for ([e es]) (recur e))
  9583. (recur body)]
  9584. [else ((super interp-exp env) e)]))
  9585. ))
  9586. (define (interp-Rwhile p)
  9587. (send (new interp-Rwhile-class) interp-program p))
  9588. \end{lstlisting}
  9589. \caption{Interpreter for \LangLoop{}.}
  9590. \label{fig:interp-Rwhile}
  9591. \end{figure}
  9592. The type checker for \LangLoop{} is define in
  9593. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9594. variable and the right-hand-side must agree. The result type is
  9595. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9596. \code{Boolean}. The result type is also \code{Void}. For
  9597. \code{Begin}, the result type is the type of its last subexpression.
  9598. \begin{figure}[tbp]
  9599. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9600. (define type-check-Rwhile-class
  9601. (class type-check-Rany-class
  9602. (super-new)
  9603. (inherit check-type-equal?)
  9604. (define/override (type-check-exp env)
  9605. (lambda (e)
  9606. (define recur (type-check-exp env))
  9607. (match e
  9608. [(SetBang x rhs)
  9609. (define-values (rhs^ rhsT) (recur rhs))
  9610. (define varT (dict-ref env x))
  9611. (check-type-equal? rhsT varT e)
  9612. (values (SetBang x rhs^) 'Void)]
  9613. [(WhileLoop cnd body)
  9614. (define-values (cnd^ Tc) (recur cnd))
  9615. (check-type-equal? Tc 'Boolean e)
  9616. (define-values (body^ Tbody) ((type-check-exp env) body))
  9617. (values (WhileLoop cnd^ body^) 'Void)]
  9618. [(Begin es body)
  9619. (define-values (es^ ts)
  9620. (for/lists (l1 l2) ([e es]) (recur e)))
  9621. (define-values (body^ Tbody) (recur body))
  9622. (values (Begin es^ body^) Tbody)]
  9623. [else ((super type-check-exp env) e)])))
  9624. ))
  9625. (define (type-check-Rwhile p)
  9626. (send (new type-check-Rwhile-class) type-check-program p))
  9627. \end{lstlisting}
  9628. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9629. and \code{Begin} in \LangLoop{}.}
  9630. \label{fig:type-check-Rwhile}
  9631. \end{figure}
  9632. At first glance, the translation of these language features to x86
  9633. seems straightforward because the \LangCFun{} intermediate language already
  9634. supports all of the ingredients that we need: assignment, \code{goto},
  9635. conditional branching, and sequencing. However, there are two
  9636. complications that arise which we discuss in the next two
  9637. sections. After that we introduce one new compiler pass and the
  9638. changes necessary to the existing passes.
  9639. \section{Assignment and Lexically Scoped Functions}
  9640. \label{sec:assignment-scoping}
  9641. The addition of assignment raises a problem with our approach to
  9642. implementing lexically-scoped functions. Consider the following
  9643. example in which function \code{f} has a free variable \code{x} that
  9644. is changed after \code{f} is created but before the call to \code{f}.
  9645. % loop_test_11.rkt
  9646. \begin{lstlisting}
  9647. (let ([x 0])
  9648. (let ([y 0])
  9649. (let ([z 20])
  9650. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9651. (begin
  9652. (set! x 10)
  9653. (set! y 12)
  9654. (f y))))))
  9655. \end{lstlisting}
  9656. The correct output for this example is \code{42} because the call to
  9657. \code{f} is required to use the current value of \code{x} (which is
  9658. \code{10}). Unfortunately, the closure conversion pass
  9659. (Section~\ref{sec:closure-conversion}) generates code for the
  9660. \code{lambda} that copies the old value of \code{x} into a
  9661. closure. Thus, if we naively add support for assignment to our current
  9662. compiler, the output of this program would be \code{32}.
  9663. A first attempt at solving this problem would be to save a pointer to
  9664. \code{x} in the closure and change the occurrences of \code{x} inside
  9665. the lambda to dereference the pointer. Of course, this would require
  9666. assigning \code{x} to the stack and not to a register. However, the
  9667. problem goes a bit deeper. Consider the following example in which we
  9668. create a counter abstraction by creating a pair of functions that
  9669. share the free variable \code{x}.
  9670. % similar to loop_test_10.rkt
  9671. \begin{lstlisting}
  9672. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9673. (vector
  9674. (lambda: () : Integer x)
  9675. (lambda: () : Void (set! x (+ 1 x)))))
  9676. (let ([counter (f 0)])
  9677. (let ([get (vector-ref counter 0)])
  9678. (let ([inc (vector-ref counter 1)])
  9679. (begin
  9680. (inc)
  9681. (get)))))
  9682. \end{lstlisting}
  9683. In this example, the lifetime of \code{x} extends beyond the lifetime
  9684. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9685. stack frame for the call to \code{f}, it would be gone by the time we
  9686. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9687. \code{x}. This example demonstrates that when a variable occurs free
  9688. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9689. value of the variable needs to live on the heap. The verb ``box'' is
  9690. often used for allocating a single value on the heap, producing a
  9691. pointer, and ``unbox'' for dereferencing the pointer.
  9692. We recommend solving these problems by ``boxing'' the local variables
  9693. that are in the intersection of 1) variables that appear on the
  9694. left-hand-side of a \code{set!} and 2) variables that occur free
  9695. inside a \code{lambda}. We shall introduce a new pass named
  9696. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9697. perform this translation. But before diving into the compiler passes,
  9698. we one more problem to discuss.
  9699. \section{Cyclic Control Flow and Dataflow Analysis}
  9700. \label{sec:dataflow-analysis}
  9701. Up until this point the control-flow graphs generated in
  9702. \code{explicate-control} were guaranteed to be acyclic. However, each
  9703. \code{while} loop introduces a cycle in the control-flow graph.
  9704. But does that matter?
  9705. %
  9706. Indeed it does. Recall that for register allocation, the compiler
  9707. performs liveness analysis to determine which variables can share the
  9708. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9709. the control-flow graph in reverse topological order, but topological
  9710. order is only well-defined for acyclic graphs.
  9711. Let us return to the example of computing the sum of the first five
  9712. positive integers. Here is the program after instruction selection but
  9713. before register allocation.
  9714. \begin{center}
  9715. \begin{minipage}{0.45\textwidth}
  9716. \begin{lstlisting}
  9717. (define (main) : Integer
  9718. mainstart:
  9719. movq $0, sum1
  9720. movq $5, i2
  9721. jmp block5
  9722. block5:
  9723. movq i2, tmp3
  9724. cmpq tmp3, $0
  9725. jl block7
  9726. jmp block8
  9727. \end{lstlisting}
  9728. \end{minipage}
  9729. \begin{minipage}{0.45\textwidth}
  9730. \begin{lstlisting}
  9731. block7:
  9732. addq i2, sum1
  9733. movq $1, tmp4
  9734. negq tmp4
  9735. addq tmp4, i2
  9736. jmp block5
  9737. block8:
  9738. movq $27, %rax
  9739. addq sum1, %rax
  9740. jmp mainconclusion
  9741. )
  9742. \end{lstlisting}
  9743. \end{minipage}
  9744. \end{center}
  9745. Recall that liveness analysis works backwards, starting at the end
  9746. of each function. For this example we could start with \code{block8}
  9747. because we know what is live at the beginning of the conclusion,
  9748. just \code{rax} and \code{rsp}. So the live-before set
  9749. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9750. %
  9751. Next we might try to analyze \code{block5} or \code{block7}, but
  9752. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9753. we are stuck.
  9754. The way out of this impasse comes from the realization that one can
  9755. perform liveness analysis starting with an empty live-after set to
  9756. compute an under-approximation of the live-before set. By
  9757. \emph{under-approximation}, we mean that the set only contains
  9758. variables that are really live, but it may be missing some. Next, the
  9759. under-approximations for each block can be improved by 1) updating the
  9760. live-after set for each block using the approximate live-before sets
  9761. from the other blocks and 2) perform liveness analysis again on each
  9762. block. In fact, by iterating this process, the under-approximations
  9763. eventually become the correct solutions!
  9764. %
  9765. This approach of iteratively analyzing a control-flow graph is
  9766. applicable to many static analysis problems and goes by the name
  9767. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9768. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9769. Washington.
  9770. Let us apply this approach to the above example. We use the empty set
  9771. for the initial live-before set for each block. Let $m_0$ be the
  9772. following mapping from label names to sets of locations (variables and
  9773. registers).
  9774. \begin{center}
  9775. \begin{lstlisting}
  9776. mainstart: {}
  9777. block5: {}
  9778. block7: {}
  9779. block8: {}
  9780. \end{lstlisting}
  9781. \end{center}
  9782. Using the above live-before approximations, we determine the
  9783. live-after for each block and then apply liveness analysis to each
  9784. block. This produces our next approximation $m_1$ of the live-before
  9785. sets.
  9786. \begin{center}
  9787. \begin{lstlisting}
  9788. mainstart: {}
  9789. block5: {i2}
  9790. block7: {i2, sum1}
  9791. block8: {rsp, sum1}
  9792. \end{lstlisting}
  9793. \end{center}
  9794. For the second round, the live-after for \code{mainstart} is the
  9795. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9796. liveness analysis for \code{mainstart} computes the empty set. The
  9797. live-after for \code{block5} is the union of the live-before sets for
  9798. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9799. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9800. sum1\}}. The live-after for \code{block7} is the live-before for
  9801. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9802. So the liveness analysis for \code{block7} remains \code{\{i2,
  9803. sum1\}}. Together these yield the following approximation $m_2$ of
  9804. the live-before sets.
  9805. \begin{center}
  9806. \begin{lstlisting}
  9807. mainstart: {}
  9808. block5: {i2, rsp, sum1}
  9809. block7: {i2, sum1}
  9810. block8: {rsp, sum1}
  9811. \end{lstlisting}
  9812. \end{center}
  9813. In the preceding iteration, only \code{block5} changed, so we can
  9814. limit our attention to \code{mainstart} and \code{block7}, the two
  9815. blocks that jump to \code{block5}. As a result, the live-before sets
  9816. for \code{mainstart} and \code{block7} are updated to include
  9817. \code{rsp}, yielding the following approximation $m_3$.
  9818. \begin{center}
  9819. \begin{lstlisting}
  9820. mainstart: {rsp}
  9821. block5: {i2, rsp, sum1}
  9822. block7: {i2, rsp, sum1}
  9823. block8: {rsp, sum1}
  9824. \end{lstlisting}
  9825. \end{center}
  9826. Because \code{block7} changed, we analyze \code{block5} once more, but
  9827. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9828. our approximations have converged, so $m_3$ is the solution.
  9829. This iteration process is guaranteed to converge to a solution by the
  9830. Kleene Fixed-Point Theorem, a general theorem about functions on
  9831. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9832. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9833. elements, a least element $\bot$ (pronounced bottom), and a join
  9834. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9835. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9836. working with join semi-lattices.} When two elements are ordered $m_i
  9837. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9838. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9839. approximation than $m_i$. The bottom element $\bot$ represents the
  9840. complete lack of information, i.e., the worst approximation. The join
  9841. operator takes two lattice elements and combines their information,
  9842. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9843. bound}
  9844. A dataflow analysis typically involves two lattices: one lattice to
  9845. represent abstract states and another lattice that aggregates the
  9846. abstract states of all the blocks in the control-flow graph. For
  9847. liveness analysis, an abstract state is a set of locations. We form
  9848. the lattice $L$ by taking its elements to be sets of locations, the
  9849. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9850. set, and the join operator to be set union.
  9851. %
  9852. We form a second lattice $M$ by taking its elements to be mappings
  9853. from the block labels to sets of locations (elements of $L$). We
  9854. order the mappings point-wise, using the ordering of $L$. So given any
  9855. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9856. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9857. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9858. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9859. We can think of one iteration of liveness analysis as being a function
  9860. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9861. mapping.
  9862. \[
  9863. f(m_i) = m_{i+1}
  9864. \]
  9865. Next let us think for a moment about what a final solution $m_s$
  9866. should look like. If we perform liveness analysis using the solution
  9867. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9868. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9869. \[
  9870. f(m_s) = m_s
  9871. \]
  9872. Furthermore, the solution should only include locations that are
  9873. forced to be there by performing liveness analysis on the program, so
  9874. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9875. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9876. monotone (better inputs produce better outputs), then the least fixed
  9877. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9878. chain} obtained by starting at $\bot$ and iterating $f$ as
  9879. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9880. \[
  9881. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9882. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9883. \]
  9884. When a lattice contains only finitely-long ascending chains, then
  9885. every Kleene chain tops out at some fixed point after a number of
  9886. iterations of $f$. So that fixed point is also a least upper
  9887. bound of the chain.
  9888. \[
  9889. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9890. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9891. \]
  9892. The liveness analysis is indeed a monotone function and the lattice
  9893. $M$ only has finitely-long ascending chains because there are only a
  9894. finite number of variables and blocks in the program. Thus we are
  9895. guaranteed that iteratively applying liveness analysis to all blocks
  9896. in the program will eventually produce the least fixed point solution.
  9897. Next let us consider dataflow analysis in general and discuss the
  9898. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9899. %
  9900. The algorithm has four parameters: the control-flow graph \code{G}, a
  9901. function \code{transfer} that applies the analysis to one block, the
  9902. \code{bottom} and \code{join} operator for the lattice of abstract
  9903. states. The algorithm begins by creating the bottom mapping,
  9904. represented by a hash table. It then pushes all of the nodes in the
  9905. control-flow graph onto the work list (a queue). The algorithm repeats
  9906. the \code{while} loop as long as there are items in the work list. In
  9907. each iteration, a node is popped from the work list and processed. The
  9908. \code{input} for the node is computed by taking the join of the
  9909. abstract states of all the predecessor nodes. The \code{transfer}
  9910. function is then applied to obtain the \code{output} abstract
  9911. state. If the output differs from the previous state for this block,
  9912. the mapping for this block is updated and its successor nodes are
  9913. pushed onto the work list.
  9914. \begin{figure}[tb]
  9915. \begin{lstlisting}
  9916. (define (analyze-dataflow G transfer bottom join)
  9917. (define mapping (make-hash))
  9918. (for ([v (in-vertices G)])
  9919. (dict-set! mapping v bottom))
  9920. (define worklist (make-queue))
  9921. (for ([v (in-vertices G)])
  9922. (enqueue! worklist v))
  9923. (define trans-G (transpose G))
  9924. (while (not (queue-empty? worklist))
  9925. (define node (dequeue! worklist))
  9926. (define input (for/fold ([state bottom])
  9927. ([pred (in-neighbors trans-G node)])
  9928. (join state (dict-ref mapping pred))))
  9929. (define output (transfer node input))
  9930. (cond [(not (equal? output (dict-ref mapping node)))
  9931. (dict-set! mapping node output)
  9932. (for ([v (in-neighbors G node)])
  9933. (enqueue! worklist v))]))
  9934. mapping)
  9935. \end{lstlisting}
  9936. \caption{Generic work list algorithm for dataflow analysis}
  9937. \label{fig:generic-dataflow}
  9938. \end{figure}
  9939. Having discussed the two complications that arise from adding support
  9940. for assignment and loops, we turn to discussing the one new compiler
  9941. pass and the significant changes to existing passes.
  9942. \section{Convert Assignments}
  9943. \label{sec:convert-assignments}
  9944. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9945. the combination of assignments and lexically-scoped functions requires
  9946. that we box those variables that are both assigned-to and that appear
  9947. free inside a \code{lambda}. The purpose of the
  9948. \code{convert-assignments} pass is to carry out that transformation.
  9949. We recommend placing this pass after \code{uniquify} but before
  9950. \code{reveal-functions}.
  9951. Consider again the first example from
  9952. Section~\ref{sec:assignment-scoping}:
  9953. \begin{lstlisting}
  9954. (let ([x 0])
  9955. (let ([y 0])
  9956. (let ([z 20])
  9957. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9958. (begin
  9959. (set! x 10)
  9960. (set! y 12)
  9961. (f y))))))
  9962. \end{lstlisting}
  9963. The variables \code{x} and \code{y} are assigned-to. The variables
  9964. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9965. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9966. The boxing of \code{x} consists of three transformations: initialize
  9967. \code{x} with a vector, replace reads from \code{x} with
  9968. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9969. \code{vector-set!}. The output of \code{convert-assignments} for this
  9970. example is as follows.
  9971. \begin{lstlisting}
  9972. (define (main) : Integer
  9973. (let ([x0 (vector 0)])
  9974. (let ([y1 0])
  9975. (let ([z2 20])
  9976. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9977. (+ a3 (+ (vector-ref x0 0) z2)))])
  9978. (begin
  9979. (vector-set! x0 0 10)
  9980. (set! y1 12)
  9981. (f4 y1)))))))
  9982. \end{lstlisting}
  9983. \paragraph{Assigned \& Free}
  9984. We recommend defining an auxiliary function named
  9985. \code{assigned\&free} that takes an expression and simultaneously
  9986. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9987. that occur free within lambda's, and 3) a new version of the
  9988. expression that records which bound variables occurred in the
  9989. intersection of $A$ and $F$. You can use the struct
  9990. \code{AssignedFree} to do this. Consider the case for
  9991. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9992. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9993. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9994. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9995. \begin{lstlisting}
  9996. (Let |$x$| |$rhs$| |$body$|)
  9997. |$\Rightarrow$|
  9998. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  9999. \end{lstlisting}
  10000. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10001. The set of assigned variables for this \code{Let} is
  10002. $A_r \cup (A_b - \{x\})$
  10003. and the set of variables free in lambda's is
  10004. $F_r \cup (F_b - \{x\})$.
  10005. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10006. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10007. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10008. and $F_r$.
  10009. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10010. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10011. recursively processing \itm{body}. Wrap each of parameter that occurs
  10012. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10013. Let $P$ be the set of parameter names in \itm{params}. The result is
  10014. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10015. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10016. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10017. \paragraph{Convert Assignments}
  10018. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10019. functions for expressions and definitions. The function for
  10020. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10021. set of assigned-and-free variables (obtained from the result of
  10022. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10023. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10024. \code{vector-ref}.
  10025. \begin{lstlisting}
  10026. (Var |$x$|)
  10027. |$\Rightarrow$|
  10028. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10029. \end{lstlisting}
  10030. %
  10031. In the case for $\LET{\LP\code{AssignedFree}\,
  10032. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10033. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10034. \itm{body'} but with $x$ added to the set of assigned-and-free
  10035. variables. Translate the let-expression as follows to bind $x$ to a
  10036. boxed value.
  10037. \begin{lstlisting}
  10038. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10039. |$\Rightarrow$|
  10040. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10041. \end{lstlisting}
  10042. %
  10043. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10044. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10045. variables, translate the \code{set!} into a \code{vector-set!}
  10046. as follows.
  10047. \begin{lstlisting}
  10048. (SetBang |$x$| |$\itm{rhs}$|)
  10049. |$\Rightarrow$|
  10050. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10051. \end{lstlisting}
  10052. %
  10053. The case for \code{Lambda} is non-trivial, but it is similar to the
  10054. case for function definitions, which we discuss next.
  10055. The auxiliary function for definitions, \code{cnvt-assign-def},
  10056. applies assignment conversion to function definitions.
  10057. We translate a function definition as follows.
  10058. \begin{lstlisting}
  10059. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10060. |$\Rightarrow$|
  10061. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10062. \end{lstlisting}
  10063. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10064. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10065. \code{assigned\&free} on $\itm{body_1}$.
  10066. Let $P$ be the parameter names in \itm{params}.
  10067. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10068. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10069. as the set of assigned-and-free variables.
  10070. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10071. in a sequence of let-expressions that box the parameters
  10072. that are in $A_b \cap F_b$.
  10073. %
  10074. Regarding \itm{params'}, change the names of the parameters that are
  10075. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10076. variables can retain the original names). Recall the second example in
  10077. Section~\ref{sec:assignment-scoping} involving a counter
  10078. abstraction. The following is the output of assignment version for
  10079. function \code{f}.
  10080. \begin{lstlisting}
  10081. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10082. (vector
  10083. (lambda: () : Integer x1)
  10084. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10085. |$\Rightarrow$|
  10086. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10087. (let ([x1 (vector param_x1)])
  10088. (vector (lambda: () : Integer (vector-ref x1 0))
  10089. (lambda: () : Void
  10090. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10091. \end{lstlisting}
  10092. \section{Remove Complex Operands}
  10093. \label{sec:rco-loop}
  10094. The three new language forms, \code{while}, \code{set!}, and
  10095. \code{begin} are all complex expressions and their subexpressions are
  10096. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10097. output language \LangFunANF{} of this pass.
  10098. \begin{figure}[tp]
  10099. \centering
  10100. \fbox{
  10101. \begin{minipage}{0.96\textwidth}
  10102. \small
  10103. \[
  10104. \begin{array}{rcl}
  10105. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10106. \mid \VOID{} } \\
  10107. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10108. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10109. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10110. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10111. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10112. \end{array}
  10113. \]
  10114. \end{minipage}
  10115. }
  10116. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10117. \label{fig:Rwhile-anf-syntax}
  10118. \end{figure}
  10119. As usual, when a complex expression appears in a grammar position that
  10120. needs to be atomic, such as the argument of a primitive operator, we
  10121. must introduce a temporary variable and bind it to the complex
  10122. expression. This approach applies, unchanged, to handle the new
  10123. language forms. For example, in the following code there are two
  10124. \code{begin} expressions appearing as arguments to \code{+}. The
  10125. output of \code{rco-exp} is shown below, in which the \code{begin}
  10126. expressions have been bound to temporary variables. Recall that
  10127. \code{let} expressions in \LangLoopANF{} are allowed to have
  10128. arbitrary expressions in their right-hand-side expression, so it is
  10129. fine to place \code{begin} there.
  10130. \begin{lstlisting}
  10131. (let ([x0 10])
  10132. (let ([y1 0])
  10133. (+ (+ (begin (set! y1 (read)) x0)
  10134. (begin (set! x0 (read)) y1))
  10135. x0)))
  10136. |$\Rightarrow$|
  10137. (let ([x0 10])
  10138. (let ([y1 0])
  10139. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10140. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10141. (let ([tmp4 (+ tmp2 tmp3)])
  10142. (+ tmp4 x0))))))
  10143. \end{lstlisting}
  10144. \section{Explicate Control and \LangCLoop{}}
  10145. \label{sec:explicate-loop}
  10146. Recall that in the \code{explicate-control} pass we define one helper
  10147. function for each kind of position in the program. For the \LangVar{}
  10148. language of integers and variables we needed kinds of positions:
  10149. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10150. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10151. yet another kind of position: effect position. Except for the last
  10152. subexpression, the subexpressions inside a \code{begin} are evaluated
  10153. only for their effect. Their result values are discarded. We can
  10154. generate better code by taking this fact into account.
  10155. The output language of \code{explicate-control} is \LangCLoop{}
  10156. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10157. \LangCLam{}. The only syntactic difference is that \code{Call},
  10158. \code{vector-set!}, and \code{read} may also appear as statements.
  10159. The most significant difference between \LangCLam{} and \LangCLoop{}
  10160. is that the control-flow graphs of the later may contain cycles.
  10161. \begin{figure}[tp]
  10162. \fbox{
  10163. \begin{minipage}{0.96\textwidth}
  10164. \small
  10165. \[
  10166. \begin{array}{lcl}
  10167. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10168. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10169. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10170. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10171. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10172. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10173. \end{array}
  10174. \]
  10175. \end{minipage}
  10176. }
  10177. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10178. \label{fig:c7-syntax}
  10179. \end{figure}
  10180. The new auxiliary function \code{explicate-effect} takes an expression
  10181. (in an effect position) and a promise of a continuation block. The
  10182. function returns a promise for a $\Tail$ that includes the generated
  10183. code for the input expression followed by the continuation block. If
  10184. the expression is obviously pure, that is, never causes side effects,
  10185. then the expression can be removed, so the result is just the
  10186. continuation block.
  10187. %
  10188. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10189. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10190. the loop. Recursively process the \itm{body} (in effect position)
  10191. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10192. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10193. \itm{body'} as the then-branch and the continuation block as the
  10194. else-branch. The result should be added to the control-flow graph with
  10195. the label \itm{loop}. The result for the whole \code{while} loop is a
  10196. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10197. added to the control-flow graph if the loop is indeed used, which can
  10198. be accomplished using \code{delay}.
  10199. The auxiliary functions for tail, assignment, and predicate positions
  10200. need to be updated. The three new language forms, \code{while},
  10201. \code{set!}, and \code{begin}, can appear in assignment and tail
  10202. positions. Only \code{begin} may appear in predicate positions; the
  10203. other two have result type \code{Void}.
  10204. \section{Select Instructions}
  10205. \label{sec:select-instructions-loop}
  10206. Only three small additions are needed in the
  10207. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10208. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10209. stand-alone statements instead of only appearing on the right-hand
  10210. side of an assignment statement. The code generation is nearly
  10211. identical; just leave off the instruction for moving the result into
  10212. the left-hand side.
  10213. \section{Register Allocation}
  10214. \label{sec:register-allocation-loop}
  10215. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10216. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10217. which complicates the liveness analysis needed for register
  10218. allocation.
  10219. \subsection{Liveness Analysis}
  10220. \label{sec:liveness-analysis-r8}
  10221. We recommend using the generic \code{analyze-dataflow} function that
  10222. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10223. perform liveness analysis, replacing the code in
  10224. \code{uncover-live-CFG} that processed the basic blocks in topological
  10225. order (Section~\ref{sec:liveness-analysis-Rif}).
  10226. The \code{analyze-dataflow} function has four parameters.
  10227. \begin{enumerate}
  10228. \item The first parameter \code{G} should be a directed graph from the
  10229. \code{racket/graph} package (see the sidebar in
  10230. Section~\ref{sec:build-interference}) that represents the
  10231. control-flow graph.
  10232. \item The second parameter \code{transfer} is a function that applies
  10233. liveness analysis to a basic block. It takes two parameters: the
  10234. label for the block to analyze and the live-after set for that
  10235. block. The transfer function should return the live-before set for
  10236. the block. Also, as a side-effect, it should update the block's
  10237. $\itm{info}$ with the liveness information for each instruction. To
  10238. implement the \code{transfer} function, you should be able to reuse
  10239. the code you already have for analyzing basic blocks.
  10240. \item The third and fourth parameters of \code{analyze-dataflow} are
  10241. \code{bottom} and \code{join} for the lattice of abstract states,
  10242. i.e. sets of locations. The bottom of the lattice is the empty set
  10243. \code{(set)} and the join operator is \code{set-union}.
  10244. \end{enumerate}
  10245. \begin{figure}[p]
  10246. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10247. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10248. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10249. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10250. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10251. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10252. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10253. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10254. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10255. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10256. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10257. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10258. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10259. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10260. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10261. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10262. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10263. %% \path[->,bend left=15] (Rfun) edge [above] node
  10264. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10265. \path[->,bend left=15] (Rfun) edge [above] node
  10266. {\ttfamily\footnotesize shrink} (Rfun-2);
  10267. \path[->,bend left=15] (Rfun-2) edge [above] node
  10268. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10269. \path[->,bend left=15] (Rfun-3) edge [above] node
  10270. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10271. \path[->,bend left=15] (Rfun-4) edge [right] node
  10272. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10273. \path[->,bend left=15] (F1-1) edge [below] node
  10274. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10275. \path[->,bend right=15] (F1-2) edge [above] node
  10276. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10277. \path[->,bend right=15] (F1-3) edge [above] node
  10278. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10279. \path[->,bend right=15] (F1-4) edge [above] node
  10280. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10281. \path[->,bend right=15] (F1-5) edge [right] node
  10282. {\ttfamily\footnotesize explicate-control} (C3-2);
  10283. \path[->,bend left=15] (C3-2) edge [left] node
  10284. {\ttfamily\footnotesize select-instr.} (x86-2);
  10285. \path[->,bend right=15] (x86-2) edge [left] node
  10286. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10287. \path[->,bend right=15] (x86-2-1) edge [below] node
  10288. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10289. \path[->,bend right=15] (x86-2-2) edge [left] node
  10290. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10291. \path[->,bend left=15] (x86-3) edge [above] node
  10292. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10293. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10294. \end{tikzpicture}
  10295. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10296. \label{fig:Rwhile-passes}
  10297. \end{figure}
  10298. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10299. for the compilation of \LangLoop{}.
  10300. \section{Challenge: Arrays}
  10301. \label{sec:arrays}
  10302. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10303. elements whose length is determined at compile-time and where each
  10304. element of a tuple may have a different type (they are
  10305. heterogeous). This challenge is also about sequences, but this time
  10306. the length is determined at run-time and all the elements have the same
  10307. type (they are homogeneous). We use the term ``array'' for this later
  10308. kind of sequence.
  10309. The Racket language does not distinguish between tuples and arrays,
  10310. they are both represented by vectors. However, Typed Racket
  10311. distinguishes between tuples and arrays: the \code{Vector} type is for
  10312. tuples and the \code{Vectorof} type is for arrays.
  10313. %
  10314. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10315. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10316. and the \code{make-vector} primitive operator for creating an array,
  10317. whose arguments are the length of the array and an initial value for
  10318. all the elements in the array. The \code{vector-length},
  10319. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10320. for tuples become overloaded for use with arrays.
  10321. %
  10322. We also include integer multiplication in \LangArray{}, as it is
  10323. useful in many examples involving arrays such as computing the
  10324. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10325. \begin{figure}[tp]
  10326. \centering
  10327. \fbox{
  10328. \begin{minipage}{0.96\textwidth}
  10329. \small
  10330. \[
  10331. \begin{array}{lcl}
  10332. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10333. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10334. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10335. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10336. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10337. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10338. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10339. \mid \LP\key{not}\;\Exp\RP } \\
  10340. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10341. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10342. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10343. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10344. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10345. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10346. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10347. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10348. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10349. \mid \CWHILE{\Exp}{\Exp} } \\
  10350. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10351. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10352. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10353. \end{array}
  10354. \]
  10355. \end{minipage}
  10356. }
  10357. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10358. \label{fig:Rvecof-concrete-syntax}
  10359. \end{figure}
  10360. \begin{figure}[tp]
  10361. \begin{lstlisting}
  10362. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10363. [n : Integer]) : Integer
  10364. (let ([i 0])
  10365. (let ([prod 0])
  10366. (begin
  10367. (while (< i n)
  10368. (begin
  10369. (set! prod (+ prod (* (vector-ref A i)
  10370. (vector-ref B i))))
  10371. (set! i (+ i 1))
  10372. ))
  10373. prod))))
  10374. (let ([A (make-vector 2 2)])
  10375. (let ([B (make-vector 2 3)])
  10376. (+ (inner-product A B 2)
  10377. 30)))
  10378. \end{lstlisting}
  10379. \caption{Example program that computes the inner-product.}
  10380. \label{fig:inner-product}
  10381. \end{figure}
  10382. The type checker for \LangArray{} is define in
  10383. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10384. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10385. of the intializing expression. The length expression is required to
  10386. have type \code{Integer}. The type checking of the operators
  10387. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10388. updated to handle the situation where the vector has type
  10389. \code{Vectorof}. In these cases we translate the operators to their
  10390. \code{vectorof} form so that later passes can easily distinguish
  10391. between operations on tuples versus arrays. We override the
  10392. \code{operator-types} method to provide the type signature for
  10393. multiplication: it takes two integers and returns an integer. To
  10394. support injection and projection of arrays to the \code{Any} type
  10395. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10396. predicate.
  10397. \begin{figure}[tbp]
  10398. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10399. (define type-check-Rvecof-class
  10400. (class type-check-Rwhile-class
  10401. (super-new)
  10402. (inherit check-type-equal?)
  10403. (define/override (flat-ty? ty)
  10404. (match ty
  10405. ['(Vectorof Any) #t]
  10406. [else (super flat-ty? ty)]))
  10407. (define/override (operator-types)
  10408. (append '((* . ((Integer Integer) . Integer)))
  10409. (super operator-types)))
  10410. (define/override (type-check-exp env)
  10411. (lambda (e)
  10412. (define recur (type-check-exp env))
  10413. (match e
  10414. [(Prim 'make-vector (list e1 e2))
  10415. (define-values (e1^ t1) (recur e1))
  10416. (define-values (e2^ elt-type) (recur e2))
  10417. (define vec-type `(Vectorof ,elt-type))
  10418. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10419. vec-type)]
  10420. [(Prim 'vector-ref (list e1 e2))
  10421. (define-values (e1^ t1) (recur e1))
  10422. (define-values (e2^ t2) (recur e2))
  10423. (match* (t1 t2)
  10424. [(`(Vectorof ,elt-type) 'Integer)
  10425. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10426. [(other wise) ((super type-check-exp env) e)])]
  10427. [(Prim 'vector-set! (list e1 e2 e3) )
  10428. (define-values (e-vec t-vec) (recur e1))
  10429. (define-values (e2^ t2) (recur e2))
  10430. (define-values (e-arg^ t-arg) (recur e3))
  10431. (match t-vec
  10432. [`(Vectorof ,elt-type)
  10433. (check-type-equal? elt-type t-arg e)
  10434. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10435. [else ((super type-check-exp env) e)])]
  10436. [(Prim 'vector-length (list e1))
  10437. (define-values (e1^ t1) (recur e1))
  10438. (match t1
  10439. [`(Vectorof ,t)
  10440. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10441. [else ((super type-check-exp env) e)])]
  10442. [else ((super type-check-exp env) e)])))
  10443. ))
  10444. (define (type-check-Rvecof p)
  10445. (send (new type-check-Rvecof-class) type-check-program p))
  10446. \end{lstlisting}
  10447. \caption{Type checker for the \LangArray{} language.}
  10448. \label{fig:type-check-Rvecof}
  10449. \end{figure}
  10450. The interpreter for \LangArray{} is defined in
  10451. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10452. implemented with Racket's \code{make-vector} function and
  10453. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10454. integers.
  10455. \begin{figure}[tbp]
  10456. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10457. (define interp-Rvecof-class
  10458. (class interp-Rwhile-class
  10459. (super-new)
  10460. (define/override (interp-op op)
  10461. (verbose "Rvecof/interp-op" op)
  10462. (match op
  10463. ['make-vector make-vector]
  10464. ['* fx*]
  10465. [else (super interp-op op)]))
  10466. ))
  10467. (define (interp-Rvecof p)
  10468. (send (new interp-Rvecof-class) interp-program p))
  10469. \end{lstlisting}
  10470. \caption{Interpreter for \LangArray{}.}
  10471. \label{fig:interp-Rvecof}
  10472. \end{figure}
  10473. \subsection{Data Representation}
  10474. \label{sec:array-rep}
  10475. Just like tuples, we store arrays on the heap which means that the
  10476. garbage collector will need to inspect arrays. An immediate thought is
  10477. to use the same representation for arrays that we use for tuples.
  10478. However, we limit tuples to a length of $50$ so that their length and
  10479. pointer mask can fit into the 64-bit tag at the beginning of each
  10480. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10481. millions of elements, so we need more bits to store the length.
  10482. However, because arrays are homogeneous, we only need $1$ bit for the
  10483. pointer mask instead of one bit per array elements. Finally, the
  10484. garbage collector will need to be able to distinguish between tuples
  10485. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10486. arrive at the following layout for the 64-bit tag at the beginning of
  10487. an array:
  10488. \begin{itemize}
  10489. \item The right-most bit is the forwarding bit, just like in a tuple.
  10490. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10491. it is not.
  10492. \item The next bit to the left is the pointer mask. A $0$ indicates
  10493. that none of the elements are pointers to the heap and a $1$
  10494. indicates that all of the elements are pointers.
  10495. \item The next $61$ bits store the length of the array.
  10496. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10497. array ($1$).
  10498. \end{itemize}
  10499. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10500. differentiate the kinds of values that have been injected into the
  10501. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10502. to indicate that the value is an array.
  10503. In the following subsections we provide hints regarding how to update
  10504. the passes to handle arrays.
  10505. \subsection{Reveal Casts}
  10506. The array-access operators \code{vectorof-ref} and
  10507. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10508. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10509. that the type checker cannot tell whether the index will be in bounds,
  10510. so the bounds check must be performed at run time. Recall that the
  10511. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10512. an \code{If} arround a vector reference for update to check whether
  10513. the index is less than the length. You should do the same for
  10514. \code{vectorof-ref} and \code{vectorof-set!} .
  10515. In addition, the handling of the \code{any-vector} operators in
  10516. \code{reveal-casts} needs to be updated to account for arrays that are
  10517. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10518. generated code should test whether the tag is for tuples (\code{010})
  10519. or arrays (\code{110}) and then dispatch to either
  10520. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10521. we add a case in \code{select-instructions} to generate the
  10522. appropriate instructions for accessing the array length from the
  10523. header of an array.
  10524. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10525. the generated code needs to check that the index is less than the
  10526. vector length, so like the code for \code{any-vector-length}, check
  10527. the tag to determine whether to use \code{any-vector-length} or
  10528. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10529. is complete, the generated code can use \code{any-vector-ref} and
  10530. \code{any-vector-set!} for both tuples and arrays because the
  10531. instructions used for those operators do not look at the tag at the
  10532. front of the tuple or array.
  10533. \subsection{Expose Allocation}
  10534. This pass should translate the \code{make-vector} operator into
  10535. lower-level operations. In particular, the new AST node
  10536. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10537. length specified by the $\Exp$, but does not initialize the elements
  10538. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10539. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10540. element type for the array. Regarding the initialization of the array,
  10541. we recommend generated a \code{while} loop that uses
  10542. \code{vector-set!} to put the initializing value into every element of
  10543. the array.
  10544. \subsection{Remove Complex Operands}
  10545. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10546. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10547. complex and its subexpression must be atomic.
  10548. \subsection{Explicate Control}
  10549. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10550. \code{explicate-assign}.
  10551. \subsection{Select Instructions}
  10552. Generate instructions for \code{AllocateArray} similar to those for
  10553. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10554. that the tag at the front of the array should instead use the
  10555. representation discussed in Section~\ref{sec:array-rep}.
  10556. Regarding \code{vectorof-length}, extract the length from the tag
  10557. according to the representation discussed in
  10558. Section~\ref{sec:array-rep}.
  10559. The instructions generated for \code{vectorof-ref} differ from those
  10560. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10561. that the index is not a constant so the offset must be computed at
  10562. runtime, similar to the instructions generated for
  10563. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10564. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10565. appear in an assignment and as a stand-alone statement, so make sure
  10566. to handle both situations in this pass.
  10567. Finally, the instructions for \code{any-vectorof-length} should be
  10568. similar to those for \code{vectorof-length}, except that one must
  10569. first project the array by writing zeroes into the $3$-bit tag
  10570. \begin{exercise}\normalfont
  10571. Implement a compiler for the \LangArray{} language by extending your
  10572. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10573. programs, including the one in Figure~\ref{fig:inner-product} and also
  10574. a program that multiplies two matrices. Note that matrices are
  10575. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10576. arrays by laying out each row in the array, one after the next.
  10577. \end{exercise}
  10578. % Further Reading: dataflow analysis
  10579. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10580. \chapter{Gradual Typing}
  10581. \label{ch:Rgrad}
  10582. \index{subject}{gradual typing}
  10583. This chapter studies a language, \LangGrad{}, in which the programmer
  10584. can choose between static and dynamic type checking in different parts
  10585. of a program, thereby mixing the statically typed \LangLoop{} language
  10586. with the dynamically typed \LangDyn{}. There are several approaches to
  10587. mixing static and dynamic typing, including multi-language
  10588. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10589. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10590. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  10591. programmer controls the amount of static versus dynamic checking by
  10592. adding or removing type annotations on parameters and
  10593. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10594. %
  10595. The concrete syntax of \LangGrad{} is defined in
  10596. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10597. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10598. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10599. non-terminals that make type annotations optional. The return types
  10600. are not optional in the abstract syntax; the parser fills in
  10601. \code{Any} when the return type is not specified in the concrete
  10602. syntax.
  10603. \begin{figure}[tp]
  10604. \centering
  10605. \fbox{
  10606. \begin{minipage}{0.96\textwidth}
  10607. \small
  10608. \[
  10609. \begin{array}{lcl}
  10610. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10611. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10612. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10613. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10614. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10615. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10616. \mid (\key{and}\;\Exp\;\Exp)
  10617. \mid (\key{or}\;\Exp\;\Exp)
  10618. \mid (\key{not}\;\Exp) } \\
  10619. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10620. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10621. (\key{vector-ref}\;\Exp\;\Int)} \\
  10622. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10623. \mid (\Exp \; \Exp\ldots) } \\
  10624. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10625. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10626. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10627. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10628. \mid \CWHILE{\Exp}{\Exp} } \\
  10629. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10630. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  10631. \end{array}
  10632. \]
  10633. \end{minipage}
  10634. }
  10635. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10636. \label{fig:Rgrad-concrete-syntax}
  10637. \end{figure}
  10638. \begin{figure}[tp]
  10639. \centering
  10640. \fbox{
  10641. \begin{minipage}{0.96\textwidth}
  10642. \small
  10643. \[
  10644. \begin{array}{lcl}
  10645. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10646. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10647. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10648. &\mid& \gray{ \BOOL{\itm{bool}}
  10649. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10650. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10651. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10652. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10653. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10654. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10655. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10656. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10657. \end{array}
  10658. \]
  10659. \end{minipage}
  10660. }
  10661. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10662. \label{fig:Rgrad-syntax}
  10663. \end{figure}
  10664. Both the type checker and the interpreter for \LangGrad{} require some
  10665. interesting changes to enable gradual typing, which we discuss in the
  10666. next two sections in the context of the \code{map-vec} example from
  10667. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10668. revised the \code{map-vec} example, omitting the type annotations from
  10669. the \code{add1} function.
  10670. \begin{figure}[btp]
  10671. % gradual_test_9.rkt
  10672. \begin{lstlisting}
  10673. (define (map-vec [f : (Integer -> Integer)]
  10674. [v : (Vector Integer Integer)])
  10675. : (Vector Integer Integer)
  10676. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10677. (define (add1 x) (+ x 1))
  10678. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10679. \end{lstlisting}
  10680. \caption{A partially-typed version of the \code{map-vec} example.}
  10681. \label{fig:gradual-map-vec}
  10682. \end{figure}
  10683. \section{Type Checking \LangGrad{} and \LangCast{}}
  10684. \label{sec:gradual-type-check}
  10685. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10686. parameter and return types. For example, the \code{x} parameter of
  10687. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10688. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10689. consider the \code{+} operator inside \code{add1}. It expects both
  10690. arguments to have type \code{Integer}, but its first argument \code{x}
  10691. has type \code{Any}. In a gradually typed language, such differences
  10692. are allowed so long as the types are \emph{consistent}, that is, they
  10693. are equal except in places where there is an \code{Any} type. The type
  10694. \code{Any} is consistent with every other type.
  10695. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10696. \begin{figure}[tbp]
  10697. \begin{lstlisting}
  10698. (define/public (consistent? t1 t2)
  10699. (match* (t1 t2)
  10700. [('Integer 'Integer) #t]
  10701. [('Boolean 'Boolean) #t]
  10702. [('Void 'Void) #t]
  10703. [('Any t2) #t]
  10704. [(t1 'Any) #t]
  10705. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10706. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10707. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10708. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10709. (consistent? rt1 rt2))]
  10710. [(other wise) #f]))
  10711. \end{lstlisting}
  10712. \caption{The consistency predicate on types.}
  10713. \label{fig:consistent}
  10714. \end{figure}
  10715. Returning to the \code{map-vec} example of
  10716. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10717. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10718. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10719. because the two types are consistent. In particular, \code{->} is
  10720. equal to \code{->} and because \code{Any} is consistent with
  10721. \code{Integer}.
  10722. Next consider a program with an error, such as applying the
  10723. \code{map-vec} to a function that sometimes returns a Boolean, as
  10724. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10725. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10726. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10727. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10728. Integer)}. One might say that a gradual type checker is optimistic
  10729. in that it accepts programs that might execute without a runtime type
  10730. error.
  10731. %
  10732. Unfortunately, running this program with input \code{1} triggers an
  10733. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10734. performs checking at runtime to ensure the integrity of the static
  10735. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10736. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10737. new \code{Cast} form that is inserted by the type checker. Thus, the
  10738. output of the type checker is a program in the \LangCast{} language, which
  10739. adds \code{Cast} to \LangLoop{}, as shown in
  10740. Figure~\ref{fig:Rgrad-prime-syntax}.
  10741. \begin{figure}[tp]
  10742. \centering
  10743. \fbox{
  10744. \begin{minipage}{0.96\textwidth}
  10745. \small
  10746. \[
  10747. \begin{array}{lcl}
  10748. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10749. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10750. \end{array}
  10751. \]
  10752. \end{minipage}
  10753. }
  10754. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10755. \label{fig:Rgrad-prime-syntax}
  10756. \end{figure}
  10757. \begin{figure}[tbp]
  10758. \begin{lstlisting}
  10759. (define (map-vec [f : (Integer -> Integer)]
  10760. [v : (Vector Integer Integer)])
  10761. : (Vector Integer Integer)
  10762. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10763. (define (add1 x) (+ x 1))
  10764. (define (true) #t)
  10765. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10766. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10767. \end{lstlisting}
  10768. \caption{A variant of the \code{map-vec} example with an error.}
  10769. \label{fig:map-vec-maybe-add1}
  10770. \end{figure}
  10771. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10772. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10773. inserted every time the type checker sees two types that are
  10774. consistent but not equal. In the \code{add1} function, \code{x} is
  10775. cast to \code{Integer} and the result of the \code{+} is cast to
  10776. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10777. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10778. \begin{figure}[btp]
  10779. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10780. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10781. : (Vector Integer Integer)
  10782. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10783. (define (add1 [x : Any]) : Any
  10784. (cast (+ (cast x Any Integer) 1) Integer Any))
  10785. (define (true) : Any (cast #t Boolean Any))
  10786. (define (maybe-add1 [x : Any]) : Any
  10787. (if (eq? 0 (read)) (add1 x) (true)))
  10788. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10789. (vector 0 41)) 0)
  10790. \end{lstlisting}
  10791. \caption{Output of type checking \code{map-vec}
  10792. and \code{maybe-add1}.}
  10793. \label{fig:map-vec-cast}
  10794. \end{figure}
  10795. The type checker for \LangGrad{} is defined in
  10796. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10797. and \ref{fig:type-check-Rgradual-3}.
  10798. \begin{figure}[tbp]
  10799. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10800. (define type-check-gradual-class
  10801. (class type-check-Rwhile-class
  10802. (super-new)
  10803. (inherit operator-types type-predicates)
  10804. (define/override (type-check-exp env)
  10805. (lambda (e)
  10806. (define recur (type-check-exp env))
  10807. (match e
  10808. [(Prim 'vector-length (list e1))
  10809. (define-values (e1^ t) (recur e1))
  10810. (match t
  10811. [`(Vector ,ts ...)
  10812. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10813. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10814. [(Prim 'vector-ref (list e1 e2))
  10815. (define-values (e1^ t1) (recur e1))
  10816. (define-values (e2^ t2) (recur e2))
  10817. (check-consistent? t2 'Integer e)
  10818. (match t1
  10819. [`(Vector ,ts ...)
  10820. (match e2^
  10821. [(Int i)
  10822. (unless (and (0 . <= . i) (i . < . (length ts)))
  10823. (error 'type-check "invalid index ~a in ~a" i e))
  10824. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10825. [else (define e1^^ (make-cast e1^ t1 'Any))
  10826. (define e2^^ (make-cast e2^ t2 'Integer))
  10827. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10828. ['Any
  10829. (define e2^^ (make-cast e2^ t2 'Integer))
  10830. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10831. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10832. [(Prim 'vector-set! (list e1 e2 e3) )
  10833. (define-values (e1^ t1) (recur e1))
  10834. (define-values (e2^ t2) (recur e2))
  10835. (define-values (e3^ t3) (recur e3))
  10836. (check-consistent? t2 'Integer e)
  10837. (match t1
  10838. [`(Vector ,ts ...)
  10839. (match e2^
  10840. [(Int i)
  10841. (unless (and (0 . <= . i) (i . < . (length ts)))
  10842. (error 'type-check "invalid index ~a in ~a" i e))
  10843. (check-consistent? (list-ref ts i) t3 e)
  10844. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10845. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10846. [else
  10847. (define e1^^ (make-cast e1^ t1 'Any))
  10848. (define e2^^ (make-cast e2^ t2 'Integer))
  10849. (define e3^^ (make-cast e3^ t3 'Any))
  10850. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10851. ['Any
  10852. (define e2^^ (make-cast e2^ t2 'Integer))
  10853. (define e3^^ (make-cast e3^ t3 'Any))
  10854. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10855. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10856. \end{lstlisting}
  10857. \caption{Type checker for the \LangGrad{} language, part 1.}
  10858. \label{fig:type-check-Rgradual-1}
  10859. \end{figure}
  10860. \begin{figure}[tbp]
  10861. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10862. [(Prim 'eq? (list e1 e2))
  10863. (define-values (e1^ t1) (recur e1))
  10864. (define-values (e2^ t2) (recur e2))
  10865. (check-consistent? t1 t2 e)
  10866. (define T (meet t1 t2))
  10867. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10868. 'Boolean)]
  10869. [(Prim 'not (list e1))
  10870. (define-values (e1^ t1) (recur e1))
  10871. (match t1
  10872. ['Any
  10873. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10874. (Bool #t) (Bool #f)))]
  10875. [else
  10876. (define-values (t-ret new-es^)
  10877. (type-check-op 'not (list t1) (list e1^) e))
  10878. (values (Prim 'not new-es^) t-ret)])]
  10879. [(Prim 'and (list e1 e2))
  10880. (recur (If e1 e2 (Bool #f)))]
  10881. [(Prim 'or (list e1 e2))
  10882. (define tmp (gensym 'tmp))
  10883. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10884. [(Prim op es)
  10885. #:when (not (set-member? explicit-prim-ops op))
  10886. (define-values (new-es ts)
  10887. (for/lists (exprs types) ([e es])
  10888. (recur e)))
  10889. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10890. (values (Prim op new-es^) t-ret)]
  10891. [(If e1 e2 e3)
  10892. (define-values (e1^ T1) (recur e1))
  10893. (define-values (e2^ T2) (recur e2))
  10894. (define-values (e3^ T3) (recur e3))
  10895. (check-consistent? T2 T3 e)
  10896. (match T1
  10897. ['Boolean
  10898. (define Tif (join T2 T3))
  10899. (values (If e1^ (make-cast e2^ T2 Tif)
  10900. (make-cast e3^ T3 Tif)) Tif)]
  10901. ['Any
  10902. (define Tif (meet T2 T3))
  10903. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10904. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10905. Tif)]
  10906. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10907. [(HasType e1 T)
  10908. (define-values (e1^ T1) (recur e1))
  10909. (check-consistent? T1 T)
  10910. (values (make-cast e1^ T1 T) T)]
  10911. [(SetBang x e1)
  10912. (define-values (e1^ T1) (recur e1))
  10913. (define varT (dict-ref env x))
  10914. (check-consistent? T1 varT e)
  10915. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10916. [(WhileLoop e1 e2)
  10917. (define-values (e1^ T1) (recur e1))
  10918. (check-consistent? T1 'Boolean e)
  10919. (define-values (e2^ T2) ((type-check-exp env) e2))
  10920. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10921. \end{lstlisting}
  10922. \caption{Type checker for the \LangGrad{} language, part 2.}
  10923. \label{fig:type-check-Rgradual-2}
  10924. \end{figure}
  10925. \begin{figure}[tbp]
  10926. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10927. [(Apply e1 e2s)
  10928. (define-values (e1^ T1) (recur e1))
  10929. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10930. (match T1
  10931. [`(,T1ps ... -> ,T1rt)
  10932. (for ([T2 T2s] [Tp T1ps])
  10933. (check-consistent? T2 Tp e))
  10934. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10935. (make-cast e2 src tgt)))
  10936. (values (Apply e1^ e2s^^) T1rt)]
  10937. [`Any
  10938. (define e1^^ (make-cast e1^ 'Any
  10939. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10940. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10941. (make-cast e2 src 'Any)))
  10942. (values (Apply e1^^ e2s^^) 'Any)]
  10943. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10944. [(Lambda params Tr e1)
  10945. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10946. (match p
  10947. [`[,x : ,T] (values x T)]
  10948. [(? symbol? x) (values x 'Any)])))
  10949. (define-values (e1^ T1)
  10950. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10951. (check-consistent? Tr T1 e)
  10952. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10953. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10954. [else ((super type-check-exp env) e)]
  10955. )))
  10956. \end{lstlisting}
  10957. \caption{Type checker for the \LangGrad{} language, part 3.}
  10958. \label{fig:type-check-Rgradual-3}
  10959. \end{figure}
  10960. \begin{figure}[tbp]
  10961. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10962. (define/public (join t1 t2)
  10963. (match* (t1 t2)
  10964. [('Integer 'Integer) 'Integer]
  10965. [('Boolean 'Boolean) 'Boolean]
  10966. [('Void 'Void) 'Void]
  10967. [('Any t2) t2]
  10968. [(t1 'Any) t1]
  10969. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10970. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10971. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10972. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10973. -> ,(join rt1 rt2))]))
  10974. (define/public (meet t1 t2)
  10975. (match* (t1 t2)
  10976. [('Integer 'Integer) 'Integer]
  10977. [('Boolean 'Boolean) 'Boolean]
  10978. [('Void 'Void) 'Void]
  10979. [('Any t2) 'Any]
  10980. [(t1 'Any) 'Any]
  10981. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10982. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10983. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10984. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10985. -> ,(meet rt1 rt2))]))
  10986. (define/public (make-cast e src tgt)
  10987. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10988. (define/public (check-consistent? t1 t2 e)
  10989. (unless (consistent? t1 t2)
  10990. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10991. (define/override (type-check-op op arg-types args e)
  10992. (match (dict-ref (operator-types) op)
  10993. [`(,param-types . ,return-type)
  10994. (for ([at arg-types] [pt param-types])
  10995. (check-consistent? at pt e))
  10996. (values return-type
  10997. (for/list ([e args] [s arg-types] [t param-types])
  10998. (make-cast e s t)))]
  10999. [else (error 'type-check-op "unrecognized ~a" op)]))
  11000. (define explicit-prim-ops
  11001. (set-union
  11002. (type-predicates)
  11003. (set 'procedure-arity 'eq?
  11004. 'vector 'vector-length 'vector-ref 'vector-set!
  11005. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11006. (define/override (fun-def-type d)
  11007. (match d
  11008. [(Def f params rt info body)
  11009. (define ps
  11010. (for/list ([p params])
  11011. (match p
  11012. [`[,x : ,T] T]
  11013. [(? symbol?) 'Any]
  11014. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11015. `(,@ps -> ,rt)]
  11016. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11017. \end{lstlisting}
  11018. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11019. \label{fig:type-check-Rgradual-aux}
  11020. \end{figure}
  11021. \clearpage
  11022. \section{Interpreting \LangCast{}}
  11023. \label{sec:interp-casts}
  11024. The runtime behavior of first-order casts is straightforward, that is,
  11025. casts involving simple types such as \code{Integer} and
  11026. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11027. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11028. puts the integer into a tagged value
  11029. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11030. \code{Integer} is accomplished with the \code{Project} operator, that
  11031. is, by checking the value's tag and either retrieving the underlying
  11032. integer or signaling an error if it the tag is not the one for
  11033. integers (Figure~\ref{fig:apply-project}).
  11034. %
  11035. Things get more interesting for higher-order casts, that is, casts
  11036. involving function or vector types.
  11037. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11038. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11039. this cast at runtime, we can't know in general whether the function
  11040. will always return an integer.\footnote{Predicting the return value of
  11041. a function is equivalent to the halting problem, which is
  11042. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11043. of the cast until the function is applied. This is accomplished by
  11044. wrapping \code{maybe-add1} in a new function that casts its parameter
  11045. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11046. casts the return value from \code{Any} to \code{Integer}.
  11047. Turning our attention to casts involving vector types, we consider the
  11048. example in Figure~\ref{fig:map-vec-bang} that defines a
  11049. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11050. type \code{(Vector Any Any)} and that updates \code{v} in place
  11051. instead of returning a new vector. So we name this function
  11052. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11053. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11054. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11055. cast between vector types would be a build a new vector whose elements
  11056. are the result of casting each of the original elements to the
  11057. appropriate target type. However, this approach is only valid for
  11058. immutable vectors; and our vectors are mutable. In the example of
  11059. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11060. the updates inside of \code{map-vec!} would happen to the new vector
  11061. and not the original one.
  11062. \begin{figure}[tbp]
  11063. % gradual_test_11.rkt
  11064. \begin{lstlisting}
  11065. (define (map-vec! [f : (Any -> Any)]
  11066. [v : (Vector Any Any)]) : Void
  11067. (begin
  11068. (vector-set! v 0 (f (vector-ref v 0)))
  11069. (vector-set! v 1 (f (vector-ref v 1)))))
  11070. (define (add1 x) (+ x 1))
  11071. (let ([v (vector 0 41)])
  11072. (begin (map-vec! add1 v) (vector-ref v 1)))
  11073. \end{lstlisting}
  11074. \caption{An example involving casts on vectors.}
  11075. \label{fig:map-vec-bang}
  11076. \end{figure}
  11077. Instead the interpreter needs to create a new kind of value, a
  11078. \emph{vector proxy}, that intercepts every vector operation. On a
  11079. read, the proxy reads from the underlying vector and then applies a
  11080. cast to the resulting value. On a write, the proxy casts the argument
  11081. value and then performs the write to the underlying vector. For the
  11082. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11083. \code{0} from \code{Integer} to \code{Any}. For the first
  11084. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11085. to \code{Integer}.
  11086. The final category of cast that we need to consider are casts between
  11087. the \code{Any} type and either a function or a vector
  11088. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11089. in which parameter \code{v} does not have a type annotation, so it is
  11090. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11091. type \code{(Vector Integer Integer)} so the type checker inserts a
  11092. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11093. thought is to use \code{Inject}, but that doesn't work because
  11094. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11095. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11096. to \code{Any}.
  11097. \begin{figure}[tbp]
  11098. \begin{lstlisting}
  11099. (define (map-vec! [f : (Any -> Any)] v) : Void
  11100. (begin
  11101. (vector-set! v 0 (f (vector-ref v 0)))
  11102. (vector-set! v 1 (f (vector-ref v 1)))))
  11103. (define (add1 x) (+ x 1))
  11104. (let ([v (vector 0 41)])
  11105. (begin (map-vec! add1 v) (vector-ref v 1)))
  11106. \end{lstlisting}
  11107. \caption{Casting a vector to \code{Any}.}
  11108. \label{fig:map-vec-any}
  11109. \end{figure}
  11110. The \LangCast{} interpreter uses an auxiliary function named
  11111. \code{apply-cast} to cast a value from a source type to a target type,
  11112. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11113. of the kinds of casts that we've discussed in this section.
  11114. \begin{figure}[tbp]
  11115. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11116. (define/public (apply-cast v s t)
  11117. (match* (s t)
  11118. [(t1 t2) #:when (equal? t1 t2) v]
  11119. [('Any t2)
  11120. (match t2
  11121. [`(,ts ... -> ,rt)
  11122. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11123. (define v^ (apply-project v any->any))
  11124. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11125. [`(Vector ,ts ...)
  11126. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11127. (define v^ (apply-project v vec-any))
  11128. (apply-cast v^ vec-any `(Vector ,@ts))]
  11129. [else (apply-project v t2)])]
  11130. [(t1 'Any)
  11131. (match t1
  11132. [`(,ts ... -> ,rt)
  11133. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11134. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11135. (apply-inject v^ (any-tag any->any))]
  11136. [`(Vector ,ts ...)
  11137. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11138. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11139. (apply-inject v^ (any-tag vec-any))]
  11140. [else (apply-inject v (any-tag t1))])]
  11141. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11142. (define x (gensym 'x))
  11143. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11144. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11145. (define cast-writes
  11146. (for/list ([t1 ts1] [t2 ts2])
  11147. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11148. `(vector-proxy ,(vector v (apply vector cast-reads)
  11149. (apply vector cast-writes)))]
  11150. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11151. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11152. `(function ,xs ,(Cast
  11153. (Apply (Value v)
  11154. (for/list ([x xs][t1 ts1][t2 ts2])
  11155. (Cast (Var x) t2 t1)))
  11156. rt1 rt2) ())]
  11157. ))
  11158. \end{lstlisting}
  11159. \caption{The \code{apply-cast} auxiliary method.}
  11160. \label{fig:apply-cast}
  11161. \end{figure}
  11162. The interpreter for \LangCast{} is defined in
  11163. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11164. dispatching to \code{apply-cast}. To handle the addition of vector
  11165. proxies, we update the vector primitives in \code{interp-op} using the
  11166. functions in Figure~\ref{fig:guarded-vector}.
  11167. \begin{figure}[tbp]
  11168. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11169. (define interp-Rcast-class
  11170. (class interp-Rwhile-class
  11171. (super-new)
  11172. (inherit apply-fun apply-inject apply-project)
  11173. (define/override (interp-op op)
  11174. (match op
  11175. ['vector-length guarded-vector-length]
  11176. ['vector-ref guarded-vector-ref]
  11177. ['vector-set! guarded-vector-set!]
  11178. ['any-vector-ref (lambda (v i)
  11179. (match v [`(tagged ,v^ ,tg)
  11180. (guarded-vector-ref v^ i)]))]
  11181. ['any-vector-set! (lambda (v i a)
  11182. (match v [`(tagged ,v^ ,tg)
  11183. (guarded-vector-set! v^ i a)]))]
  11184. ['any-vector-length (lambda (v)
  11185. (match v [`(tagged ,v^ ,tg)
  11186. (guarded-vector-length v^)]))]
  11187. [else (super interp-op op)]
  11188. ))
  11189. (define/override ((interp-exp env) e)
  11190. (define (recur e) ((interp-exp env) e))
  11191. (match e
  11192. [(Value v) v]
  11193. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11194. [else ((super interp-exp env) e)]))
  11195. ))
  11196. (define (interp-Rcast p)
  11197. (send (new interp-Rcast-class) interp-program p))
  11198. \end{lstlisting}
  11199. \caption{The interpreter for \LangCast{}.}
  11200. \label{fig:interp-Rcast}
  11201. \end{figure}
  11202. \begin{figure}[tbp]
  11203. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11204. (define (guarded-vector-ref vec i)
  11205. (match vec
  11206. [`(vector-proxy ,proxy)
  11207. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11208. (define rd (vector-ref (vector-ref proxy 1) i))
  11209. (apply-fun rd (list val) 'guarded-vector-ref)]
  11210. [else (vector-ref vec i)]))
  11211. (define (guarded-vector-set! vec i arg)
  11212. (match vec
  11213. [`(vector-proxy ,proxy)
  11214. (define wr (vector-ref (vector-ref proxy 2) i))
  11215. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11216. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11217. [else (vector-set! vec i arg)]))
  11218. (define (guarded-vector-length vec)
  11219. (match vec
  11220. [`(vector-proxy ,proxy)
  11221. (guarded-vector-length (vector-ref proxy 0))]
  11222. [else (vector-length vec)]))
  11223. \end{lstlisting}
  11224. \caption{The guarded-vector auxiliary functions.}
  11225. \label{fig:guarded-vector}
  11226. \end{figure}
  11227. \section{Lower Casts}
  11228. \label{sec:lower-casts}
  11229. The next step in the journey towards x86 is the \code{lower-casts}
  11230. pass that translates the casts in \LangCast{} to the lower-level
  11231. \code{Inject} and \code{Project} operators and a new operator for
  11232. creating vector proxies, extending the \LangLoop{} language to create
  11233. \LangProxy{}. We recommend creating an auxiliary function named
  11234. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11235. and a target type, and translates it to expression in \LangProxy{} that has
  11236. the same behavior as casting the expression from the source to the
  11237. target type in the interpreter.
  11238. The \code{lower-cast} function can follow a code structure similar to
  11239. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11240. the interpreter for \LangCast{} because it must handle the same cases as
  11241. \code{apply-cast} and it needs to mimic the behavior of
  11242. \code{apply-cast}. The most interesting cases are those concerning the
  11243. casts between two vector types and between two function types.
  11244. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11245. type to another vector type is accomplished by creating a proxy that
  11246. intercepts the operations on the underlying vector. Here we make the
  11247. creation of the proxy explicit with the \code{vector-proxy} primitive
  11248. operation. It takes three arguments, the first is an expression for
  11249. the vector, the second is a vector of functions for casting an element
  11250. that is being read from the vector, and the third is a vector of
  11251. functions for casting an element that is being written to the vector.
  11252. You can create the functions using \code{Lambda}. Also, as we shall
  11253. see in the next section, we need to differentiate these vectors from
  11254. the user-created ones, so we recommend using a new primitive operator
  11255. named \code{raw-vector} instead of \code{vector} to create these
  11256. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11257. the output of \code{lower-casts} on the example in
  11258. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11259. integers to a vector of \code{Any}.
  11260. \begin{figure}[tbp]
  11261. \begin{lstlisting}
  11262. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11263. (begin
  11264. (vector-set! v 0 (f (vector-ref v 0)))
  11265. (vector-set! v 1 (f (vector-ref v 1)))))
  11266. (define (add1 [x : Any]) : Any
  11267. (inject (+ (project x Integer) 1) Integer))
  11268. (let ([v (vector 0 41)])
  11269. (begin
  11270. (map-vec! add1 (vector-proxy v
  11271. (raw-vector (lambda: ([x9 : Integer]) : Any
  11272. (inject x9 Integer))
  11273. (lambda: ([x9 : Integer]) : Any
  11274. (inject x9 Integer)))
  11275. (raw-vector (lambda: ([x9 : Any]) : Integer
  11276. (project x9 Integer))
  11277. (lambda: ([x9 : Any]) : Integer
  11278. (project x9 Integer)))))
  11279. (vector-ref v 1)))
  11280. \end{lstlisting}
  11281. \caption{Output of \code{lower-casts} on the example in
  11282. Figure~\ref{fig:map-vec-bang}.}
  11283. \label{fig:map-vec-bang-lower-cast}
  11284. \end{figure}
  11285. A cast from one function type to another function type is accomplished
  11286. by generating a \code{Lambda} whose parameter and return types match
  11287. the target function type. The body of the \code{Lambda} should cast
  11288. the parameters from the target type to the source type (yes,
  11289. backwards! functions are contravariant\index{subject}{contravariant} in the
  11290. parameters), then call the underlying function, and finally cast the
  11291. result from the source return type to the target return type.
  11292. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11293. \code{lower-casts} pass on the \code{map-vec} example in
  11294. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11295. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11296. \begin{figure}[tbp]
  11297. \begin{lstlisting}
  11298. (define (map-vec [f : (Integer -> Integer)]
  11299. [v : (Vector Integer Integer)])
  11300. : (Vector Integer Integer)
  11301. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11302. (define (add1 [x : Any]) : Any
  11303. (inject (+ (project x Integer) 1) Integer))
  11304. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11305. (project (add1 (inject x9 Integer)) Integer))
  11306. (vector 0 41)) 1)
  11307. \end{lstlisting}
  11308. \caption{Output of \code{lower-casts} on the example in
  11309. Figure~\ref{fig:gradual-map-vec}.}
  11310. \label{fig:map-vec-lower-cast}
  11311. \end{figure}
  11312. \section{Differentiate Proxies}
  11313. \label{sec:differentiate-proxies}
  11314. So far the job of differentiating vectors and vector proxies has been
  11315. the job of the interpreter. For example, the interpreter for \LangCast{}
  11316. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11317. function in Figure~\ref{fig:guarded-vector}. In the
  11318. \code{differentiate-proxies} pass we shift this responsibility to the
  11319. generated code.
  11320. We begin by designing the output language $R^p_8$. In
  11321. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11322. proxies. In $R^p_8$ we return the \code{Vector} type to
  11323. its original meaning, as the type of real vectors, and we introduce a
  11324. new type, \code{PVector}, whose values can be either real vectors or
  11325. vector proxies. This new type comes with a suite of new primitive
  11326. operations for creating and using values of type \code{PVector}. We
  11327. don't need to introduce a new type to represent vector proxies. A
  11328. proxy is represented by a vector containing three things: 1) the
  11329. underlying vector, 2) a vector of functions for casting elements that
  11330. are read from the vector, and 3) a vector of functions for casting
  11331. values to be written to the vector. So we define the following
  11332. abbreviation for the type of a vector proxy:
  11333. \[
  11334. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11335. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11336. \to (\key{PVector}~ T' \ldots)
  11337. \]
  11338. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11339. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11340. %
  11341. Next we describe each of the new primitive operations.
  11342. \begin{description}
  11343. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11344. (\key{PVector} $T \ldots$)]\ \\
  11345. %
  11346. This operation brands a vector as a value of the \code{PVector} type.
  11347. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11348. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11349. %
  11350. This operation brands a vector proxy as value of the \code{PVector} type.
  11351. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11352. \code{Boolean}] \ \\
  11353. %
  11354. returns true if the value is a vector proxy and false if it is a
  11355. real vector.
  11356. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11357. (\key{Vector} $T \ldots$)]\ \\
  11358. %
  11359. Assuming that the input is a vector (and not a proxy), this
  11360. operation returns the vector.
  11361. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11362. $\to$ \code{Boolean}]\ \\
  11363. %
  11364. Given a vector proxy, this operation returns the length of the
  11365. underlying vector.
  11366. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11367. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11368. %
  11369. Given a vector proxy, this operation returns the $i$th element of
  11370. the underlying vector.
  11371. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11372. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11373. proxy, this operation writes a value to the $i$th element of the
  11374. underlying vector.
  11375. \end{description}
  11376. Now to discuss the translation that differentiates vectors from
  11377. proxies. First, every type annotation in the program must be
  11378. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11379. Next, we must insert uses of \code{PVector} operations in the
  11380. appropriate places. For example, we wrap every vector creation with an
  11381. \code{inject-vector}.
  11382. \begin{lstlisting}
  11383. (vector |$e_1 \ldots e_n$|)
  11384. |$\Rightarrow$|
  11385. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11386. \end{lstlisting}
  11387. The \code{raw-vector} operator that we introduced in the previous
  11388. section does not get injected.
  11389. \begin{lstlisting}
  11390. (raw-vector |$e_1 \ldots e_n$|)
  11391. |$\Rightarrow$|
  11392. (vector |$e'_1 \ldots e'_n$|)
  11393. \end{lstlisting}
  11394. The \code{vector-proxy} primitive translates as follows.
  11395. \begin{lstlisting}
  11396. (vector-proxy |$e_1~e_2~e_3$|)
  11397. |$\Rightarrow$|
  11398. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11399. \end{lstlisting}
  11400. We translate the vector operations into conditional expressions that
  11401. check whether the value is a proxy and then dispatch to either the
  11402. appropriate proxy vector operation or the regular vector operation.
  11403. For example, the following is the translation for \code{vector-ref}.
  11404. \begin{lstlisting}
  11405. (vector-ref |$e_1$| |$i$|)
  11406. |$\Rightarrow$|
  11407. (let ([|$v~e_1$|])
  11408. (if (proxy? |$v$|)
  11409. (proxy-vector-ref |$v$| |$i$|)
  11410. (vector-ref (project-vector |$v$|) |$i$|)
  11411. \end{lstlisting}
  11412. Note in the case of a real vector, we must apply \code{project-vector}
  11413. before the \code{vector-ref}.
  11414. \section{Reveal Casts}
  11415. \label{sec:reveal-casts-gradual}
  11416. Recall that the \code{reveal-casts} pass
  11417. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11418. \code{Inject} and \code{Project} into lower-level operations. In
  11419. particular, \code{Project} turns into a conditional expression that
  11420. inspects the tag and retrieves the underlying value. Here we need to
  11421. augment the translation of \code{Project} to handle the situation when
  11422. the target type is \code{PVector}. Instead of using
  11423. \code{vector-length} we need to use \code{proxy-vector-length}.
  11424. \begin{lstlisting}
  11425. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11426. |$\Rightarrow$|
  11427. (let |$\itm{tmp}$| |$e'$|
  11428. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11429. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11430. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11431. (exit)))
  11432. \end{lstlisting}
  11433. \section{Closure Conversion}
  11434. \label{sec:closure-conversion-gradual}
  11435. The closure conversion pass only requires one minor adjustment. The
  11436. auxiliary function that translates type annotations needs to be
  11437. updated to handle the \code{PVector} type.
  11438. \section{Explicate Control}
  11439. \label{sec:explicate-control-gradual}
  11440. Update the \code{explicate-control} pass to handle the new primitive
  11441. operations on the \code{PVector} type.
  11442. \section{Select Instructions}
  11443. \label{sec:select-instructions-gradual}
  11444. Recall that the \code{select-instructions} pass is responsible for
  11445. lowering the primitive operations into x86 instructions. So we need
  11446. to translate the new \code{PVector} operations to x86. To do so, the
  11447. first question we need to answer is how will we differentiate the two
  11448. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11449. We need just one bit to accomplish this, and use the bit in position
  11450. $57$ of the 64-bit tag at the front of every vector (see
  11451. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11452. for \code{inject-vector} we leave it that way.
  11453. \begin{lstlisting}
  11454. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11455. |$\Rightarrow$|
  11456. movq |$e'_1$|, |$\itm{lhs'}$|
  11457. \end{lstlisting}
  11458. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11459. \begin{lstlisting}
  11460. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11461. |$\Rightarrow$|
  11462. movq |$e'_1$|, %r11
  11463. movq |$(1 << 57)$|, %rax
  11464. orq 0(%r11), %rax
  11465. movq %rax, 0(%r11)
  11466. movq %r11, |$\itm{lhs'}$|
  11467. \end{lstlisting}
  11468. The \code{proxy?} operation consumes the information so carefully
  11469. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11470. isolates the $57$th bit to tell whether the value is a real vector or
  11471. a proxy.
  11472. \begin{lstlisting}
  11473. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11474. |$\Rightarrow$|
  11475. movq |$e_1'$|, %r11
  11476. movq 0(%r11), %rax
  11477. sarq $57, %rax
  11478. andq $1, %rax
  11479. movq %rax, |$\itm{lhs'}$|
  11480. \end{lstlisting}
  11481. The \code{project-vector} operation is straightforward to translate,
  11482. so we leave it up to the reader.
  11483. Regarding the \code{proxy-vector} operations, the runtime provides
  11484. procedures that implement them (they are recursive functions!) so
  11485. here we simply need to translate these vector operations into the
  11486. appropriate function call. For example, here is the translation for
  11487. \code{proxy-vector-ref}.
  11488. \begin{lstlisting}
  11489. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11490. |$\Rightarrow$|
  11491. movq |$e_1'$|, %rdi
  11492. movq |$e_2'$|, %rsi
  11493. callq proxy_vector_ref
  11494. movq %rax, |$\itm{lhs'}$|
  11495. \end{lstlisting}
  11496. We have another batch of vector operations to deal with, those for the
  11497. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11498. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11499. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11500. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11501. Section~\ref{sec:select-Rany} we selected instructions for these
  11502. operations based on the idea that the underlying value was a real
  11503. vector. But in the current setting, the underlying value is of type
  11504. \code{PVector}. So \code{any-vector-ref} can be translates to
  11505. pseudo-x86 as follows. We begin by projecting the underlying value out
  11506. of the tagged value and then call the \code{proxy\_vector\_ref}
  11507. procedure in the runtime.
  11508. \begin{lstlisting}
  11509. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11510. movq |$\neg 111$|, %rdi
  11511. andq |$e_1'$|, %rdi
  11512. movq |$e_2'$|, %rsi
  11513. callq proxy_vector_ref
  11514. movq %rax, |$\itm{lhs'}$|
  11515. \end{lstlisting}
  11516. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11517. be translated in a similar way.
  11518. \begin{exercise}\normalfont
  11519. Implement a compiler for the gradually-typed \LangGrad{} language by
  11520. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11521. partially-typed test programs. In addition to testing with these
  11522. new programs, also test your compiler on all the tests for \LangLoop{}
  11523. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11524. on the \LangDyn{} programs but you can adapt them by inserting
  11525. a cast to the \code{Any} type around each subexpression
  11526. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11527. you can induce one by wrapping the subexpression \code{e}
  11528. with a call to an un-annotated identity function, like this:
  11529. \code{((lambda (x) x) e)}.
  11530. \end{exercise}
  11531. \begin{figure}[p]
  11532. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11533. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11534. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11535. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11536. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11537. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11538. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11539. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11540. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11541. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11542. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11543. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11544. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11545. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11546. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11547. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11548. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11549. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11550. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11551. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11552. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11553. \path[->,bend right=15] (Rgradual) edge [above] node
  11554. {\ttfamily\footnotesize type-check} (Rgradualp);
  11555. \path[->,bend right=15] (Rgradualp) edge [above] node
  11556. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11557. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11558. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11559. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11560. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11561. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11562. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11563. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11564. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11565. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11566. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11567. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11568. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11569. \path[->,bend left=15] (F1-1) edge [below] node
  11570. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11571. \path[->,bend right=15] (F1-2) edge [above] node
  11572. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11573. \path[->,bend right=15] (F1-3) edge [above] node
  11574. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11575. \path[->,bend right=15] (F1-4) edge [above] node
  11576. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11577. \path[->,bend right=15] (F1-5) edge [right] node
  11578. {\ttfamily\footnotesize explicate-control} (C3-2);
  11579. \path[->,bend left=15] (C3-2) edge [left] node
  11580. {\ttfamily\footnotesize select-instr.} (x86-2);
  11581. \path[->,bend right=15] (x86-2) edge [left] node
  11582. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11583. \path[->,bend right=15] (x86-2-1) edge [below] node
  11584. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11585. \path[->,bend right=15] (x86-2-2) edge [left] node
  11586. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11587. \path[->,bend left=15] (x86-3) edge [above] node
  11588. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11589. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11590. \end{tikzpicture}
  11591. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11592. \label{fig:Rgradual-passes}
  11593. \end{figure}
  11594. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11595. for the compilation of \LangGrad{}.
  11596. \section{Further Reading}
  11597. This chapter just scratches the surface of gradual typing. The basic
  11598. approach described here is missing two key ingredients that one would
  11599. want in a implementation of gradual typing: blame
  11600. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11601. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11602. problem addressed by blame tracking is that when a cast on a
  11603. higher-order value fails, it often does so at a point in the program
  11604. that is far removed from the original cast. Blame tracking is a
  11605. technique for propagating extra information through casts and proxies
  11606. so that when a cast fails, the error message can point back to the
  11607. original location of the cast in the source program.
  11608. The problem addressed by space-efficient casts also relates to
  11609. higher-order casts. It turns out that in partially typed programs, a
  11610. function or vector can flow through very-many casts at runtime. With
  11611. the approach described in this chapter, each cast adds another
  11612. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11613. considerable space, but it also makes the function calls and vector
  11614. operations slow. For example, a partially-typed version of quicksort
  11615. could, in the worst case, build a chain of proxies of length $O(n)$
  11616. around the vector, changing the overall time complexity of the
  11617. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11618. solution to this problem by representing casts using the coercion
  11619. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11620. long chains of proxies by compressing them into a concise normal
  11621. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11622. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11623. the Grift compiler.
  11624. \begin{center}
  11625. \url{https://github.com/Gradual-Typing/Grift}
  11626. \end{center}
  11627. There are also interesting interactions between gradual typing and
  11628. other language features, such as parametetric polymorphism,
  11629. information-flow types, and type inference, to name a few. We
  11630. recommend the reader to the online gradual typing bibliography:
  11631. \begin{center}
  11632. \url{http://samth.github.io/gradual-typing-bib/}
  11633. \end{center}
  11634. % TODO: challenge problem:
  11635. % type analysis and type specialization?
  11636. % coercions?
  11637. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11638. \chapter{Parametric Polymorphism}
  11639. \label{ch:Rpoly}
  11640. \index{subject}{parametric polymorphism}
  11641. \index{subject}{generics}
  11642. This chapter studies the compilation of parametric
  11643. polymorphism\index{subject}{parametric polymorphism}
  11644. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  11645. Racket. Parametric polymorphism enables improved code reuse by
  11646. parameterizing functions and data structures with respect to the types
  11647. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11648. revisits the \code{map-vec} example but this time gives it a more
  11649. fitting type. This \code{map-vec} function is parameterized with
  11650. respect to the element type of the vector. The type of \code{map-vec}
  11651. is the following polymorphic type as specified by the \code{All} and
  11652. the type parameter \code{a}.
  11653. \begin{lstlisting}
  11654. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11655. \end{lstlisting}
  11656. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11657. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11658. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11659. \code{a}, but we could have just as well applied \code{map-vec} to a
  11660. vector of Booleans (and a function on Booleans).
  11661. \begin{figure}[tbp]
  11662. % poly_test_2.rkt
  11663. \begin{lstlisting}
  11664. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11665. (define (map-vec f v)
  11666. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11667. (define (add1 [x : Integer]) : Integer (+ x 1))
  11668. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11669. \end{lstlisting}
  11670. \caption{The \code{map-vec} example using parametric polymorphism.}
  11671. \label{fig:map-vec-poly}
  11672. \end{figure}
  11673. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11674. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11675. syntax. We add a second form for function definitions in which a type
  11676. declaration comes before the \code{define}. In the abstract syntax,
  11677. the return type in the \code{Def} is \code{Any}, but that should be
  11678. ignored in favor of the return type in the type declaration. (The
  11679. \code{Any} comes from using the same parser as in
  11680. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11681. enables the use of an \code{All} type for a function, thereby making
  11682. it polymorphic. The grammar for types is extended to include
  11683. polymorphic types and type variables.
  11684. \begin{figure}[tp]
  11685. \centering
  11686. \fbox{
  11687. \begin{minipage}{0.96\textwidth}
  11688. \small
  11689. \[
  11690. \begin{array}{lcl}
  11691. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11692. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11693. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11694. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11695. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11696. \end{array}
  11697. \]
  11698. \end{minipage}
  11699. }
  11700. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11701. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11702. \label{fig:Rpoly-concrete-syntax}
  11703. \end{figure}
  11704. \begin{figure}[tp]
  11705. \centering
  11706. \fbox{
  11707. \begin{minipage}{0.96\textwidth}
  11708. \small
  11709. \[
  11710. \begin{array}{lcl}
  11711. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11712. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11713. &\mid& \DECL{\Var}{\Type} \\
  11714. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11715. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11716. \end{array}
  11717. \]
  11718. \end{minipage}
  11719. }
  11720. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11721. (Figure~\ref{fig:Rwhile-syntax}).}
  11722. \label{fig:Rpoly-syntax}
  11723. \end{figure}
  11724. By including polymorphic types in the $\Type$ non-terminal we choose
  11725. to make them first-class which has interesting repercussions on the
  11726. compiler. Many languages with polymorphism, such as
  11727. C++~\citep{stroustrup88:_param_types} and Standard
  11728. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11729. it is useful to see an example of first-class polymorphism. In
  11730. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11731. whose parameter is a polymorphic function. The occurrence of a
  11732. polymorphic type underneath a function type is enabled by the normal
  11733. recursive structure of the grammar for $\Type$ and the categorization
  11734. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11735. applies the polymorphic function to a Boolean and to an integer.
  11736. \begin{figure}[tbp]
  11737. \begin{lstlisting}
  11738. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11739. (define (apply-twice f)
  11740. (if (f #t) (f 42) (f 777)))
  11741. (: id (All (a) (a -> a)))
  11742. (define (id x) x)
  11743. (apply-twice id)
  11744. \end{lstlisting}
  11745. \caption{An example illustrating first-class polymorphism.}
  11746. \label{fig:apply-twice}
  11747. \end{figure}
  11748. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11749. three new responsibilities (compared to \LangLoop{}). The type checking of
  11750. function application is extended to handle the case where the operator
  11751. expression is a polymorphic function. In that case the type arguments
  11752. are deduced by matching the type of the parameters with the types of
  11753. the arguments.
  11754. %
  11755. The \code{match-types} auxiliary function carries out this deduction
  11756. by recursively descending through a parameter type \code{pt} and the
  11757. corresponding argument type \code{at}, making sure that they are equal
  11758. except when there is a type parameter on the left (in the parameter
  11759. type). If it's the first time that the type parameter has been
  11760. encountered, then the algorithm deduces an association of the type
  11761. parameter to the corresponding type on the right (in the argument
  11762. type). If it's not the first time that the type parameter has been
  11763. encountered, the algorithm looks up its deduced type and makes sure
  11764. that it is equal to the type on the right.
  11765. %
  11766. Once the type arguments are deduced, the operator expression is
  11767. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11768. type of the operator, but more importantly, records the deduced type
  11769. arguments. The return type of the application is the return type of
  11770. the polymorphic function, but with the type parameters replaced by the
  11771. deduced type arguments, using the \code{subst-type} function.
  11772. The second responsibility of the type checker is extending the
  11773. function \code{type-equal?} to handle the \code{All} type. This is
  11774. not quite a simple as equal on other types, such as function and
  11775. vector types, because two polymorphic types can be syntactically
  11776. different even though they are equivalent types. For example,
  11777. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11778. Two polymorphic types should be considered equal if they differ only
  11779. in the choice of the names of the type parameters. The
  11780. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11781. renames the type parameters of the first type to match the type
  11782. parameters of the second type.
  11783. The third responsibility of the type checker is making sure that only
  11784. defined type variables appear in type annotations. The
  11785. \code{check-well-formed} function defined in
  11786. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11787. sure that each type variable has been defined.
  11788. The output language of the type checker is \LangInst{}, defined in
  11789. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11790. declaration and polymorphic function into a single definition, using
  11791. the \code{Poly} form, to make polymorphic functions more convenient to
  11792. process in next pass of the compiler.
  11793. \begin{figure}[tp]
  11794. \centering
  11795. \fbox{
  11796. \begin{minipage}{0.96\textwidth}
  11797. \small
  11798. \[
  11799. \begin{array}{lcl}
  11800. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11801. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11802. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11803. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11804. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11805. \end{array}
  11806. \]
  11807. \end{minipage}
  11808. }
  11809. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11810. (Figure~\ref{fig:Rwhile-syntax}).}
  11811. \label{fig:Rpoly-prime-syntax}
  11812. \end{figure}
  11813. The output of the type checker on the polymorphic \code{map-vec}
  11814. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11815. \begin{figure}[tbp]
  11816. % poly_test_2.rkt
  11817. \begin{lstlisting}
  11818. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11819. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11820. (define (add1 [x : Integer]) : Integer (+ x 1))
  11821. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11822. (Integer))
  11823. add1 (vector 0 41)) 1)
  11824. \end{lstlisting}
  11825. \caption{Output of the type checker on the \code{map-vec} example.}
  11826. \label{fig:map-vec-type-check}
  11827. \end{figure}
  11828. \begin{figure}[tbp]
  11829. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11830. (define type-check-poly-class
  11831. (class type-check-Rwhile-class
  11832. (super-new)
  11833. (inherit check-type-equal?)
  11834. (define/override (type-check-apply env e1 es)
  11835. (define-values (e^ ty) ((type-check-exp env) e1))
  11836. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11837. ((type-check-exp env) e)))
  11838. (match ty
  11839. [`(,ty^* ... -> ,rt)
  11840. (for ([arg-ty ty*] [param-ty ty^*])
  11841. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11842. (values e^ es^ rt)]
  11843. [`(All ,xs (,tys ... -> ,rt))
  11844. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11845. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11846. (match-types env^^ param-ty arg-ty)))
  11847. (define targs
  11848. (for/list ([x xs])
  11849. (match (dict-ref env^^ x (lambda () #f))
  11850. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11851. x (Apply e1 es))]
  11852. [ty ty])))
  11853. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11854. [else (error 'type-check "expected a function, not ~a" ty)]))
  11855. (define/override ((type-check-exp env) e)
  11856. (match e
  11857. [(Lambda `([,xs : ,Ts] ...) rT body)
  11858. (for ([T Ts]) ((check-well-formed env) T))
  11859. ((check-well-formed env) rT)
  11860. ((super type-check-exp env) e)]
  11861. [(HasType e1 ty)
  11862. ((check-well-formed env) ty)
  11863. ((super type-check-exp env) e)]
  11864. [else ((super type-check-exp env) e)]))
  11865. (define/override ((type-check-def env) d)
  11866. (verbose 'type-check "poly/def" d)
  11867. (match d
  11868. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11869. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11870. (for ([p ps]) ((check-well-formed ts-env) p))
  11871. ((check-well-formed ts-env) rt)
  11872. (define new-env (append ts-env (map cons xs ps) env))
  11873. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11874. (check-type-equal? ty^ rt body)
  11875. (Generic ts (Def f p:t* rt info body^))]
  11876. [else ((super type-check-def env) d)]))
  11877. (define/override (type-check-program p)
  11878. (match p
  11879. [(Program info body)
  11880. (type-check-program (ProgramDefsExp info '() body))]
  11881. [(ProgramDefsExp info ds body)
  11882. (define ds^ (combine-decls-defs ds))
  11883. (define new-env (for/list ([d ds^])
  11884. (cons (def-name d) (fun-def-type d))))
  11885. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11886. (define-values (body^ ty) ((type-check-exp new-env) body))
  11887. (check-type-equal? ty 'Integer body)
  11888. (ProgramDefsExp info ds^^ body^)]))
  11889. ))
  11890. \end{lstlisting}
  11891. \caption{Type checker for the \LangPoly{} language.}
  11892. \label{fig:type-check-Rvar0}
  11893. \end{figure}
  11894. \begin{figure}[tbp]
  11895. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11896. (define/override (type-equal? t1 t2)
  11897. (match* (t1 t2)
  11898. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11899. (define env (map cons xs ys))
  11900. (type-equal? (subst-type env T1) T2)]
  11901. [(other wise)
  11902. (super type-equal? t1 t2)]))
  11903. (define/public (match-types env pt at)
  11904. (match* (pt at)
  11905. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11906. [('Void 'Void) env] [('Any 'Any) env]
  11907. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11908. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11909. (match-types env^ pt1 at1))]
  11910. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11911. (define env^ (match-types env prt art))
  11912. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11913. (match-types env^^ pt1 at1))]
  11914. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11915. (define env^ (append (map cons pxs axs) env))
  11916. (match-types env^ pt1 at1)]
  11917. [((? symbol? x) at)
  11918. (match (dict-ref env x (lambda () #f))
  11919. [#f (error 'type-check "undefined type variable ~a" x)]
  11920. ['Type (cons (cons x at) env)]
  11921. [t^ (check-type-equal? at t^ 'matching) env])]
  11922. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11923. (define/public (subst-type env pt)
  11924. (match pt
  11925. ['Integer 'Integer] ['Boolean 'Boolean]
  11926. ['Void 'Void] ['Any 'Any]
  11927. [`(Vector ,ts ...)
  11928. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11929. [`(,ts ... -> ,rt)
  11930. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11931. [`(All ,xs ,t)
  11932. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11933. [(? symbol? x) (dict-ref env x)]
  11934. [else (error 'type-check "expected a type not ~a" pt)]))
  11935. (define/public (combine-decls-defs ds)
  11936. (match ds
  11937. ['() '()]
  11938. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11939. (unless (equal? name f)
  11940. (error 'type-check "name mismatch, ~a != ~a" name f))
  11941. (match type
  11942. [`(All ,xs (,ps ... -> ,rt))
  11943. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11944. (cons (Generic xs (Def name params^ rt info body))
  11945. (combine-decls-defs ds^))]
  11946. [`(,ps ... -> ,rt)
  11947. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11948. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11949. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11950. [`(,(Def f params rt info body) . ,ds^)
  11951. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11952. \end{lstlisting}
  11953. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11954. \label{fig:type-check-Rvar0-aux}
  11955. \end{figure}
  11956. \begin{figure}[tbp]
  11957. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11958. (define/public ((check-well-formed env) ty)
  11959. (match ty
  11960. ['Integer (void)]
  11961. ['Boolean (void)]
  11962. ['Void (void)]
  11963. [(? symbol? a)
  11964. (match (dict-ref env a (lambda () #f))
  11965. ['Type (void)]
  11966. [else (error 'type-check "undefined type variable ~a" a)])]
  11967. [`(Vector ,ts ...)
  11968. (for ([t ts]) ((check-well-formed env) t))]
  11969. [`(,ts ... -> ,t)
  11970. (for ([t ts]) ((check-well-formed env) t))
  11971. ((check-well-formed env) t)]
  11972. [`(All ,xs ,t)
  11973. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11974. ((check-well-formed env^) t)]
  11975. [else (error 'type-check "unrecognized type ~a" ty)]))
  11976. \end{lstlisting}
  11977. \caption{Well-formed types.}
  11978. \label{fig:well-formed-types}
  11979. \end{figure}
  11980. % TODO: interpreter for R'_10
  11981. \section{Compiling Polymorphism}
  11982. \label{sec:compiling-poly}
  11983. Broadly speaking, there are four approaches to compiling parametric
  11984. polymorphism, which we describe below.
  11985. \begin{description}
  11986. \item[Monomorphization] generates a different version of a polymorphic
  11987. function for each set of type arguments that it is used with,
  11988. producing type-specialized code. This approach results in the most
  11989. efficient code but requires whole-program compilation (no separate
  11990. compilation) and increases code size. For our current purposes
  11991. monomorphization is a non-starter because, with first-class
  11992. polymorphism, it is sometimes not possible to determine which
  11993. generic functions are used with which type arguments during
  11994. compilation. (It can be done at runtime, with just-in-time
  11995. compilation.) This approach is used to compile C++
  11996. templates~\citep{stroustrup88:_param_types} and polymorphic
  11997. functions in NESL~\citep{Blelloch:1993aa} and
  11998. ML~\citep{Weeks:2006aa}.
  11999. \item[Uniform representation] generates one version of each
  12000. polymorphic function but requires all values have a common ``boxed''
  12001. format, such as the tagged values of type \code{Any} in
  12002. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12003. similarly to code in a dynamically typed language (like \LangDyn{}),
  12004. in which primitive operators require their arguments to be projected
  12005. from \code{Any} and their results are injected into \code{Any}. (In
  12006. object-oriented languages, the projection is accomplished via
  12007. virtual method dispatch.) The uniform representation approach is
  12008. compatible with separate compilation and with first-class
  12009. polymorphism. However, it produces the least-efficient code because
  12010. it introduces overhead in the entire program, including
  12011. non-polymorphic code. This approach is used in implementations of
  12012. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12013. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12014. Java~\citep{Bracha:1998fk}.
  12015. \item[Mixed representation] generates one version of each polymorphic
  12016. function, using a boxed representation for type
  12017. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12018. and conversions are performed at the boundaries between monomorphic
  12019. and polymorphic (e.g. when a polymorphic function is instantiated
  12020. and called). This approach is compatible with separate compilation
  12021. and first-class polymorphism and maintains the efficiency of
  12022. monomorphic code. The tradeoff is increased overhead at the boundary
  12023. between monomorphic and polymorphic code. This approach is used in
  12024. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12025. Java 5 with the addition of autoboxing.
  12026. \item[Type passing] uses the unboxed representation in both
  12027. monomorphic and polymorphic code. Each polymorphic function is
  12028. compiled to a single function with extra parameters that describe
  12029. the type arguments. The type information is used by the generated
  12030. code to know how to access the unboxed values at runtime. This
  12031. approach is used in implementation of the Napier88
  12032. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12033. passing is compatible with separate compilation and first-class
  12034. polymorphism and maintains the efficiency for monomorphic
  12035. code. There is runtime overhead in polymorphic code from dispatching
  12036. on type information.
  12037. \end{description}
  12038. In this chapter we use the mixed representation approach, partly
  12039. because of its favorable attributes, and partly because it is
  12040. straightforward to implement using the tools that we have already
  12041. built to support gradual typing. To compile polymorphic functions, we
  12042. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12043. \LangCast{}.
  12044. \section{Erase Types}
  12045. \label{sec:erase-types}
  12046. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12047. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12048. shows the output of the \code{erase-types} pass on the polymorphic
  12049. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12050. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12051. \code{All} types are removed from the type of \code{map-vec}.
  12052. \begin{figure}[tbp]
  12053. \begin{lstlisting}
  12054. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12055. : (Vector Any Any)
  12056. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12057. (define (add1 [x : Integer]) : Integer (+ x 1))
  12058. (vector-ref ((cast map-vec
  12059. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12060. ((Integer -> Integer) (Vector Integer Integer)
  12061. -> (Vector Integer Integer)))
  12062. add1 (vector 0 41)) 1)
  12063. \end{lstlisting}
  12064. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12065. \label{fig:map-vec-erase}
  12066. \end{figure}
  12067. This process of type erasure creates a challenge at points of
  12068. instantiation. For example, consider the instantiation of
  12069. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12070. The type of \code{map-vec} is
  12071. \begin{lstlisting}
  12072. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12073. \end{lstlisting}
  12074. and it is instantiated to
  12075. \begin{lstlisting}
  12076. ((Integer -> Integer) (Vector Integer Integer)
  12077. -> (Vector Integer Integer))
  12078. \end{lstlisting}
  12079. After erasure, the type of \code{map-vec} is
  12080. \begin{lstlisting}
  12081. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12082. \end{lstlisting}
  12083. but we need to convert it to the instantiated type. This is easy to
  12084. do in the target language \LangCast{} with a single \code{cast}. In
  12085. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12086. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12087. the instantiated type. The source and target type of a cast must be
  12088. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12089. because both the source and target are obtained from the same
  12090. polymorphic type of \code{map-vec}, replacing the type parameters with
  12091. \code{Any} in the former and with the deduced type arguments in the
  12092. later. (Recall that the \code{Any} type is consistent with any type.)
  12093. To implement the \code{erase-types} pass, we recommend defining a
  12094. recursive auxiliary function named \code{erase-type} that applies the
  12095. following two transformations. It replaces type variables with
  12096. \code{Any}
  12097. \begin{lstlisting}
  12098. |$x$|
  12099. |$\Rightarrow$|
  12100. Any
  12101. \end{lstlisting}
  12102. and it removes the polymorphic \code{All} types.
  12103. \begin{lstlisting}
  12104. (All |$xs$| |$T_1$|)
  12105. |$\Rightarrow$|
  12106. |$T'_1$|
  12107. \end{lstlisting}
  12108. Apply the \code{erase-type} function to all of the type annotations in
  12109. the program.
  12110. Regarding the translation of expressions, the case for \code{Inst} is
  12111. the interesting one. We translate it into a \code{Cast}, as shown
  12112. below. The type of the subexpression $e$ is the polymorphic type
  12113. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12114. $T$, the type $T'$. The target type $T''$ is the result of
  12115. substituting the arguments types $ts$ for the type parameters $xs$ in
  12116. $T$ followed by doing type erasure.
  12117. \begin{lstlisting}
  12118. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12119. |$\Rightarrow$|
  12120. (Cast |$e'$| |$T'$| |$T''$|)
  12121. \end{lstlisting}
  12122. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12123. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12124. Finally, each polymorphic function is translated to a regular
  12125. functions in which type erasure has been applied to all the type
  12126. annotations and the body.
  12127. \begin{lstlisting}
  12128. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12129. |$\Rightarrow$|
  12130. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12131. \end{lstlisting}
  12132. \begin{exercise}\normalfont
  12133. Implement a compiler for the polymorphic language \LangPoly{} by
  12134. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12135. programs that use polymorphic functions. Some of them should make
  12136. use of first-class polymorphism.
  12137. \end{exercise}
  12138. \begin{figure}[p]
  12139. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12140. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12141. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12142. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12143. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12144. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12145. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12146. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12147. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12148. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12149. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12150. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12151. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12152. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12153. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12154. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12155. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12156. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12157. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12158. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12159. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12160. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12161. \path[->,bend right=15] (Rpoly) edge [above] node
  12162. {\ttfamily\footnotesize type-check} (Rpolyp);
  12163. \path[->,bend right=15] (Rpolyp) edge [above] node
  12164. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12165. \path[->,bend right=15] (Rgradualp) edge [above] node
  12166. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12167. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12168. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12169. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12170. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12171. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12172. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12173. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12174. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12175. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12176. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12177. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12178. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12179. \path[->,bend left=15] (F1-1) edge [below] node
  12180. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12181. \path[->,bend right=15] (F1-2) edge [above] node
  12182. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12183. \path[->,bend right=15] (F1-3) edge [above] node
  12184. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12185. \path[->,bend right=15] (F1-4) edge [above] node
  12186. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12187. \path[->,bend right=15] (F1-5) edge [right] node
  12188. {\ttfamily\footnotesize explicate-control} (C3-2);
  12189. \path[->,bend left=15] (C3-2) edge [left] node
  12190. {\ttfamily\footnotesize select-instr.} (x86-2);
  12191. \path[->,bend right=15] (x86-2) edge [left] node
  12192. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12193. \path[->,bend right=15] (x86-2-1) edge [below] node
  12194. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12195. \path[->,bend right=15] (x86-2-2) edge [left] node
  12196. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12197. \path[->,bend left=15] (x86-3) edge [above] node
  12198. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12199. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12200. \end{tikzpicture}
  12201. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12202. \label{fig:Rpoly-passes}
  12203. \end{figure}
  12204. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12205. for the compilation of \LangPoly{}.
  12206. % TODO: challenge problem: specialization of instantiations
  12207. % Further Reading
  12208. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12209. \clearpage
  12210. \appendix
  12211. \chapter{Appendix}
  12212. \section{Interpreters}
  12213. \label{appendix:interp}
  12214. \index{subject}{interpreter}
  12215. We provide interpreters for each of the source languages \LangInt{},
  12216. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12217. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12218. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12219. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12220. and x86 are in the \key{interp.rkt} file.
  12221. \section{Utility Functions}
  12222. \label{appendix:utilities}
  12223. The utility functions described in this section are in the
  12224. \key{utilities.rkt} file of the support code.
  12225. \paragraph{\code{interp-tests}}
  12226. The \key{interp-tests} function runs the compiler passes and the
  12227. interpreters on each of the specified tests to check whether each pass
  12228. is correct. The \key{interp-tests} function has the following
  12229. parameters:
  12230. \begin{description}
  12231. \item[name (a string)] a name to identify the compiler,
  12232. \item[typechecker] a function of exactly one argument that either
  12233. raises an error using the \code{error} function when it encounters a
  12234. type error, or returns \code{\#f} when it encounters a type
  12235. error. If there is no type error, the type checker returns the
  12236. program.
  12237. \item[passes] a list with one entry per pass. An entry is a list with
  12238. four things:
  12239. \begin{enumerate}
  12240. \item a string giving the name of the pass,
  12241. \item the function that implements the pass (a translator from AST
  12242. to AST),
  12243. \item a function that implements the interpreter (a function from
  12244. AST to result value) for the output language,
  12245. \item and a type checker for the output language. Type checkers for
  12246. the $R$ and $C$ languages are provided in the support code. For
  12247. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12248. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12249. type checker entry is optional. The support code does not provide
  12250. type checkers for the x86 languages.
  12251. \end{enumerate}
  12252. \item[source-interp] an interpreter for the source language. The
  12253. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12254. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12255. \item[tests] a list of test numbers that specifies which tests to
  12256. run. (see below)
  12257. \end{description}
  12258. %
  12259. The \key{interp-tests} function assumes that the subdirectory
  12260. \key{tests} has a collection of Racket programs whose names all start
  12261. with the family name, followed by an underscore and then the test
  12262. number, ending with the file extension \key{.rkt}. Also, for each test
  12263. program that calls \code{read} one or more times, there is a file with
  12264. the same name except that the file extension is \key{.in} that
  12265. provides the input for the Racket program. If the test program is
  12266. expected to fail type checking, then there should be an empty file of
  12267. the same name but with extension \key{.tyerr}.
  12268. \paragraph{\code{compiler-tests}}
  12269. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12270. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12271. machine code and checks that the output is $42$. The parameters to the
  12272. \code{compiler-tests} function are similar to those of the
  12273. \code{interp-tests} function, and consist of
  12274. \begin{itemize}
  12275. \item a compiler name (a string),
  12276. \item a type checker,
  12277. \item description of the passes,
  12278. \item name of a test-family, and
  12279. \item a list of test numbers.
  12280. \end{itemize}
  12281. \paragraph{\code{compile-file}}
  12282. takes a description of the compiler passes (see the comment for
  12283. \key{interp-tests}) and returns a function that, given a program file
  12284. name (a string ending in \key{.rkt}), applies all of the passes and
  12285. writes the output to a file whose name is the same as the program file
  12286. name but with \key{.rkt} replaced with \key{.s}.
  12287. \paragraph{\code{read-program}}
  12288. takes a file path and parses that file (it must be a Racket program)
  12289. into an abstract syntax tree.
  12290. \paragraph{\code{parse-program}}
  12291. takes an S-expression representation of an abstract syntax tree and converts it into
  12292. the struct-based representation.
  12293. \paragraph{\code{assert}}
  12294. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12295. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12296. \paragraph{\code{lookup}}
  12297. % remove discussion of lookup? -Jeremy
  12298. takes a key and an alist, and returns the first value that is
  12299. associated with the given key, if there is one. If not, an error is
  12300. triggered. The alist may contain both immutable pairs (built with
  12301. \key{cons}) and mutable pairs (built with \key{mcons}).
  12302. %The \key{map2} function ...
  12303. \section{x86 Instruction Set Quick-Reference}
  12304. \label{sec:x86-quick-reference}
  12305. \index{subject}{x86}
  12306. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12307. do. We write $A \to B$ to mean that the value of $A$ is written into
  12308. location $B$. Address offsets are given in bytes. The instruction
  12309. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12310. registers (such as \code{\%rax}), or memory references (such as
  12311. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12312. reference per instruction. Other operands must be immediates or
  12313. registers.
  12314. \begin{table}[tbp]
  12315. \centering
  12316. \begin{tabular}{l|l}
  12317. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12318. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12319. \texttt{negq} $A$ & $- A \to A$ \\
  12320. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12321. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12322. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12323. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12324. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12325. \texttt{retq} & Pops the return address and jumps to it \\
  12326. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12327. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12328. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12329. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12330. be an immediate) \\
  12331. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12332. matches the condition code of the instruction, otherwise go to the
  12333. next instructions. The condition codes are \key{e} for ``equal'',
  12334. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12335. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12336. \texttt{jl} $L$ & \\
  12337. \texttt{jle} $L$ & \\
  12338. \texttt{jg} $L$ & \\
  12339. \texttt{jge} $L$ & \\
  12340. \texttt{jmp} $L$ & Jump to label $L$ \\
  12341. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12342. \texttt{movzbq} $A$, $B$ &
  12343. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12344. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12345. and the extra bytes of $B$ are set to zero.} \\
  12346. & \\
  12347. & \\
  12348. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12349. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12350. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12351. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12352. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12353. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12354. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12355. description of the condition codes. $A$ must be a single byte register
  12356. (e.g., \texttt{al} or \texttt{cl}).} \\
  12357. \texttt{setl} $A$ & \\
  12358. \texttt{setle} $A$ & \\
  12359. \texttt{setg} $A$ & \\
  12360. \texttt{setge} $A$ &
  12361. \end{tabular}
  12362. \vspace{5pt}
  12363. \caption{Quick-reference for the x86 instructions used in this book.}
  12364. \label{tab:x86-instr}
  12365. \end{table}
  12366. \cleardoublepage
  12367. \section{Concrete Syntax for Intermediate Languages}
  12368. The concrete syntax of \LangAny{} is defined in
  12369. Figure~\ref{fig:Rany-concrete-syntax}.
  12370. \begin{figure}[tp]
  12371. \centering
  12372. \fbox{
  12373. \begin{minipage}{0.97\textwidth}\small
  12374. \[
  12375. \begin{array}{lcl}
  12376. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12377. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12378. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12379. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12380. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12381. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12382. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12383. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12384. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12385. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12386. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12387. \mid \LP\key{void?}\;\Exp\RP \\
  12388. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12389. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12390. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  12391. \end{array}
  12392. \]
  12393. \end{minipage}
  12394. }
  12395. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12396. (Figure~\ref{fig:Rlam-syntax}).}
  12397. \label{fig:Rany-concrete-syntax}
  12398. \end{figure}
  12399. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12400. defined in Figures~\ref{fig:c0-concrete-syntax},
  12401. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12402. and \ref{fig:c3-concrete-syntax}, respectively.
  12403. \begin{figure}[tbp]
  12404. \fbox{
  12405. \begin{minipage}{0.96\textwidth}
  12406. \[
  12407. \begin{array}{lcl}
  12408. \Atm &::=& \Int \mid \Var \\
  12409. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12410. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12411. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12412. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12413. \end{array}
  12414. \]
  12415. \end{minipage}
  12416. }
  12417. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12418. \label{fig:c0-concrete-syntax}
  12419. \end{figure}
  12420. \begin{figure}[tbp]
  12421. \fbox{
  12422. \begin{minipage}{0.96\textwidth}
  12423. \small
  12424. \[
  12425. \begin{array}{lcl}
  12426. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12427. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12428. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12429. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12430. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12431. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12432. \mid \key{goto}~\itm{label}\key{;}\\
  12433. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12434. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12435. \end{array}
  12436. \]
  12437. \end{minipage}
  12438. }
  12439. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12440. \label{fig:c1-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} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12450. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12451. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12452. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12453. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12454. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12455. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12456. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12457. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12458. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12459. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12460. \end{array}
  12461. \]
  12462. \end{minipage}
  12463. }
  12464. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12465. \label{fig:c2-concrete-syntax}
  12466. \end{figure}
  12467. \begin{figure}[tp]
  12468. \fbox{
  12469. \begin{minipage}{0.96\textwidth}
  12470. \small
  12471. \[
  12472. \begin{array}{lcl}
  12473. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12474. \\
  12475. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12476. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12477. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12478. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12479. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12480. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12481. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12482. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12483. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12484. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12485. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12486. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12487. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12488. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12489. \LangCFunM{} & ::= & \Def\ldots
  12490. \end{array}
  12491. \]
  12492. \end{minipage}
  12493. }
  12494. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12495. \label{fig:c3-concrete-syntax}
  12496. \end{figure}
  12497. \backmatter
  12498. \addtocontents{toc}{\vspace{11pt}}
  12499. %% \addtocontents{toc}{\vspace{11pt}}
  12500. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  12501. \nocite{*}\let\bibname\refname
  12502. \addcontentsline{toc}{fmbm}{\refname}
  12503. \printbibliography
  12504. \printindex{authors}{Author Index}
  12505. \printindex{subject}{Subject Index}
  12506. \end{document}