book.tex 510 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM!, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses on programming languages by Professor Daniel
  148. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, he returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Professor Dybvig continued
  159. development of Chez Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Friedman's ideas was to split the compiler into many small
  163. ``passes'' so that the code for each pass would be easy to understood
  164. in isolation. In contrast, most compilers of the time were organized
  165. into only a few monolithic passes for reasons of compile-time
  166. efficiency. Another idea, called ``the game'', was to test the code
  167. generated by each pass on interpreters for each intermediate language,
  168. thereby helping to pinpoint errors in individual passes.
  169. %
  170. Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  171. Keep, developed infrastructure to support this approach and evolved
  172. the course, first to use smaller micro-passes and then into even
  173. smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  174. in this compiler course in the early 2000's as part of my
  175. Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  176. course immensely!
  177. During that time, another graduate student named Abdulaziz Ghuloum
  178. observed that the front-to-back organization of the course made it
  179. difficult for students to understand the rationale for the compiler
  180. design. Ghuloum proposed an incremental approach in which the students
  181. start by implementing a complete compiler for a very small subset of
  182. the language. In each subsequent stage they add a feature to the
  183. language and then add or modify passes to handle the new
  184. feature~\citep{Ghuloum:2006bh}. In this way, the students see how the
  185. language features motivate aspects of the compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}.
  190. %% Python and Scheme are quite different
  191. %% on the surface but there is a large overlap in the compiler techniques
  192. %% required for the two languages. Thus, I was able to teach much of the
  193. %% same content from the Indiana compiler course.
  194. I very much enjoyed teaching the course organized in this way, and
  195. even better, many of the students learned a lot and got excited about
  196. compilers.
  197. I returned to Indiana University in 2013. In my absence the compiler
  198. course had switched from the front-to-back organization to a
  199. back-to-front~\citep{Dybvig:2010aa}. While that organization also works
  200. well, I prefer the incremental approach and started porting and
  201. adapting the structure of the Colorado course back into the land of
  202. Scheme. In the meantime Indiana University had moved on from Scheme to
  203. Racket~\citep{plt-tr}, so the course is now about compiling a subset
  204. of Racket (and Typed Racket) to the x86 assembly language.
  205. This is the textbook for the incremental version of the compiler
  206. course at Indiana University (Spring 2016 - present). With this book
  207. I hope to make the Indiana compiler course available to people that
  208. have not had the chance to study compilers at Indiana University.
  209. %% I have captured what
  210. %% I think are the most important topics from \cite{Dybvig:2010aa} but
  211. %% have omitted topics that are less interesting conceptually. I have
  212. %% also made simplifications to reduce complexity. In this way, this
  213. %% book leans more towards pedagogy than towards the efficiency of the
  214. %% generated code. Also, the book differs in places where we I the
  215. %% opportunity to make the topics more fun, such as in relating register
  216. %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  217. \section*{Prerequisites}
  218. The material in this book is challenging but rewarding. It is meant to
  219. prepare students for a lifelong career in programming languages.
  220. The book uses the Racket language both for the implementation of the
  221. compiler and for the language that is compiled, so a student should be
  222. proficient with Racket or Scheme prior to reading this book. There are
  223. many excellent resources for learning Scheme and
  224. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  225. It is helpful but not necessary for the student to have prior exposure
  226. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  227. from a computer systems
  228. course~\citep{Bryant:2010aa}. This book introduces the
  229. parts of x86-64 assembly language that are needed.
  230. %
  231. We follow the System V calling
  232. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  233. assembly code that we generate will work properly with our runtime
  234. system (written in C) when it is compiled using the GNU C compiler
  235. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  236. adjustments are needed for MacOS which we note as they arise.)
  237. %
  238. The GNU C compiler, when running on the Microsoft Windows operating
  239. system, follows the Microsoft x64 calling
  240. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  241. code that we generate will \emph{not} work properly with our runtime
  242. system on Windows. One option to consider for using a Windows computer
  243. is to run a virtual machine with Linux as the guest operating system.
  244. %\section*{Structure of book}
  245. % You might want to add short description about each chapter in this book.
  246. %\section*{About the companion website}
  247. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  248. %\begin{itemize}
  249. % \item A link to (freely downlodable) latest version of this document.
  250. % \item Link to download LaTeX source for this document.
  251. % \item Miscellaneous material (e.g. suggested readings etc).
  252. %\end{itemize}
  253. \section*{Acknowledgments}
  254. Many people have contributed to the ideas, techniques, and
  255. organization of this book and have taught courses based on it. Many
  256. of the compiler design decisions in this book are drawn from the
  257. assignment descriptions of \cite{Dybvig:2010aa}. We also would like
  258. to thank John Clements, Bor-Yuh Evan Chang, Daniel P. Friedman, Ronald
  259. Garcia, Abdulaziz Ghuloum, Jay McCarthy, Nate Nystrom, Dipanwita
  260. Sarkar, Oscar Waddell, and Michael Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  276. syntax tree}\index{AST}\index{program}\index{parse} The translation
  277. from concrete syntax to abstract syntax is a process called
  278. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  279. implementation of parsing in this book. A parser is provided in the
  280. supporting materials for translating from concrete to abstract syntax.
  281. ASTs can be represented in many different ways inside the compiler,
  282. depending on the programming language used to write the compiler.
  283. %
  284. We use Racket's
  285. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  286. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  287. define the abstract syntax of programming languages
  288. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  289. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  290. recursive functions to construct and deconstruct ASTs
  291. (Section~\ref{sec:recursion}). This chapter provides an brief
  292. introduction to these ideas. \index{struct}
  293. \section{Abstract Syntax Trees and Racket Structures}
  294. \label{sec:ast}
  295. Compilers use abstract syntax trees to represent programs because they
  296. often need to ask questions like: for a given part of a program, what
  297. kind of language feature is it? What are its sub-parts? Consider the
  298. program on the left and its AST on the right. This program is an
  299. addition operation and it has two sub-parts, a read operation and a
  300. negation. The negation has another sub-part, the integer constant
  301. \code{8}. By using a tree to represent the program, we can easily
  302. follow the links to go from one part of a program to its sub-parts.
  303. \begin{center}
  304. \begin{minipage}{0.4\textwidth}
  305. \begin{lstlisting}
  306. (+ (read) (- 8))
  307. \end{lstlisting}
  308. \end{minipage}
  309. \begin{minipage}{0.4\textwidth}
  310. \begin{equation}
  311. \begin{tikzpicture}
  312. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  313. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  314. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  315. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  316. \draw[->] (plus) to (read);
  317. \draw[->] (plus) to (minus);
  318. \draw[->] (minus) to (8);
  319. \end{tikzpicture}
  320. \label{eq:arith-prog}
  321. \end{equation}
  322. \end{minipage}
  323. \end{center}
  324. We use the standard terminology for trees to describe ASTs: each
  325. circle above is called a \emph{node}. The arrows connect a node to its
  326. \emph{children} (which are also nodes). The top-most node is the
  327. \emph{root}. Every node except for the root has a \emph{parent} (the
  328. node it is the child of). If a node has no children, it is a
  329. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  330. \index{node}
  331. \index{children}
  332. \index{root}
  333. \index{parent}
  334. \index{leaf}
  335. \index{internal node}
  336. %% Recall that an \emph{symbolic expression} (S-expression) is either
  337. %% \begin{enumerate}
  338. %% \item an atom, or
  339. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  340. %% where $e_1$ and $e_2$ are each an S-expression.
  341. %% \end{enumerate}
  342. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  343. %% null value \code{'()}, etc. We can create an S-expression in Racket
  344. %% simply by writing a backquote (called a quasi-quote in Racket)
  345. %% followed by the textual representation of the S-expression. It is
  346. %% quite common to use S-expressions to represent a list, such as $a, b
  347. %% ,c$ in the following way:
  348. %% \begin{lstlisting}
  349. %% `(a . (b . (c . ())))
  350. %% \end{lstlisting}
  351. %% Each element of the list is in the first slot of a pair, and the
  352. %% second slot is either the rest of the list or the null value, to mark
  353. %% the end of the list. Such lists are so common that Racket provides
  354. %% special notation for them that removes the need for the periods
  355. %% and so many parenthesis:
  356. %% \begin{lstlisting}
  357. %% `(a b c)
  358. %% \end{lstlisting}
  359. %% The following expression creates an S-expression that represents AST
  360. %% \eqref{eq:arith-prog}.
  361. %% \begin{lstlisting}
  362. %% `(+ (read) (- 8))
  363. %% \end{lstlisting}
  364. %% When using S-expressions to represent ASTs, the convention is to
  365. %% represent each AST node as a list and to put the operation symbol at
  366. %% the front of the list. The rest of the list contains the children. So
  367. %% in the above case, the root AST node has operation \code{`+} and its
  368. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  369. %% diagram \eqref{eq:arith-prog}.
  370. %% To build larger S-expressions one often needs to splice together
  371. %% several smaller S-expressions. Racket provides the comma operator to
  372. %% splice an S-expression into a larger one. For example, instead of
  373. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  374. %% we could have first created an S-expression for AST
  375. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  376. %% S-expression.
  377. %% \begin{lstlisting}
  378. %% (define ast1.4 `(- 8))
  379. %% (define ast1.1 `(+ (read) ,ast1.4))
  380. %% \end{lstlisting}
  381. %% In general, the Racket expression that follows the comma (splice)
  382. %% can be any expression that produces an S-expression.
  383. We define a Racket \code{struct} for each kind of node. For this
  384. chapter we require just two kinds of nodes: one for integer constants
  385. and one for primitive operations. The following is the \code{struct}
  386. definition for integer constants.
  387. \begin{lstlisting}
  388. (struct Int (value))
  389. \end{lstlisting}
  390. An integer node includes just one thing: the integer value.
  391. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  392. \begin{lstlisting}
  393. (define eight (Int 8))
  394. \end{lstlisting}
  395. We say that the value created by \code{(Int 8)} is an
  396. \emph{instance} of the \code{Int} structure.
  397. The following is the \code{struct} definition for primitives operations.
  398. \begin{lstlisting}
  399. (struct Prim (op args))
  400. \end{lstlisting}
  401. A primitive operation node includes an operator symbol \code{op}
  402. and a list of children \code{args}. For example, to create
  403. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  404. \begin{lstlisting}
  405. (define neg-eight (Prim '- (list eight)))
  406. \end{lstlisting}
  407. Primitive operations may have zero or more children. The \code{read}
  408. operator has zero children:
  409. \begin{lstlisting}
  410. (define rd (Prim 'read '()))
  411. \end{lstlisting}
  412. whereas the addition operator has two children:
  413. \begin{lstlisting}
  414. (define ast1.1 (Prim '+ (list rd neg-eight)))
  415. \end{lstlisting}
  416. We have made a design choice regarding the \code{Prim} structure.
  417. Instead of using one structure for many different operations
  418. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  419. structure for each operation, as follows.
  420. \begin{lstlisting}
  421. (struct Read ())
  422. (struct Add (left right))
  423. (struct Neg (value))
  424. \end{lstlisting}
  425. The reason we choose to use just one structure is that in many parts
  426. of the compiler the code for the different primitive operators is the
  427. same, so we might as well just write that code once, which is enabled
  428. by using a single structure.
  429. When compiling a program such as \eqref{eq:arith-prog}, we need to
  430. know that the operation associated with the root node is addition and
  431. we need to be able to access its two children. Racket provides pattern
  432. matching to support these kinds of queries, as we see in
  433. Section~\ref{sec:pattern-matching}.
  434. In this book, we often write down the concrete syntax of a program
  435. even when we really have in mind the AST because the concrete syntax
  436. is more concise. We recommend that, in your mind, you always think of
  437. programs as abstract syntax trees.
  438. \section{Grammars}
  439. \label{sec:grammar}
  440. \index{integer}
  441. \index{literal}
  442. \index{constant}
  443. A programming language can be thought of as a \emph{set} of programs.
  444. The set is typically infinite (one can always create larger and larger
  445. programs), so one cannot simply describe a language by listing all of
  446. the programs in the language. Instead we write down a set of rules, a
  447. \emph{grammar}, for building programs. Grammars are often used to
  448. define the concrete syntax of a language, but they can also be used to
  449. describe the abstract syntax. We write our rules in a variant of
  450. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  451. \index{Backus-Naur Form}\index{BNF}
  452. As an example, we describe a small language, named \LangInt{}, that consists of
  453. integers and arithmetic operations.
  454. \index{grammar}
  455. The first grammar rule for the abstract syntax of \LangInt{} says that an
  456. instance of the \code{Int} structure is an expression:
  457. \begin{equation}
  458. \Exp ::= \INT{\Int} \label{eq:arith-int}
  459. \end{equation}
  460. %
  461. Each rule has a left-hand-side and a right-hand-side. The way to read
  462. a rule is that if you have an AST node that matches the
  463. right-hand-side, then you can categorize it according to the
  464. left-hand-side.
  465. %
  466. A name such as $\Exp$ that is defined by the grammar rules is a
  467. \emph{non-terminal}. \index{non-terminal}
  468. %
  469. The name $\Int$ is a also a non-terminal, but instead of defining it
  470. with a grammar rule, we define it with the following explanation. We
  471. make the simplifying design decision that all of the languages in this
  472. book only handle machine-representable integers. On most modern
  473. machines this corresponds to integers represented with 64-bits, i.e.,
  474. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  475. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  476. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  477. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  478. that the sequence of decimals represent an integer in range $-2^{62}$
  479. to $2^{62}-1$.
  480. The second grammar rule is the \texttt{read} operation that receives
  481. an input integer from the user of the program.
  482. \begin{equation}
  483. \Exp ::= \READ{} \label{eq:arith-read}
  484. \end{equation}
  485. The third rule says that, given an $\Exp$ node, the negation of that
  486. node is also an $\Exp$.
  487. \begin{equation}
  488. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  489. \end{equation}
  490. Symbols in typewriter font such as \key{-} and \key{read} are
  491. \emph{terminal} symbols and must literally appear in the program for
  492. the rule to be applicable.
  493. \index{terminal}
  494. We can apply these rules to categorize the ASTs that are in the
  495. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  496. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  497. following AST is an $\Exp$.
  498. \begin{center}
  499. \begin{minipage}{0.4\textwidth}
  500. \begin{lstlisting}
  501. (Prim '- (list (Int 8)))
  502. \end{lstlisting}
  503. \end{minipage}
  504. \begin{minipage}{0.25\textwidth}
  505. \begin{equation}
  506. \begin{tikzpicture}
  507. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  508. \node[draw, circle] (8) at (0, -1.2) {$8$};
  509. \draw[->] (minus) to (8);
  510. \end{tikzpicture}
  511. \label{eq:arith-neg8}
  512. \end{equation}
  513. \end{minipage}
  514. \end{center}
  515. The next grammar rule is for addition expressions:
  516. \begin{equation}
  517. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  518. \end{equation}
  519. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  520. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  521. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  522. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  523. to show that
  524. \begin{lstlisting}
  525. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  526. \end{lstlisting}
  527. is an $\Exp$ in the \LangInt{} language.
  528. If you have an AST for which the above rules do not apply, then the
  529. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  530. is not in \LangInt{} because there are no rules for \code{+} with only one
  531. argument, nor for \key{-} with two arguments. Whenever we define a
  532. language with a grammar, the language only includes those programs
  533. that are justified by the rules.
  534. The last grammar rule for \LangInt{} states that there is a \code{Program}
  535. node to mark the top of the whole program:
  536. \[
  537. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  538. \]
  539. The \code{Program} structure is defined as follows
  540. \begin{lstlisting}
  541. (struct Program (info body))
  542. \end{lstlisting}
  543. where \code{body} is an expression. In later chapters, the \code{info}
  544. part will be used to store auxiliary information but for now it is
  545. just the empty list.
  546. It is common to have many grammar rules with the same left-hand side
  547. but different right-hand sides, such as the rules for $\Exp$ in the
  548. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  549. combine several right-hand-sides into a single rule.
  550. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  551. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  552. defined in Figure~\ref{fig:r0-concrete-syntax}.
  553. The \code{read-program} function provided in \code{utilities.rkt} of
  554. the support materials reads a program in from a file (the sequence of
  555. characters in the concrete syntax of Racket) and parses it into an
  556. abstract syntax tree. See the description of \code{read-program} in
  557. Appendix~\ref{appendix:utilities} for more details.
  558. \begin{figure}[tp]
  559. \fbox{
  560. \begin{minipage}{0.96\textwidth}
  561. \[
  562. \begin{array}{rcl}
  563. \begin{array}{rcl}
  564. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  565. \LangInt{} &::=& \Exp
  566. \end{array}
  567. \end{array}
  568. \]
  569. \end{minipage}
  570. }
  571. \caption{The concrete syntax of \LangInt{}.}
  572. \label{fig:r0-concrete-syntax}
  573. \end{figure}
  574. \begin{figure}[tp]
  575. \fbox{
  576. \begin{minipage}{0.96\textwidth}
  577. \[
  578. \begin{array}{rcl}
  579. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  580. &\mid& \ADD{\Exp}{\Exp} \\
  581. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  582. \end{array}
  583. \]
  584. \end{minipage}
  585. }
  586. \caption{The abstract syntax of \LangInt{}.}
  587. \label{fig:r0-syntax}
  588. \end{figure}
  589. \section{Pattern Matching}
  590. \label{sec:pattern-matching}
  591. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  592. the parts of an AST node. Racket provides the \texttt{match} form to
  593. access the parts of a structure. Consider the following example and
  594. the output on the right. \index{match} \index{pattern matching}
  595. \begin{center}
  596. \begin{minipage}{0.5\textwidth}
  597. \begin{lstlisting}
  598. (match ast1.1
  599. [(Prim op (list child1 child2))
  600. (print op)])
  601. \end{lstlisting}
  602. \end{minipage}
  603. \vrule
  604. \begin{minipage}{0.25\textwidth}
  605. \begin{lstlisting}
  606. '+
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. In the above example, the \texttt{match} form takes an AST
  611. \eqref{eq:arith-prog} and binds its parts to the three pattern
  612. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  613. prints out the operator. In general, a match clause consists of a
  614. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  615. recursively defined to be either a pattern variable, a structure name
  616. followed by a pattern for each of the structure's arguments, or an
  617. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  618. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  619. and Chapter 9 of The Racket
  620. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  621. for a complete description of \code{match}.)
  622. %
  623. The body of a match clause may contain arbitrary Racket code. The
  624. pattern variables can be used in the scope of the body, such as
  625. \code{op} in \code{(print op)}.
  626. A \code{match} form may contain several clauses, as in the following
  627. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  628. the AST. The \code{match} proceeds through the clauses in order,
  629. checking whether the pattern can match the input AST. The body of the
  630. first clause that matches is executed. The output of \code{leaf?} for
  631. several ASTs is shown on the right.
  632. \begin{center}
  633. \begin{minipage}{0.6\textwidth}
  634. \begin{lstlisting}
  635. (define (leaf? arith)
  636. (match arith
  637. [(Int n) #t]
  638. [(Prim 'read '()) #t]
  639. [(Prim '- (list e1)) #f]
  640. [(Prim '+ (list e1 e2)) #f]))
  641. (leaf? (Prim 'read '()))
  642. (leaf? (Prim '- (list (Int 8))))
  643. (leaf? (Int 8))
  644. \end{lstlisting}
  645. \end{minipage}
  646. \vrule
  647. \begin{minipage}{0.25\textwidth}
  648. \begin{lstlisting}
  649. #t
  650. #f
  651. #t
  652. \end{lstlisting}
  653. \end{minipage}
  654. \end{center}
  655. When writing a \code{match}, we refer to the grammar definition to
  656. identify which non-terminal we are expecting to match against, then we
  657. make sure that 1) we have one clause for each alternative of that
  658. non-terminal and 2) that the pattern in each clause corresponds to the
  659. corresponding right-hand side of a grammar rule. For the \code{match}
  660. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  661. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  662. alternatives, so the \code{match} has 4 clauses. The pattern in each
  663. clause corresponds to the right-hand side of a grammar rule. For
  664. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  665. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  666. patterns, replace non-terminals such as $\Exp$ with pattern variables
  667. of your choice (e.g. \code{e1} and \code{e2}).
  668. \section{Recursive Functions}
  669. \label{sec:recursion}
  670. \index{recursive function}
  671. Programs are inherently recursive. For example, an \LangInt{} expression is
  672. often made of smaller expressions. Thus, the natural way to process an
  673. entire program is with a recursive function. As a first example of
  674. such a recursive function, we define \texttt{exp?} below, which takes
  675. an arbitrary value and determines whether or not it is an \LangInt{}
  676. expression.
  677. %
  678. We say that a function is defined by \emph{structural recursion} when
  679. it is defined using a sequence of match clauses that correspond to a
  680. grammar, and the body of each clause makes a recursive call on each
  681. child node.\footnote{This principle of structuring code according to
  682. the data definition is advocated in the book \emph{How to Design
  683. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  684. Below we also define a second function, named \code{Rint?}, that
  685. determines whether an AST is an \LangInt{} program. In general we can
  686. expect to write one recursive function to handle each non-terminal in
  687. a grammar.\index{structural recursion}
  688. %
  689. \begin{center}
  690. \begin{minipage}{0.7\textwidth}
  691. \begin{lstlisting}
  692. (define (exp? ast)
  693. (match ast
  694. [(Int n) #t]
  695. [(Prim 'read '()) #t]
  696. [(Prim '- (list e)) (exp? e)]
  697. [(Prim '+ (list e1 e2))
  698. (and (exp? e1) (exp? e2))]
  699. [else #f]))
  700. (define (Rint? ast)
  701. (match ast
  702. [(Program '() e) (exp? e)]
  703. [else #f]))
  704. (Rint? (Program '() ast1.1)
  705. (Rint? (Program '()
  706. (Prim '- (list (Prim 'read '())
  707. (Prim '+ (list (Num 8)))))))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \vrule
  711. \begin{minipage}{0.25\textwidth}
  712. \begin{lstlisting}
  713. #t
  714. #f
  715. \end{lstlisting}
  716. \end{minipage}
  717. \end{center}
  718. You may be tempted to merge the two functions into one, like this:
  719. \begin{center}
  720. \begin{minipage}{0.5\textwidth}
  721. \begin{lstlisting}
  722. (define (Rint? ast)
  723. (match ast
  724. [(Int n) #t]
  725. [(Prim 'read '()) #t]
  726. [(Prim '- (list e)) (Rint? e)]
  727. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  728. [(Program '() e) (Rint? e)]
  729. [else #f]))
  730. \end{lstlisting}
  731. \end{minipage}
  732. \end{center}
  733. %
  734. Sometimes such a trick will save a few lines of code, especially when
  735. it comes to the \code{Program} wrapper. Yet this style is generally
  736. \emph{not} recommended because it can get you into trouble.
  737. %
  738. For example, the above function is subtly wrong:
  739. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  740. returns true when it should return false.
  741. \section{Interpreters}
  742. \label{sec:interp-Rint}
  743. \index{interpreter}
  744. In general, the intended behavior of a program is defined by the
  745. specification of the language. For example, the Scheme language is
  746. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  747. defined in its reference manual~\citep{plt-tr}. In this book we use
  748. interpreters to specify each language that we consider. An interpreter
  749. that is designated as the definition of a language is called a
  750. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  751. \index{definitional interpreter} We warm up by creating a definitional
  752. interpreter for the \LangInt{} language, which serves as a second example
  753. of structural recursion. The \texttt{interp-Rint} function is defined in
  754. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  755. input program followed by a call to the \lstinline{interp-exp} helper
  756. function, which in turn has one match clause per grammar rule for
  757. \LangInt{} expressions.
  758. \begin{figure}[tp]
  759. \begin{lstlisting}
  760. (define (interp-exp e)
  761. (match e
  762. [(Int n) n]
  763. [(Prim 'read '())
  764. (define r (read))
  765. (cond [(fixnum? r) r]
  766. [else (error 'interp-exp "read expected an integer" r)])]
  767. [(Prim '- (list e))
  768. (define v (interp-exp e))
  769. (fx- 0 v)]
  770. [(Prim '+ (list e1 e2))
  771. (define v1 (interp-exp e1))
  772. (define v2 (interp-exp e2))
  773. (fx+ v1 v2)]))
  774. (define (interp-Rint p)
  775. (match p
  776. [(Program '() e) (interp-exp e)]))
  777. \end{lstlisting}
  778. \caption{Interpreter for the \LangInt{} language.}
  779. \label{fig:interp-Rint}
  780. \end{figure}
  781. Let us consider the result of interpreting a few \LangInt{} programs. The
  782. following program adds two integers.
  783. \begin{lstlisting}
  784. (+ 10 32)
  785. \end{lstlisting}
  786. The result is \key{42}, the answer to life, the universe, and
  787. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  788. Galaxy} by Douglas Adams.}.
  789. %
  790. We wrote the above program in concrete syntax whereas the parsed
  791. abstract syntax is:
  792. \begin{lstlisting}
  793. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  794. \end{lstlisting}
  795. The next example demonstrates that expressions may be nested within
  796. each other, in this case nesting several additions and negations.
  797. \begin{lstlisting}
  798. (+ 10 (- (+ 12 20)))
  799. \end{lstlisting}
  800. What is the result of the above program?
  801. As mentioned previously, the \LangInt{} language does not support
  802. arbitrarily-large integers, but only $63$-bit integers, so we
  803. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  804. in Racket.
  805. Suppose
  806. \[
  807. n = 999999999999999999
  808. \]
  809. which indeed fits in $63$-bits. What happens when we run the
  810. following program in our interpreter?
  811. \begin{lstlisting}
  812. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  813. \end{lstlisting}
  814. It produces an error:
  815. \begin{lstlisting}
  816. fx+: result is not a fixnum
  817. \end{lstlisting}
  818. We establish the convention that if running the definitional
  819. interpreter on a program produces an error then the meaning of that
  820. program is \emph{unspecified}\index{unspecified behavior}, unless the
  821. error is a \code{trapped-error}. A compiler for the language is under
  822. no obligations regarding programs with unspecified behavior; it does
  823. not have to produce an executable, and if it does, that executable can
  824. do anything. On the other hand, if the error is a
  825. \code{trapped-error}, then the compiler must produce an executable and
  826. it is required to report that an error occurred. To signal an error,
  827. exit with a return code of \code{255}. The interpreters in chapters
  828. \ref{ch:type-dynamic} and \ref{ch:gradual-typing} use
  829. \code{trapped-error}.
  830. %% This convention applies to the languages defined in this
  831. %% book, as a way to simplify the student's task of implementing them,
  832. %% but this convention is not applicable to all programming languages.
  833. %%
  834. Moving on to the last feature of the \LangInt{} language, the \key{read}
  835. operation prompts the user of the program for an integer. Recall that
  836. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  837. \code{8}. So if we run
  838. \begin{lstlisting}
  839. (interp-Rint (Program '() ast1.1))
  840. \end{lstlisting}
  841. and if the input is \code{50}, the result is \code{42}.
  842. We include the \key{read} operation in \LangInt{} so a clever student
  843. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  844. during compilation to obtain the output and then generates the trivial
  845. code to produce the output. (Yes, a clever student did this in the
  846. first instance of this course.)
  847. The job of a compiler is to translate a program in one language into a
  848. program in another language so that the output program behaves the
  849. same way as the input program does. This idea is depicted in the
  850. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  851. $\mathcal{L}_2$, and a definitional interpreter for each language.
  852. Given a compiler that translates from language $\mathcal{L}_1$ to
  853. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  854. compiler must translate it into some program $P_2$ such that
  855. interpreting $P_1$ and $P_2$ on their respective interpreters with
  856. same input $i$ yields the same output $o$.
  857. \begin{equation} \label{eq:compile-correct}
  858. \begin{tikzpicture}[baseline=(current bounding box.center)]
  859. \node (p1) at (0, 0) {$P_1$};
  860. \node (p2) at (3, 0) {$P_2$};
  861. \node (o) at (3, -2.5) {$o$};
  862. \path[->] (p1) edge [above] node {compile} (p2);
  863. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  864. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  865. \end{tikzpicture}
  866. \end{equation}
  867. In the next section we see our first example of a compiler.
  868. \section{Example Compiler: a Partial Evaluator}
  869. \label{sec:partial-evaluation}
  870. In this section we consider a compiler that translates \LangInt{} programs
  871. into \LangInt{} programs that may be more efficient, that is, this compiler
  872. is an optimizer. This optimizer eagerly computes the parts of the
  873. program that do not depend on any inputs, a process known as
  874. \emph{partial evaluation}~\citep{Jones:1993uq}.
  875. \index{partial evaluation}
  876. For example, given the following program
  877. \begin{lstlisting}
  878. (+ (read) (- (+ 5 3)))
  879. \end{lstlisting}
  880. our compiler will translate it into the program
  881. \begin{lstlisting}
  882. (+ (read) -8)
  883. \end{lstlisting}
  884. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  885. evaluator for the \LangInt{} language. The output of the partial evaluator
  886. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  887. recursion over $\Exp$ is captured in the \code{pe-exp} function
  888. whereas the code for partially evaluating the negation and addition
  889. operations is factored into two separate helper functions:
  890. \code{pe-neg} and \code{pe-add}. The input to these helper
  891. functions is the output of partially evaluating the children.
  892. \begin{figure}[tp]
  893. \begin{lstlisting}
  894. (define (pe-neg r)
  895. (match r
  896. [(Int n) (Int (fx- 0 n))]
  897. [else (Prim '- (list r))]))
  898. (define (pe-add r1 r2)
  899. (match* (r1 r2)
  900. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  901. [(_ _) (Prim '+ (list r1 r2))]))
  902. (define (pe-exp e)
  903. (match e
  904. [(Int n) (Int n)]
  905. [(Prim 'read '()) (Prim 'read '())]
  906. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  907. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  908. (define (pe-Rint p)
  909. (match p
  910. [(Program '() e) (Program '() (pe-exp e))]))
  911. \end{lstlisting}
  912. \caption{A partial evaluator for \LangInt{}.}
  913. \label{fig:pe-arith}
  914. \end{figure}
  915. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  916. arguments are integers and if they are, perform the appropriate
  917. arithmetic. Otherwise, they create an AST node for the arithmetic
  918. operation.
  919. To gain some confidence that the partial evaluator is correct, we can
  920. test whether it produces programs that get the same result as the
  921. input programs. That is, we can test whether it satisfies Diagram
  922. \ref{eq:compile-correct}. The following code runs the partial
  923. evaluator on several examples and tests the output program. The
  924. \texttt{parse-program} and \texttt{assert} functions are defined in
  925. Appendix~\ref{appendix:utilities}.\\
  926. \begin{minipage}{1.0\textwidth}
  927. \begin{lstlisting}
  928. (define (test-pe p)
  929. (assert "testing pe-Rint"
  930. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  931. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  932. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  933. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  934. \end{lstlisting}
  935. \end{minipage}
  936. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  937. \chapter{Integers and Variables}
  938. \label{ch:int-exp}
  939. This chapter is about compiling a subset of Racket to x86-64 assembly
  940. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  941. integer arithmetic and local variable binding. We often refer to
  942. x86-64 simply as x86. The chapter begins with a description of the
  943. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  944. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  945. is large so we discuss only the instructions needed for compiling
  946. \LangVar{}. We introduce more x86 instructions in later chapters.
  947. After introducing \LangVar{} and x86, we reflect on their differences
  948. and come up with a plan to break down the translation from \LangVar{}
  949. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  950. rest of the sections in this chapter give detailed hints regarding
  951. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  952. We hope to give enough hints that the well-prepared reader, together
  953. with a few friends, can implement a compiler from \LangVar{} to x86 in
  954. a couple weeks. To give the reader a feeling for the scale of this
  955. first compiler, the instructor solution for the \LangVar{} compiler is
  956. approximately 500 lines of code.
  957. \section{The \LangVar{} Language}
  958. \label{sec:s0}
  959. \index{variable}
  960. The \LangVar{} language extends the \LangInt{} language with variable
  961. definitions. The concrete syntax of the \LangVar{} language is defined by
  962. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  963. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  964. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  965. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  966. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  967. \key{Program} struct to mark the top of the program.
  968. %% The $\itm{info}$
  969. %% field of the \key{Program} structure contains an \emph{association
  970. %% list} (a list of key-value pairs) that is used to communicate
  971. %% auxiliary data from one compiler pass the next.
  972. Despite the simplicity of the \LangVar{} language, it is rich enough to
  973. exhibit several compilation techniques.
  974. \begin{figure}[tp]
  975. \centering
  976. \fbox{
  977. \begin{minipage}{0.96\textwidth}
  978. \[
  979. \begin{array}{rcl}
  980. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  981. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  982. \LangVar{} &::=& \Exp
  983. \end{array}
  984. \]
  985. \end{minipage}
  986. }
  987. \caption{The concrete syntax of \LangVar{}.}
  988. \label{fig:r1-concrete-syntax}
  989. \end{figure}
  990. \begin{figure}[tp]
  991. \centering
  992. \fbox{
  993. \begin{minipage}{0.96\textwidth}
  994. \[
  995. \begin{array}{rcl}
  996. \Exp &::=& \INT{\Int} \mid \READ{} \\
  997. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  998. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  999. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1000. \end{array}
  1001. \]
  1002. \end{minipage}
  1003. }
  1004. \caption{The abstract syntax of \LangVar{}.}
  1005. \label{fig:r1-syntax}
  1006. \end{figure}
  1007. Let us dive further into the syntax and semantics of the \LangVar{}
  1008. language. The \key{let} feature defines a variable for use within its
  1009. body and initializes the variable with the value of an expression.
  1010. The abstract syntax for \key{let} is defined in
  1011. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1012. \begin{lstlisting}
  1013. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1014. \end{lstlisting}
  1015. For example, the following program initializes \code{x} to $32$ and then
  1016. evaluates the body \code{(+ 10 x)}, producing $42$.
  1017. \begin{lstlisting}
  1018. (let ([x (+ 12 20)]) (+ 10 x))
  1019. \end{lstlisting}
  1020. When there are multiple \key{let}'s for the same variable, the closest
  1021. enclosing \key{let} is used. That is, variable definitions overshadow
  1022. prior definitions. Consider the following program with two \key{let}'s
  1023. that define variables named \code{x}. Can you figure out the result?
  1024. \begin{lstlisting}
  1025. (let ([x 32]) (+ (let ([x 10]) x) x))
  1026. \end{lstlisting}
  1027. For the purposes of depicting which variable uses correspond to which
  1028. definitions, the following shows the \code{x}'s annotated with
  1029. subscripts to distinguish them. Double check that your answer for the
  1030. above is the same as your answer for this annotated version of the
  1031. program.
  1032. \begin{lstlisting}
  1033. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1034. \end{lstlisting}
  1035. The initializing expression is always evaluated before the body of the
  1036. \key{let}, so in the following, the \key{read} for \code{x} is
  1037. performed before the \key{read} for \code{y}. Given the input
  1038. $52$ then $10$, the following produces $42$ (not $-42$).
  1039. \begin{lstlisting}
  1040. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1041. \end{lstlisting}
  1042. \subsection{Extensible Interpreters via Method Overriding}
  1043. To prepare for discussing the interpreter for \LangVar{}, we need to
  1044. explain why we choose to implement the interpreter using
  1045. object-oriented programming, that is, as a collection of methods
  1046. inside of a class. Throughout this book we define many interpreters,
  1047. one for each of the languages that we study. Because each language
  1048. builds on the prior one, there is a lot of commonality between their
  1049. interpreters. We want to write down those common parts just once
  1050. instead of many times. A naive approach would be to have, for example,
  1051. the interpreter for \LangIf{} handle all of the new features in that
  1052. language and then have a default case that dispatches to the
  1053. interpreter for \LangVar{}. The following code sketches this idea.
  1054. \begin{center}
  1055. \begin{minipage}{0.45\textwidth}
  1056. \begin{lstlisting}
  1057. (define (interp-Rvar e)
  1058. (match e
  1059. [(Prim '- (list e))
  1060. (fx- 0 (interp-Rvar e))]
  1061. ...))
  1062. \end{lstlisting}
  1063. \end{minipage}
  1064. \begin{minipage}{0.45\textwidth}
  1065. \begin{lstlisting}
  1066. (define (interp-Rif e)
  1067. (match e
  1068. [(If cnd thn els)
  1069. (match (interp-Rif cnd)
  1070. [#t (interp-Rif thn)]
  1071. [#f (interp-Rif els)])]
  1072. ...
  1073. [else (interp-Rvar e)]))
  1074. \end{lstlisting}
  1075. \end{minipage}
  1076. \end{center}
  1077. The problem with this approach is that it does not handle situations
  1078. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1079. feature, like the \code{-} operator, as in the following program.
  1080. \begin{lstlisting}
  1081. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1082. \end{lstlisting}
  1083. If we invoke \code{interp-Rif} on this program, it dispatches to
  1084. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1085. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1086. which is an \code{If}. But there is no case for \code{If} in
  1087. \code{interp-Rvar}, so we get an error!
  1088. To make our interpreters extensible we need something called
  1089. \emph{open recursion}\index{open recursion}, where the tying of the
  1090. recursive knot is delayed to when the functions are
  1091. composed. Object-oriented languages provide open recursion with the
  1092. late-binding of overridden methods\index{method overriding}. The
  1093. following code sketches this idea for interpreting \LangVar{} and
  1094. \LangIf{} using the
  1095. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1096. \index{class} feature of Racket. We define one class for each
  1097. language and define a method for interpreting expressions inside each
  1098. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1099. and the method \code{interp-exp} in \LangIf{} overrides the
  1100. \code{interp-exp} in \LangVar{}. Note that the default case of
  1101. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1102. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1103. that dispatches to the \code{interp-exp} in \LangVar{}.
  1104. \begin{center}
  1105. \begin{minipage}{0.45\textwidth}
  1106. \begin{lstlisting}
  1107. (define interp-Rvar-class
  1108. (class object%
  1109. (define/public (interp-exp e)
  1110. (match e
  1111. [(Prim '- (list e))
  1112. (fx- 0 (interp-exp e))]
  1113. ...))
  1114. ...))
  1115. \end{lstlisting}
  1116. \end{minipage}
  1117. \begin{minipage}{0.45\textwidth}
  1118. \begin{lstlisting}
  1119. (define interp-Rif-class
  1120. (class interp-Rvar-class
  1121. (define/override (interp-exp e)
  1122. (match e
  1123. [(If cnd thn els)
  1124. (match (interp-exp cnd)
  1125. [#t (interp-exp thn)]
  1126. [#f (interp-exp els)])]
  1127. ...
  1128. [else (super interp-exp e)]))
  1129. ...
  1130. ))
  1131. \end{lstlisting}
  1132. \end{minipage}
  1133. \end{center}
  1134. Getting back to the troublesome example, repeated here:
  1135. \begin{lstlisting}
  1136. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1137. \end{lstlisting}
  1138. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1139. expression by creating an object of the \LangIf{} class and sending it the
  1140. \code{interp-exp} method with the argument \code{e0}.
  1141. \begin{lstlisting}
  1142. (send (new interp-Rif-class) interp-exp e0)
  1143. \end{lstlisting}
  1144. The default case of \code{interp-exp} in \LangIf{} handles it by
  1145. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1146. handles the \code{-} operator. But then for the recursive method call,
  1147. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1148. \code{If} is handled correctly. Thus, method overriding gives us the
  1149. open recursion that we need to implement our interpreters in an
  1150. extensible way.
  1151. \newpage
  1152. \subsection{Definitional Interpreter for \LangVar{}}
  1153. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1154. \small
  1155. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1156. An \emph{association list} (alist) is a list of key-value pairs.
  1157. For example, we can map people to their ages with an alist.
  1158. \index{alist}\index{association list}
  1159. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1160. (define ages
  1161. '((jane . 25) (sam . 24) (kate . 45)))
  1162. \end{lstlisting}
  1163. The \emph{dictionary} interface is for mapping keys to values.
  1164. Every alist implements this interface. \index{dictionary} The package
  1165. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1166. provides many functions for working with dictionaries. Here
  1167. are a few of them:
  1168. \begin{description}
  1169. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1170. returns the value associated with the given $\itm{key}$.
  1171. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1172. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1173. but otherwise is the same as $\itm{dict}$.
  1174. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1175. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1176. of keys and values in $\itm{dict}$. For example, the following
  1177. creates a new alist in which the ages are incremented.
  1178. \end{description}
  1179. \vspace{-10pt}
  1180. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1181. (for/list ([(k v) (in-dict ages)])
  1182. (cons k (add1 v)))
  1183. \end{lstlisting}
  1184. \end{tcolorbox}
  1185. \end{wrapfigure}
  1186. Having justified the use of classes and methods to implement
  1187. interpreters, we turn to the definitional interpreter for \LangVar{}
  1188. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1189. \LangInt{} but adds two new \key{match} clauses for variables and
  1190. \key{let}. For \key{let} we need a way to communicate the value bound
  1191. to a variable to all the uses of the variable. To accomplish this, we
  1192. maintain a mapping from variables to values. Throughout the compiler
  1193. we often need to map variables to information about them. We refer to
  1194. these mappings as
  1195. \emph{environments}\index{environment}.\footnote{Another common term
  1196. for environment in the compiler literature is \emph{symbol
  1197. table}\index{symbol table}.}
  1198. %
  1199. For simplicity, we use an association list (alist) to represent the
  1200. environment. The sidebar to the right gives a brief introduction to
  1201. alists and the \code{racket/dict} package. The \code{interp-exp}
  1202. function takes the current environment, \code{env}, as an extra
  1203. parameter. When the interpreter encounters a variable, it finds the
  1204. corresponding value using the \code{dict-ref} function. When the
  1205. interpreter encounters a \key{Let}, it evaluates the initializing
  1206. expression, extends the environment with the result value bound to the
  1207. variable, using \code{dict-set}, then evaluates the body of the
  1208. \key{Let}.
  1209. \begin{figure}[tp]
  1210. \begin{lstlisting}
  1211. (define interp-Rvar-class
  1212. (class object%
  1213. (super-new)
  1214. (define/public ((interp-exp env) e)
  1215. (match e
  1216. [(Int n) n]
  1217. [(Prim 'read '())
  1218. (define r (read))
  1219. (cond [(fixnum? r) r]
  1220. [else (error 'interp-exp "expected an integer" r)])]
  1221. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1222. [(Prim '+ (list e1 e2))
  1223. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1224. [(Var x) (dict-ref env x)]
  1225. [(Let x e body)
  1226. (define new-env (dict-set env x ((interp-exp env) e)))
  1227. ((interp-exp new-env) body)]))
  1228. (define/public (interp-program p)
  1229. (match p
  1230. [(Program '() e) ((interp-exp '()) e)]))
  1231. ))
  1232. (define (interp-Rvar p)
  1233. (send (new interp-Rvar-class) interp-program p))
  1234. \end{lstlisting}
  1235. \caption{Interpreter for the \LangVar{} language.}
  1236. \label{fig:interp-Rvar}
  1237. \end{figure}
  1238. The goal for this chapter is to implement a compiler that translates
  1239. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1240. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1241. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1242. is, they output the same integer $n$. We depict this correctness
  1243. criteria in the following diagram.
  1244. \[
  1245. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1246. \node (p1) at (0, 0) {$P_1$};
  1247. \node (p2) at (4, 0) {$P_2$};
  1248. \node (o) at (4, -2) {$n$};
  1249. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1250. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1251. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1252. \end{tikzpicture}
  1253. \]
  1254. In the next section we introduce the \LangXASTInt{} subset of x86 that
  1255. suffices for compiling \LangVar{}.
  1256. \section{The \LangXASTInt{} Assembly Language}
  1257. \label{sec:x86}
  1258. \index{x86}
  1259. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1260. \LangXASTInt{}. We use the AT\&T syntax expected by the GNU
  1261. assembler.
  1262. %
  1263. A program begins with a \code{main} label followed by a sequence of
  1264. instructions. The \key{globl} directive says that the \key{main}
  1265. procedure is externally visible, which is necessary so that the
  1266. operating system can call it. In the grammar, ellipses such as
  1267. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1268. \ldots$ is a sequence of instructions.\index{instruction}
  1269. %
  1270. An x86 program is stored in the computer's memory. For our purposes,
  1271. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1272. values. The computer has a \emph{program counter} (PC)\index{program
  1273. counter}\index{PC} stored in the \code{rip} register that points to
  1274. the address of the next instruction to be executed. For most
  1275. instructions, the program counter is incremented after the instruction
  1276. is executed, so it points to the next instruction in memory. Most x86
  1277. instructions take two operands, where each operand is either an
  1278. integer constant (called \emph{immediate value}\index{immediate
  1279. value}), a \emph{register}\index{register}, or a memory location.
  1280. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1281. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1282. && \key{r8} \mid \key{r9} \mid \key{r10}
  1283. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1284. \mid \key{r14} \mid \key{r15}}
  1285. \begin{figure}[tp]
  1286. \fbox{
  1287. \begin{minipage}{0.96\textwidth}
  1288. \[
  1289. \begin{array}{lcl}
  1290. \Reg &::=& \allregisters{} \\
  1291. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1292. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1293. \key{subq} \; \Arg\key{,} \Arg \mid
  1294. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1295. && \key{callq} \; \mathit{label} \mid
  1296. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1297. && \itm{label}\key{:}\; \Instr \\
  1298. \LangXInt{} &::= & \key{.globl main}\\
  1299. & & \key{main:} \; \Instr\ldots
  1300. \end{array}
  1301. \]
  1302. \end{minipage}
  1303. }
  1304. \caption{The syntax of the \LangXASTInt{} assembly language (AT\&T syntax).}
  1305. \label{fig:x86-int-concrete}
  1306. \end{figure}
  1307. A register is a special kind of variable. Each one holds a 64-bit
  1308. value; there are 16 general-purpose registers in the computer and
  1309. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1310. is written with a \key{\%} followed by the register name, such as
  1311. \key{\%rax}.
  1312. An immediate value is written using the notation \key{\$}$n$ where $n$
  1313. is an integer.
  1314. %
  1315. %
  1316. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1317. which obtains the address stored in register $r$ and then adds $n$
  1318. bytes to the address. The resulting address is used to load or store
  1319. to memory depending on whether it occurs as a source or destination
  1320. argument of an instruction.
  1321. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1322. source $s$ and destination $d$, applies the arithmetic operation, then
  1323. writes the result back to the destination $d$.
  1324. %
  1325. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1326. stores the result in $d$.
  1327. %
  1328. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1329. specified by the label and $\key{retq}$ returns from a procedure to
  1330. its caller.
  1331. %
  1332. We discuss procedure calls in more detail later in this chapter and in
  1333. Chapter~\ref{ch:functions}. The instruction $\key{jmp}\,\itm{label}$
  1334. updates the program counter to the address of the instruction after
  1335. the specified label.
  1336. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1337. all of the x86 instructions used in this book.
  1338. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1339. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1340. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1341. adds $32$ to the $10$ in \key{rax} and
  1342. puts the result, $42$, back into \key{rax}.
  1343. %
  1344. The last instruction, \key{retq}, finishes the \key{main} function by
  1345. returning the integer in \key{rax} to the operating system. The
  1346. operating system interprets this integer as the program's exit
  1347. code. By convention, an exit code of 0 indicates that a program
  1348. completed successfully, and all other exit codes indicate various
  1349. errors. Nevertheless, in this book we return the result of the program
  1350. as the exit code.
  1351. \begin{figure}[tbp]
  1352. \begin{lstlisting}
  1353. .globl main
  1354. main:
  1355. movq $10, %rax
  1356. addq $32, %rax
  1357. retq
  1358. \end{lstlisting}
  1359. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1360. \label{fig:p0-x86}
  1361. \end{figure}
  1362. The x86 assembly language varies in a couple ways depending on what
  1363. operating system it is assembled in. The code examples shown here are
  1364. correct on Linux and most Unix-like platforms, but when assembled on
  1365. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1366. as in \key{\_main}.
  1367. We exhibit the use of memory for storing intermediate results in the
  1368. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1369. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1370. memory called the \emph{procedure call stack} (or \emph{stack} for
  1371. short). \index{stack}\index{procedure call stack} The stack consists
  1372. of a separate \emph{frame}\index{frame} for each procedure call. The
  1373. memory layout for an individual frame is shown in
  1374. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1375. \emph{stack pointer}\index{stack pointer} and points to the item at
  1376. the top of the stack. The stack grows downward in memory, so we
  1377. increase the size of the stack by subtracting from the stack pointer.
  1378. In the context of a procedure call, the \emph{return
  1379. address}\index{return address} is the instruction after the call
  1380. instruction on the caller side. The function call instruction,
  1381. \code{callq}, pushes the return address onto the stack prior to
  1382. jumping to the procedure. The register \key{rbp} is the \emph{base
  1383. pointer}\index{base pointer} and is used to access variables that
  1384. are stored in the frame of the current procedure call. The base
  1385. pointer of the caller is pushed onto the stack after the return
  1386. address and then the base pointer is set to the location of the old
  1387. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1388. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1389. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1390. \begin{figure}[tbp]
  1391. \begin{lstlisting}
  1392. start:
  1393. movq $10, -8(%rbp)
  1394. negq -8(%rbp)
  1395. movq -8(%rbp), %rax
  1396. addq $52, %rax
  1397. jmp conclusion
  1398. .globl main
  1399. main:
  1400. pushq %rbp
  1401. movq %rsp, %rbp
  1402. subq $16, %rsp
  1403. jmp start
  1404. conclusion:
  1405. addq $16, %rsp
  1406. popq %rbp
  1407. retq
  1408. \end{lstlisting}
  1409. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1410. \label{fig:p1-x86}
  1411. \end{figure}
  1412. \begin{figure}[tbp]
  1413. \centering
  1414. \begin{tabular}{|r|l|} \hline
  1415. Position & Contents \\ \hline
  1416. 8(\key{\%rbp}) & return address \\
  1417. 0(\key{\%rbp}) & old \key{rbp} \\
  1418. -8(\key{\%rbp}) & variable $1$ \\
  1419. -16(\key{\%rbp}) & variable $2$ \\
  1420. \ldots & \ldots \\
  1421. 0(\key{\%rsp}) & variable $n$\\ \hline
  1422. \end{tabular}
  1423. \caption{Memory layout of a frame.}
  1424. \label{fig:frame}
  1425. \end{figure}
  1426. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1427. control is transferred from the operating system to the \code{main}
  1428. function. The operating system issues a \code{callq main} instruction
  1429. which pushes its return address on the stack and then jumps to
  1430. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1431. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1432. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1433. alignment (because the \code{callq} pushed the return address). The
  1434. first three instructions are the typical \emph{prelude}\index{prelude}
  1435. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1436. pointer for the caller onto the stack and subtracts $8$ from the stack
  1437. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1438. base pointer so that it points the location of the old base
  1439. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1440. pointer down to make enough room for storing variables. This program
  1441. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1442. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1443. functions. The last instruction of the prelude is \code{jmp start},
  1444. which transfers control to the instructions that were generated from
  1445. the Racket expression \code{(+ 52 (- 10))}.
  1446. The first instruction under the \code{start} label is
  1447. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1448. %
  1449. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1450. %
  1451. The next instruction moves the $-10$ from variable $1$ into the
  1452. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1453. the value in \code{rax}, updating its contents to $42$.
  1454. The three instructions under the label \code{conclusion} are the
  1455. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1456. two instructions restore the \code{rsp} and \code{rbp} registers to
  1457. the state they were in at the beginning of the procedure. The
  1458. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1459. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1460. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1461. instruction, \key{retq}, jumps back to the procedure that called this
  1462. one and adds $8$ to the stack pointer.
  1463. The compiler needs a convenient representation for manipulating x86
  1464. programs, so we define an abstract syntax for x86 in
  1465. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1466. \LangXASTInt{}. The main difference compared to the concrete syntax of
  1467. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1468. allowed in front of every instructions. Instead instructions are
  1469. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1470. label associated with every block, which is why the \key{X86Program}
  1471. struct includes an alist mapping labels to blocks. The reason for this
  1472. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1473. introduce conditional branching. The \code{Block} structure includes
  1474. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1475. useful in Chapter~\ref{ch:register-allocation-r1}. For now, the
  1476. $\itm{info}$ field should contain an empty list. Also, regarding the
  1477. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1478. integer for representing the arity of the function, i.e., the number
  1479. of arguments, which is helpful to know during register allocation
  1480. (Chapter~\ref{ch:register-allocation-r1}).
  1481. \begin{figure}[tp]
  1482. \fbox{
  1483. \begin{minipage}{0.98\textwidth}
  1484. \small
  1485. \[
  1486. \begin{array}{lcl}
  1487. \Reg &::=& \allregisters{} \\
  1488. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1489. \mid \DEREF{\Reg}{\Int} \\
  1490. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1491. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1492. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1493. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1494. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1495. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1496. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1497. \LangXASTInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1498. \end{array}
  1499. \]
  1500. \end{minipage}
  1501. }
  1502. \caption{The abstract syntax of \LangXASTInt{} assembly.}
  1503. \label{fig:x86-int-ast}
  1504. \end{figure}
  1505. \section{Planning the trip to x86 via the \LangCVar{} language}
  1506. \label{sec:plan-s0-x86}
  1507. To compile one language to another it helps to focus on the
  1508. differences between the two languages because the compiler will need
  1509. to bridge those differences. What are the differences between \LangVar{}
  1510. and x86 assembly? Here are some of the most important ones:
  1511. \begin{enumerate}
  1512. \item[(a)] x86 arithmetic instructions typically have two arguments
  1513. and update the second argument in place. In contrast, \LangVar{}
  1514. arithmetic operations take two arguments and produce a new value.
  1515. An x86 instruction may have at most one memory-accessing argument.
  1516. Furthermore, some instructions place special restrictions on their
  1517. arguments.
  1518. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1519. expression, whereas x86 instructions restrict their arguments to be
  1520. integers constants, registers, and memory locations.
  1521. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1522. sequence of instructions and jumps to labeled positions, whereas in
  1523. \LangVar{} the order of evaluation is a left-to-right depth-first
  1524. traversal of the abstract syntax tree.
  1525. \item[(d)] A program in \LangVar{} can have any number of variables
  1526. whereas x86 has 16 registers and the procedure calls stack.
  1527. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1528. same name. In x86, registers have unique names and memory locations
  1529. have unique addresses.
  1530. \end{enumerate}
  1531. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1532. the problem into several steps, dealing with the above differences one
  1533. at a time. Each of these steps is called a \emph{pass} of the
  1534. compiler.\index{pass}\index{compiler pass}
  1535. %
  1536. This terminology comes from the way each step passes over the AST of
  1537. the program.
  1538. %
  1539. We begin by sketching how we might implement each pass, and give them
  1540. names. We then figure out an ordering of the passes and the
  1541. input/output language for each pass. The very first pass has
  1542. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1543. its output language. In between we can choose whichever language is
  1544. most convenient for expressing the output of each pass, whether that
  1545. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1546. our own design. Finally, to implement each pass we write one
  1547. recursive function per non-terminal in the grammar of the input
  1548. language of the pass. \index{intermediate language}
  1549. \begin{description}
  1550. \item[\key{select-instructions}] handles the difference between
  1551. \LangVar{} operations and x86 instructions. This pass converts each
  1552. \LangVar{} operation to a short sequence of instructions that
  1553. accomplishes the same task.
  1554. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1555. a primitive operation is a variable or integer, that is, an
  1556. \emph{atomic} expression. We refer to non-atomic expressions as
  1557. \emph{complex}. This pass introduces temporary variables to hold
  1558. the results of complex subexpressions.\index{atomic
  1559. expression}\index{complex expression}%
  1560. \footnote{The subexpressions of an operation are often called
  1561. operators and operands which explains the presence of
  1562. \code{opera*} in the name of this pass.}
  1563. \item[\key{explicate-control}] makes the execution order of the
  1564. program explicit. It convert the abstract syntax tree representation
  1565. into a control-flow graph in which each node contains a sequence of
  1566. statements and the edges between nodes say which nodes contain jumps
  1567. to other nodes.
  1568. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1569. registers or stack locations in x86.
  1570. \item[\key{uniquify}] deals with the shadowing of variables by
  1571. renaming every variable to a unique name.
  1572. \end{description}
  1573. The next question is: in what order should we apply these passes? This
  1574. question can be challenging because it is difficult to know ahead of
  1575. time which orderings will be better (easier to implement, produce more
  1576. efficient code, etc.) so oftentimes trial-and-error is
  1577. involved. Nevertheless, we can try to plan ahead and make educated
  1578. choices regarding the ordering.
  1579. What should be the ordering of \key{explicate-control} with respect to
  1580. \key{uniquify}? The \key{uniquify} pass should come first because
  1581. \key{explicate-control} changes all the \key{let}-bound variables to
  1582. become local variables whose scope is the entire program, which would
  1583. confuse variables with the same name.
  1584. %
  1585. We place \key{remove-complex-opera*} before \key{explicate-control}
  1586. because the later removes the \key{let} form, but it is convenient to
  1587. use \key{let} in the output of \key{remove-complex-opera*}.
  1588. %
  1589. The ordering of \key{uniquify} with respect to
  1590. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1591. \key{uniquify} to come first.
  1592. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1593. These two passes are intertwined. In Chapter~\ref{ch:functions} we
  1594. learn that, in x86, registers are used for passing arguments to
  1595. functions and it is preferable to assign parameters to their
  1596. corresponding registers. On the other hand, by selecting instructions
  1597. first we may run into a dead end in \key{assign-homes}. Recall that
  1598. only one argument of an x86 instruction may be a memory access but
  1599. \key{assign-homes} might fail to assign even one of them to a
  1600. register.
  1601. %
  1602. A sophisticated approach is to iteratively repeat the two passes until
  1603. a solution is found. However, to reduce implementation complexity we
  1604. recommend a simpler approach in which \key{select-instructions} comes
  1605. first, followed by the \key{assign-homes}, then a third pass named
  1606. \key{patch-instructions} that uses a reserved register to fix
  1607. outstanding problems.
  1608. \begin{figure}[tbp]
  1609. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1610. \node (Rvar) at (0,2) {\large \LangVar{}};
  1611. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1612. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1613. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1614. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1615. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1616. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1617. \node (x86-4) at (9,-2) {\large \LangXASTInt{}};
  1618. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1619. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1620. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1621. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1622. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1623. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1624. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1625. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1626. \end{tikzpicture}
  1627. \caption{Diagram of the passes for compiling \LangVar{}. }
  1628. \label{fig:Rvar-passes}
  1629. \end{figure}
  1630. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1631. passes and identifies the input and output language of each pass. The
  1632. last pass, \key{print-x86}, converts from the abstract syntax of
  1633. \LangXASTInt{} to the concrete syntax. In the following two sections
  1634. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1635. dialect of x86. The remainder of this chapter gives hints regarding
  1636. the implementation of each of the compiler passes in
  1637. Figure~\ref{fig:Rvar-passes}.
  1638. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1639. %% are programs that are still in the \LangVar{} language, though the
  1640. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1641. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1642. %% %
  1643. %% The output of \key{explicate-control} is in an intermediate language
  1644. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1645. %% syntax, which we introduce in the next section. The
  1646. %% \key{select-instruction} pass translates from \LangCVar{} to
  1647. %% \LangXVar{}. The \key{assign-homes} and
  1648. %% \key{patch-instructions}
  1649. %% passes input and output variants of x86 assembly.
  1650. \subsection{The \LangCVar{} Intermediate Language}
  1651. The output of \key{explicate-control} is similar to the $C$
  1652. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1653. categories for expressions and statements, so we name it \LangCVar{}. The
  1654. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1655. (The concrete syntax for \LangCVar{} is in the Appendix,
  1656. Figure~\ref{fig:c0-concrete-syntax}.)
  1657. %
  1658. The \LangCVar{} language supports the same operators as \LangVar{} but
  1659. the arguments of operators are restricted to atomic
  1660. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1661. assignment statements which can be executed in sequence using the
  1662. \key{Seq} form. A sequence of statements always ends with
  1663. \key{Return}, a guarantee that is baked into the grammar rules for
  1664. \itm{tail}. The naming of this non-terminal comes from the term
  1665. \emph{tail position}\index{tail position}, which refers to an
  1666. expression that is the last one to execute within a function.
  1667. A \LangCVar{} program consists of a control-flow graph represented as
  1668. an alist mapping labels to tails. This is more general than necessary
  1669. for the present chapter, as we do not yet introduce \key{goto} for
  1670. jumping to labels, but it saves us from having to change the syntax in
  1671. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1672. \key{start}, and the whole program is its tail.
  1673. %
  1674. The $\itm{info}$ field of the \key{CProgram} form, after the
  1675. \key{explicate-control} pass, contains a mapping from the symbol
  1676. \key{locals} to a list of variables, that is, a list of all the
  1677. variables used in the program. At the start of the program, these
  1678. variables are uninitialized; they become initialized on their first
  1679. assignment.
  1680. \begin{figure}[tbp]
  1681. \fbox{
  1682. \begin{minipage}{0.96\textwidth}
  1683. \[
  1684. \begin{array}{lcl}
  1685. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1686. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1687. &\mid& \ADD{\Atm}{\Atm}\\
  1688. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1689. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1690. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1691. \end{array}
  1692. \]
  1693. \end{minipage}
  1694. }
  1695. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1696. \label{fig:c0-syntax}
  1697. \end{figure}
  1698. The definitional interpreter for \LangCVar{} is in the support code
  1699. for this book, in the file \code{interp-Cvar.rkt}. The support code is
  1700. in a \code{github} repository at the following URL:
  1701. \begin{center}\footnotesize
  1702. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1703. \end{center}
  1704. \subsection{The \LangXVar{} dialect}
  1705. The \LangXVar{} language is the output of the pass
  1706. \key{select-instructions}. It extends \LangXASTInt{} with an unbounded
  1707. number of program-scope variables and removes the restrictions
  1708. regarding instruction arguments.
  1709. \section{Uniquify Variables}
  1710. \label{sec:uniquify-Rvar}
  1711. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1712. programs in which every \key{let} binds a unique variable name. For
  1713. example, the \code{uniquify} pass should translate the program on the
  1714. left into the program on the right. \\
  1715. \begin{tabular}{lll}
  1716. \begin{minipage}{0.4\textwidth}
  1717. \begin{lstlisting}
  1718. (let ([x 32])
  1719. (+ (let ([x 10]) x) x))
  1720. \end{lstlisting}
  1721. \end{minipage}
  1722. &
  1723. $\Rightarrow$
  1724. &
  1725. \begin{minipage}{0.4\textwidth}
  1726. \begin{lstlisting}
  1727. (let ([x.1 32])
  1728. (+ (let ([x.2 10]) x.2) x.1))
  1729. \end{lstlisting}
  1730. \end{minipage}
  1731. \end{tabular} \\
  1732. %
  1733. The following is another example translation, this time of a program
  1734. with a \key{let} nested inside the initializing expression of another
  1735. \key{let}.\\
  1736. \begin{tabular}{lll}
  1737. \begin{minipage}{0.4\textwidth}
  1738. \begin{lstlisting}
  1739. (let ([x (let ([x 4])
  1740. (+ x 1))])
  1741. (+ x 2))
  1742. \end{lstlisting}
  1743. \end{minipage}
  1744. &
  1745. $\Rightarrow$
  1746. &
  1747. \begin{minipage}{0.4\textwidth}
  1748. \begin{lstlisting}
  1749. (let ([x.2 (let ([x.1 4])
  1750. (+ x.1 1))])
  1751. (+ x.2 2))
  1752. \end{lstlisting}
  1753. \end{minipage}
  1754. \end{tabular}
  1755. We recommend implementing \code{uniquify} by creating a structurally
  1756. recursive function named \code{uniquify-exp} that mostly just copies
  1757. an expression. However, when encountering a \key{let}, it should
  1758. generate a unique name for the variable and associate the old name
  1759. with the new name in an alist.\footnote{The Racket function
  1760. \code{gensym} is handy for generating unique variable names.} The
  1761. \code{uniquify-exp} function needs to access this alist when it gets
  1762. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1763. for the alist.
  1764. The skeleton of the \code{uniquify-exp} function is shown in
  1765. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1766. convenient to partially apply it to an alist and then apply it to
  1767. different expressions, as in the last clause for primitive operations
  1768. in Figure~\ref{fig:uniquify-Rvar}. The
  1769. %
  1770. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1771. %
  1772. form of Racket is useful for transforming each element of a list to
  1773. produce a new list.\index{for/list}
  1774. \begin{exercise}
  1775. \normalfont % I don't like the italics for exercises. -Jeremy
  1776. Complete the \code{uniquify} pass by filling in the blanks in
  1777. Figure~\ref{fig:uniquify-Rvar}, that is, implement the clauses for
  1778. variables and for the \key{let} form in the file \code{compiler.rkt}
  1779. in the support code.
  1780. \end{exercise}
  1781. \begin{figure}[tbp]
  1782. \begin{lstlisting}
  1783. (define (uniquify-exp env)
  1784. (lambda (e)
  1785. (match e
  1786. [(Var x) ___]
  1787. [(Int n) (Int n)]
  1788. [(Let x e body) ___]
  1789. [(Prim op es)
  1790. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1791. (define (uniquify p)
  1792. (match p
  1793. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1794. \end{lstlisting}
  1795. \caption{Skeleton for the \key{uniquify} pass.}
  1796. \label{fig:uniquify-Rvar}
  1797. \end{figure}
  1798. \begin{exercise}
  1799. \normalfont % I don't like the italics for exercises. -Jeremy
  1800. Creating five \LangVar{} programs to test the most interesting parts
  1801. of the \key{uniquify} pass, that is, the programs should include
  1802. \key{let} forms, variables, and variables that overshadow each other.
  1803. The five programs should be placed in the subdirectory named
  1804. \key{tests} and the file names should start with \code{var\_test\_}
  1805. followed by a unique integer and end with the file extension
  1806. \key{.rkt}. Run the \key{run-tests.rkt} script in the support code to
  1807. check whether the output programs produce the same result as the input
  1808. programs. The script uses the \key{interp-tests} function
  1809. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1810. your \key{uniquify} pass on the example programs.
  1811. \end{exercise}
  1812. \section{Remove Complex Operands}
  1813. \label{sec:remove-complex-opera-Rvar}
  1814. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1815. \LangVar{} programs in which the arguments of operations are atomic
  1816. expressions. Put another way, this pass removes complex
  1817. operands\index{complex operand}, such as the expression \code{(- 10)}
  1818. in the program below. This is accomplished by introducing a new
  1819. \key{let}-bound variable, binding the complex operand to the new
  1820. variable, and then using the new variable in place of the complex
  1821. operand, as shown in the output of \code{remove-complex-opera*} on the
  1822. right.\\
  1823. \begin{tabular}{lll}
  1824. \begin{minipage}{0.4\textwidth}
  1825. % s0_19.rkt
  1826. \begin{lstlisting}
  1827. (+ 52 (- 10))
  1828. \end{lstlisting}
  1829. \end{minipage}
  1830. &
  1831. $\Rightarrow$
  1832. &
  1833. \begin{minipage}{0.4\textwidth}
  1834. \begin{lstlisting}
  1835. (let ([tmp.1 (- 10)])
  1836. (+ 52 tmp.1))
  1837. \end{lstlisting}
  1838. \end{minipage}
  1839. \end{tabular}
  1840. \begin{figure}[tp]
  1841. \centering
  1842. \fbox{
  1843. \begin{minipage}{0.96\textwidth}
  1844. \[
  1845. \begin{array}{rcl}
  1846. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1847. \Exp &::=& \Atm \mid \READ{} \\
  1848. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1849. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1850. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1851. \end{array}
  1852. \]
  1853. \end{minipage}
  1854. }
  1855. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1856. \label{fig:r1-anf-syntax}
  1857. \end{figure}
  1858. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1859. this pass, the language \LangVarANF{}. The only difference is that
  1860. operator arguments are required to be atomic expressions. In the
  1861. literature, this is called \emph{administrative normal form}, or ANF
  1862. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  1863. normal form} \index{ANF}
  1864. We recommend implementing this pass with two mutually recursive
  1865. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1866. \code{rco-atom} to subexpressions that are required to be atomic and
  1867. to apply \code{rco-exp} to subexpressions that can be atomic or
  1868. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1869. \LangVar{} expression as input. The \code{rco-exp} function returns an
  1870. expression. The \code{rco-atom} function returns two things: an
  1871. atomic expression and alist mapping temporary variables to complex
  1872. subexpressions. You can return multiple things from a function using
  1873. Racket's \key{values} form and you can receive multiple things from a
  1874. function call using the \key{define-values} form. If you are not
  1875. familiar with these features, review the Racket documentation. Also,
  1876. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1877. form is useful for applying a function to each
  1878. element of a list, in the case where the function returns multiple
  1879. values.
  1880. \index{for/lists}
  1881. The following shows the output of \code{rco-atom} on the expression
  1882. \code{(- 10)} (using concrete syntax to be concise).
  1883. \begin{tabular}{lll}
  1884. \begin{minipage}{0.4\textwidth}
  1885. \begin{lstlisting}
  1886. (- 10)
  1887. \end{lstlisting}
  1888. \end{minipage}
  1889. &
  1890. $\Rightarrow$
  1891. &
  1892. \begin{minipage}{0.4\textwidth}
  1893. \begin{lstlisting}
  1894. tmp.1
  1895. ((tmp.1 . (- 10)))
  1896. \end{lstlisting}
  1897. \end{minipage}
  1898. \end{tabular}
  1899. Take special care of programs such as the following one that binds a
  1900. variable to an atomic expression. You should leave such variable
  1901. bindings unchanged, as shown in to the program on the right \\
  1902. \begin{tabular}{lll}
  1903. \begin{minipage}{0.4\textwidth}
  1904. % s0_20.rkt
  1905. \begin{lstlisting}
  1906. (let ([a 42])
  1907. (let ([b a])
  1908. b))
  1909. \end{lstlisting}
  1910. \end{minipage}
  1911. &
  1912. $\Rightarrow$
  1913. &
  1914. \begin{minipage}{0.4\textwidth}
  1915. \begin{lstlisting}
  1916. (let ([a 42])
  1917. (let ([b a])
  1918. b))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \end{tabular} \\
  1922. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1923. produce the following output with unnecessary temporary variables.\\
  1924. \begin{minipage}{0.4\textwidth}
  1925. \begin{lstlisting}
  1926. (let ([tmp.1 42])
  1927. (let ([a tmp.1])
  1928. (let ([tmp.2 a])
  1929. (let ([b tmp.2])
  1930. b))))
  1931. \end{lstlisting}
  1932. \end{minipage}
  1933. \begin{exercise}
  1934. \normalfont Implement the \code{remove-complex-opera*} in
  1935. \code{compiler.rkt}. Create three new \LangInt{} programs that are
  1936. designed to exercise the interesting code in the
  1937. \code{remove-complex-opera*} pass (Following the same file name
  1938. guidelines as before.). In the \code{run-tests.rkt} script,
  1939. uncomment the line for this pass in the list of \code{passes} and
  1940. then run the script to test your compiler.
  1941. \end{exercise}
  1942. \section{Explicate Control}
  1943. \label{sec:explicate-control-r1}
  1944. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  1945. programs that make the order of execution explicit in their
  1946. syntax. For now this amounts to flattening \key{let} constructs into a
  1947. sequence of assignment statements. For example, consider the following
  1948. \LangVar{} program.\\
  1949. % s0_11.rkt
  1950. \begin{minipage}{0.96\textwidth}
  1951. \begin{lstlisting}
  1952. (let ([y (let ([x 20])
  1953. (+ x (let ([x 22]) x)))])
  1954. y)
  1955. \end{lstlisting}
  1956. \end{minipage}\\
  1957. %
  1958. The output of the previous pass and of \code{explicate-control} is
  1959. shown below. Recall that the right-hand-side of a \key{let} executes
  1960. before its body, so the order of evaluation for this program is to
  1961. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  1962. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1963. output of \code{explicate-control} makes this ordering explicit.\\
  1964. \begin{tabular}{lll}
  1965. \begin{minipage}{0.4\textwidth}
  1966. \begin{lstlisting}
  1967. (let ([y (let ([x.1 20])
  1968. (let ([x.2 22])
  1969. (+ x.1 x.2)))])
  1970. y)
  1971. \end{lstlisting}
  1972. \end{minipage}
  1973. &
  1974. $\Rightarrow$
  1975. &
  1976. \begin{minipage}{0.4\textwidth}
  1977. \begin{lstlisting}[language=C]
  1978. start:
  1979. x.1 = 20;
  1980. x.2 = 22;
  1981. y = (+ x.1 x.2);
  1982. return y;
  1983. \end{lstlisting}
  1984. \end{minipage}
  1985. \end{tabular}
  1986. \begin{figure}[tbp]
  1987. \begin{lstlisting}
  1988. (define (explicate-tail e)
  1989. (match e
  1990. [(Var x) ___]
  1991. [(Int n) (Return (Int n))]
  1992. [(Let x rhs body) ___]
  1993. [(Prim op es) ___]
  1994. [else (error "explicate-tail unhandled case" e)]))
  1995. (define (explicate-assign e x cont)
  1996. (match e
  1997. [(Var x) ___]
  1998. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  1999. [(Let y rhs body) ___]
  2000. [(Prim op es) ___]
  2001. [else (error "explicate-assign unhandled case" e)]))
  2002. (define (explicate-control p)
  2003. (match p
  2004. [(Program info body) ___]))
  2005. \end{lstlisting}
  2006. \caption{Skeleton for the \key{explicate-control} pass.}
  2007. \label{fig:explicate-control-Rvar}
  2008. \end{figure}
  2009. The organization of this pass depends on the notion of tail position
  2010. that we have alluded to earlier. Formally, \emph{tail
  2011. position}\index{tail position} in the context of \LangVar{} is
  2012. defined recursively by the following two rules.
  2013. \begin{enumerate}
  2014. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2015. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2016. \end{enumerate}
  2017. We recommend implementing \code{explicate-control} using two mutually
  2018. recursive functions, \code{explicate-tail} and
  2019. \code{explicate-assign}, as suggested in the skeleton code in
  2020. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2021. function should be applied to expressions in tail position whereas the
  2022. \code{explicate-assign} should be applied to expressions that occur on
  2023. the right-hand-side of a \key{let}.
  2024. %
  2025. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2026. input and produces a \Tail{} in \LangCVar{} (see
  2027. Figure~\ref{fig:c0-syntax}).
  2028. %
  2029. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2030. the variable that it is to be assigned to, and a \Tail{} in
  2031. \LangCVar{} for the code that will come after the assignment. The
  2032. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2033. The \code{explicate-assign} function is in accumulator-passing style
  2034. in that the \code{cont} parameter is used for accumulating the
  2035. output. The reader might be tempted to instead organize
  2036. \code{explicate-assign} in a more direct fashion, without the
  2037. \code{cont} parameter and perhaps using \code{append} to combine
  2038. statements. We warn against that alternative because the
  2039. accumulator-passing style is key to how we generate high-quality code
  2040. for conditional expressions in Chapter~\ref{ch:bool-types}.
  2041. \section{Select Instructions}
  2042. \label{sec:select-r1}
  2043. \index{instruction selection}
  2044. In the \code{select-instructions} pass we begin the work of
  2045. translating from \LangCVar{} to \LangXVar{}. The target language of
  2046. this pass is a variant of x86 that still uses variables, so we add an
  2047. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2048. the \LangXASTInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2049. recommend implementing the \code{select-instructions} with
  2050. three auxiliary functions, one for each of the non-terminals of
  2051. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2052. The cases for $\Atm$ are straightforward, variables stay
  2053. the same and integer constants are changed to immediates:
  2054. $\INT{n}$ changes to $\IMM{n}$.
  2055. Next we consider the cases for $\Stmt$, starting with arithmetic
  2056. operations. For example, consider the addition operation below that
  2057. puts the sum of \code{y} and \code{z} into \code{x}. We can use the
  2058. \key{addq} instruction, but it performs an in-place update. So we
  2059. could move \code{y} to \code{x} and then add \code{z} to \code{x}. \\
  2060. \begin{tabular}{lll}
  2061. \begin{minipage}{0.4\textwidth}
  2062. \begin{lstlisting}
  2063. x = (+ y z);
  2064. \end{lstlisting}
  2065. \end{minipage}
  2066. &
  2067. $\Rightarrow$
  2068. &
  2069. \begin{minipage}{0.4\textwidth}
  2070. \begin{lstlisting}
  2071. movq y, x
  2072. addq z, x
  2073. \end{lstlisting}
  2074. \end{minipage}
  2075. \end{tabular} \\
  2076. %
  2077. There are also cases that require special care to avoid generating
  2078. needlessly complicated code. For example, if one of the arguments of
  2079. the addition is the same variable as the left-hand side of the
  2080. assignment, then there is no need for the extra move instruction. The
  2081. following assignment statement can be translated into a single
  2082. \key{addq} instruction.\\
  2083. \begin{tabular}{lll}
  2084. \begin{minipage}{0.4\textwidth}
  2085. \begin{lstlisting}
  2086. x = (+ 10 x);
  2087. \end{lstlisting}
  2088. \end{minipage}
  2089. &
  2090. $\Rightarrow$
  2091. &
  2092. \begin{minipage}{0.4\textwidth}
  2093. \begin{lstlisting}
  2094. addq $10, x
  2095. \end{lstlisting}
  2096. \end{minipage}
  2097. \end{tabular}
  2098. The \key{read} operation does not have a direct counterpart in x86
  2099. assembly, so we provide this functionality with the function
  2100. \code{read\_int} in the file \code{runtime.c}, written in
  2101. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2102. functionality in this file as the \emph{runtime system}\index{runtime
  2103. system}, or simply the \emph{runtime} for short. When compiling your
  2104. generated x86 assembly code, you need to compile \code{runtime.c} to
  2105. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2106. \code{-c}) and link it into the executable. For our purposes of code
  2107. generation, all you need to do is translate an assignment of
  2108. \key{read} into a call to the \code{read\_int} function followed by a
  2109. move from \code{rax} to the left-hand-side of the assignment. The
  2110. move from \code{rax} is needed because the return value from
  2111. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2112. \begin{tabular}{lll}
  2113. \begin{minipage}{0.3\textwidth}
  2114. \begin{lstlisting}
  2115. x = (read);
  2116. \end{lstlisting}
  2117. \end{minipage}
  2118. &
  2119. $\Rightarrow$
  2120. &
  2121. \begin{minipage}{0.3\textwidth}
  2122. \begin{lstlisting}
  2123. callq read_int
  2124. movq %rax, x
  2125. \end{lstlisting}
  2126. \end{minipage}
  2127. \end{tabular}
  2128. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2129. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2130. assignment to the \key{rax} register followed by a jump to the
  2131. conclusion of the program (so the conclusion needs to be labeled).
  2132. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2133. recursively and then append the resulting instructions.
  2134. \begin{exercise}
  2135. \normalfont Implement the \key{select-instructions} pass in
  2136. \code{compiler.rkt}. Create three new example programs that are
  2137. designed to exercise all of the interesting cases in this pass. In
  2138. the \code{run-tests.rkt} script, uncomment the line for this pass in
  2139. the list of \code{passes} and then run the script to test your
  2140. compiler.
  2141. \end{exercise}
  2142. \section{Assign Homes}
  2143. \label{sec:assign-r1}
  2144. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2145. \LangXVar{} programs that no longer use program variables.
  2146. Thus, the \key{assign-homes} pass is responsible for placing all of
  2147. the program variables in registers or on the stack. For runtime
  2148. efficiency, it is better to place variables in registers, but as there
  2149. are only 16 registers, some programs must necessarily resort to
  2150. placing some variables on the stack. In this chapter we focus on the
  2151. mechanics of placing variables on the stack. We study an algorithm for
  2152. placing variables in registers in
  2153. Chapter~\ref{ch:register-allocation-r1}.
  2154. Consider again the following \LangVar{} program from
  2155. Section~\ref{sec:remove-complex-opera-Rvar}.
  2156. % s0_20.rkt
  2157. \begin{lstlisting}
  2158. (let ([a 42])
  2159. (let ([b a])
  2160. b))
  2161. \end{lstlisting}
  2162. The output of \code{select-instructions} is shown on the left and the
  2163. output of \code{assign-homes} on the right. In this example, we
  2164. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2165. variable \code{b} to location \code{-16(\%rbp)}.\\
  2166. \begin{tabular}{l}
  2167. \begin{minipage}{0.4\textwidth}
  2168. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2169. locals-types:
  2170. a : Integer, b : Integer
  2171. start:
  2172. movq $42, a
  2173. movq a, b
  2174. movq b, %rax
  2175. jmp conclusion
  2176. \end{lstlisting}
  2177. \end{minipage}
  2178. {$\Rightarrow$}
  2179. \begin{minipage}{0.4\textwidth}
  2180. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2181. stack-space: 16
  2182. start:
  2183. movq $42, -8(%rbp)
  2184. movq -8(%rbp), -16(%rbp)
  2185. movq -16(%rbp), %rax
  2186. jmp conclusion
  2187. \end{lstlisting}
  2188. \end{minipage}
  2189. \end{tabular}
  2190. The \code{locals-types} entry in the $\itm{info}$ of the
  2191. \code{X86Program} node is an alist mapping all the variables in the
  2192. program to their types (for now just \code{Integer}). The
  2193. \code{assign-homes} pass should replace all uses of those variables
  2194. with stack locations. As an aside, the \code{locals-types} entry is
  2195. computed by \code{type-check-Cvar} in the support code, which installs
  2196. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2197. be propagated to the \code{X86Program} node.
  2198. In the process of assigning variables to stack locations, it is
  2199. convenient for you to compute and store the size of the frame (in
  2200. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2201. the key \code{stack-space}, which is needed later to generate the
  2202. conclusion of the \code{main} procedure. The x86-64 standard requires
  2203. the frame size to be a multiple of 16 bytes.\index{frame}
  2204. \begin{exercise}\normalfont
  2205. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2206. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2207. \Block{}. We recommend that the auxiliary functions take an extra
  2208. parameter that is an alist mapping variable names to homes (stack
  2209. locations for now). In the \code{run-tests.rkt} script, uncomment the
  2210. line for this pass in the list of \code{passes} and then run the
  2211. script to test your compiler.
  2212. \end{exercise}
  2213. \section{Patch Instructions}
  2214. \label{sec:patch-s0}
  2215. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2216. \LangXASTInt{} by making sure that each instruction adheres to the
  2217. restriction that at most one argument of an instruction may be a
  2218. memory reference.
  2219. We return to the following example.
  2220. % s0_20.rkt
  2221. \begin{lstlisting}
  2222. (let ([a 42])
  2223. (let ([b a])
  2224. b))
  2225. \end{lstlisting}
  2226. The \key{assign-homes} pass produces the following output
  2227. for this program. \\
  2228. \begin{minipage}{0.5\textwidth}
  2229. \begin{lstlisting}
  2230. stack-space: 16
  2231. start:
  2232. movq $42, -8(%rbp)
  2233. movq -8(%rbp), -16(%rbp)
  2234. movq -16(%rbp), %rax
  2235. jmp conclusion
  2236. \end{lstlisting}
  2237. \end{minipage}\\
  2238. The second \key{movq} instruction is problematic because both
  2239. arguments are stack locations. We suggest fixing this problem by
  2240. moving from the source location to the register \key{rax} and then
  2241. from \key{rax} to the destination location, as follows.
  2242. \begin{lstlisting}
  2243. movq -8(%rbp), %rax
  2244. movq %rax, -16(%rbp)
  2245. \end{lstlisting}
  2246. \begin{exercise}
  2247. \normalfont Implement the \key{patch-instructions} pass in
  2248. \code{compiler.rkt}. Create three new example programs that are
  2249. designed to exercise all of the interesting cases in this pass. In
  2250. the \code{run-tests.rkt} script, uncomment the line for this pass in
  2251. the list of \code{passes} and then run the script to test your
  2252. compiler.
  2253. \end{exercise}
  2254. \section{Print x86}
  2255. \label{sec:print-x86}
  2256. The last step of the compiler from \LangVar{} to x86 is to convert the
  2257. \LangXASTInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2258. string representation (defined in
  2259. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2260. \key{string-append} functions are useful in this regard. The main work
  2261. that this step needs to perform is to create the \key{main} function
  2262. and the standard instructions for its prelude and conclusion, as shown
  2263. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2264. know the amount of space needed for the stack frame, which you can
  2265. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2266. the \key{X86Program} node.
  2267. When running on Mac OS X, you compiler should prefix an underscore to
  2268. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2269. useful for determining which operating system the compiler is running
  2270. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2271. \begin{exercise}
  2272. \normalfont Implement the \key{print-x86} pass in
  2273. \code{compiler.rkt}. Uncomment the line for this pass in the list of
  2274. \code{passes} in the \code{run-tests.rkt} script. Also uncomment the
  2275. call to the \key{compiler-tests} function
  2276. (Appendix~\ref{appendix:utilities}), which tests your complete
  2277. compiler by executing the generated x86 code. Compile the provided
  2278. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2279. script to test your compiler.
  2280. \end{exercise}
  2281. \section{Challenge: Partial Evaluator for \LangVar{}}
  2282. \label{sec:pe-Rvar}
  2283. \index{partial evaluation}
  2284. This section describes optional challenge exercises that involve
  2285. adapting and improving the partial evaluator for \LangInt{} that was
  2286. introduced in Section~\ref{sec:partial-evaluation}.
  2287. \begin{exercise}\label{ex:pe-Rvar}
  2288. \normalfont
  2289. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2290. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2291. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2292. and variables to the \LangInt{} language, so you will need to add cases for
  2293. them in the \code{pe-exp} function. Once complete, add the partial
  2294. evaluation pass to the front of your compiler and make sure that your
  2295. compiler still passes all of the tests.
  2296. \end{exercise}
  2297. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2298. \begin{exercise}
  2299. \normalfont
  2300. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2301. \code{pe-add} auxiliary functions with functions that know more about
  2302. arithmetic. For example, your partial evaluator should translate
  2303. \[
  2304. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2305. \code{(+ 2 (read))}
  2306. \]
  2307. To accomplish this, the \code{pe-exp} function should produce output
  2308. in the form of the $\itm{residual}$ non-terminal of the following
  2309. grammar. The idea is that when processing an addition expression, we
  2310. can always produce either 1) an integer constant, 2) and addition
  2311. expression with an integer constant on the left-hand side but not the
  2312. right-hand side, or 3) or an addition expression in which neither
  2313. subexpression is a constant.
  2314. \[
  2315. \begin{array}{lcl}
  2316. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2317. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2318. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2319. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2320. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2321. \end{array}
  2322. \]
  2323. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2324. inputs are $\itm{residual}$ expressions and they should return
  2325. $\itm{residual}$ expressions. Once the improvements are complete,
  2326. make sure that your compiler still passes all of the tests. After
  2327. all, fast code is useless if it produces incorrect results!
  2328. \end{exercise}
  2329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2330. \chapter{Register Allocation}
  2331. \label{ch:register-allocation-r1}
  2332. \index{register allocation}
  2333. In Chapter~\ref{ch:int-exp} we learned how to store variables on the
  2334. stack. In this Chapter we learn how to improve the performance of the
  2335. generated code by placing some variables into registers. The CPU can
  2336. access a register in a single cycle, whereas accessing the stack can
  2337. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2338. serves as a running example. The source program is on the left and the
  2339. output of instruction selection is on the right. The program is almost
  2340. in the x86 assembly language but it still uses variables.
  2341. \begin{figure}
  2342. \begin{minipage}{0.45\textwidth}
  2343. Example \LangVar{} program:
  2344. % s0_28.rkt
  2345. \begin{lstlisting}
  2346. (let ([v 1])
  2347. (let ([w 42])
  2348. (let ([x (+ v 7)])
  2349. (let ([y x])
  2350. (let ([z (+ x w)])
  2351. (+ z (- y)))))))
  2352. \end{lstlisting}
  2353. \end{minipage}
  2354. \begin{minipage}{0.45\textwidth}
  2355. After instruction selection:
  2356. \begin{lstlisting}
  2357. locals-types:
  2358. x : Integer, y : Integer,
  2359. z : Integer, t : Integer,
  2360. v : Integer, w : Integer
  2361. start:
  2362. movq $1, v
  2363. movq $42, w
  2364. movq v, x
  2365. addq $7, x
  2366. movq x, y
  2367. movq x, z
  2368. addq w, z
  2369. movq y, t
  2370. negq t
  2371. movq z, %rax
  2372. addq t, %rax
  2373. jmp conclusion
  2374. \end{lstlisting}
  2375. \end{minipage}
  2376. \caption{A running example for register allocation.}
  2377. \label{fig:reg-eg}
  2378. \end{figure}
  2379. The goal of register allocation is to fit as many variables into
  2380. registers as possible. Some programs have more variables than
  2381. registers so we cannot always map each variable to a different
  2382. register. Fortunately, it is common for different variables to be
  2383. needed during different periods of time during program execution, and
  2384. in such cases several variables can be mapped to the same register.
  2385. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2386. After the variable \code{x} is moved to \code{z} it is no longer
  2387. needed. Variable \code{z}, on the other hand, is used only after this
  2388. point, so \code{x} and \code{z} could share the same register. The
  2389. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2390. where a variable is needed. Once we have that information, we compute
  2391. which variables are needed at the same time, i.e., which ones
  2392. \emph{interfere} with each other, and represent this relation as an
  2393. undirected graph whose vertices are variables and edges indicate when
  2394. two variables interfere (Section~\ref{sec:build-interference}). We
  2395. then model register allocation as a graph coloring problem
  2396. (Section~\ref{sec:graph-coloring}).
  2397. If we run out of registers despite these efforts, we place the
  2398. remaining variables on the stack, similar to what we did in
  2399. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2400. for assigning a variable to a stack location. The decision to spill a
  2401. variable is handled as part of the graph coloring process
  2402. (Section~\ref{sec:graph-coloring}).
  2403. We make the simplifying assumption that each variable is assigned to
  2404. one location (a register or stack address). A more sophisticated
  2405. approach is to assign a variable to one or more locations in different
  2406. regions of the program. For example, if a variable is used many times
  2407. in short sequence and then only used again after many other
  2408. instructions, it could be more efficient to assign the variable to a
  2409. register during the initial sequence and then move it to the stack for
  2410. the rest of its lifetime. We refer the interested reader to
  2411. \citet{Cooper:2011aa} for more information about that approach.
  2412. % discuss prioritizing variables based on how much they are used.
  2413. \section{Registers and Calling Conventions}
  2414. \label{sec:calling-conventions}
  2415. \index{calling conventions}
  2416. As we perform register allocation, we need to be aware of the
  2417. \emph{calling conventions} \index{calling conventions} that govern how
  2418. functions calls are performed in x86.
  2419. %
  2420. Even though \LangVar{} does not include programmer-defined functions,
  2421. our generated code includes a \code{main} function that is called by
  2422. the operating system and our generated code contains calls to the
  2423. \code{read\_int} function.
  2424. Function calls require coordination between two pieces of code that
  2425. may be written by different programmers or generated by different
  2426. compilers. Here we follow the System V calling conventions that are
  2427. used by the GNU C compiler on Linux and
  2428. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2429. %
  2430. The calling conventions include rules about how functions share the
  2431. use of registers. In particular, the caller is responsible for freeing
  2432. up some registers prior to the function call for use by the callee.
  2433. These are called the \emph{caller-saved registers}
  2434. \index{caller-saved registers}
  2435. and they are
  2436. \begin{lstlisting}
  2437. rax rcx rdx rsi rdi r8 r9 r10 r11
  2438. \end{lstlisting}
  2439. On the other hand, the callee is responsible for preserving the values
  2440. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2441. which are
  2442. \begin{lstlisting}
  2443. rsp rbp rbx r12 r13 r14 r15
  2444. \end{lstlisting}
  2445. We can think about this caller/callee convention from two points of
  2446. view, the caller view and the callee view:
  2447. \begin{itemize}
  2448. \item The caller should assume that all the caller-saved registers get
  2449. overwritten with arbitrary values by the callee. On the other hand,
  2450. the caller can safely assume that all the callee-saved registers
  2451. contain the same values after the call that they did before the
  2452. call.
  2453. \item The callee can freely use any of the caller-saved registers.
  2454. However, if the callee wants to use a callee-saved register, the
  2455. callee must arrange to put the original value back in the register
  2456. prior to returning to the caller. This can be accomplished by saving
  2457. the value to the stack in the prelude of the function and restoring
  2458. the value in the conclusion of the function.
  2459. \end{itemize}
  2460. In x86, registers are also used for passing arguments to a function
  2461. and for the return value. In particular, the first six arguments to a
  2462. function are passed in the following six registers, in this order.
  2463. \begin{lstlisting}
  2464. rdi rsi rdx rcx r8 r9
  2465. \end{lstlisting}
  2466. If there are more than six arguments, then the convention is to use
  2467. space on the frame of the caller for the rest of the
  2468. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2469. need more than six arguments. For now, the only function we care about
  2470. is \code{read\_int} and it takes zero arguments.
  2471. %
  2472. The register \code{rax} is used for the return value of a function.
  2473. The next question is how these calling conventions impact register
  2474. allocation. Consider the \LangVar{} program in
  2475. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2476. example from the caller point of view and then from the callee point
  2477. of view.
  2478. The program makes two calls to the \code{read} function. Also, the
  2479. variable \code{x} is in-use during the second call to \code{read}, so
  2480. we need to make sure that the value in \code{x} does not get
  2481. accidentally wiped out by the call to \code{read}. One obvious
  2482. approach is to save all the values in caller-saved registers to the
  2483. stack prior to each function call, and restore them after each
  2484. call. That way, if the register allocator chooses to assign \code{x}
  2485. to a caller-saved register, its value will be preserved across the
  2486. call to \code{read}. However, saving and restoring to the stack is
  2487. relatively slow. If \code{x} is not used many times, it may be better
  2488. to assign \code{x} to a stack location in the first place. Or better
  2489. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2490. register, then it won't need to be saved and restored during function
  2491. calls.
  2492. The approach that we recommend for variables that are in-use during a
  2493. function call is to either assign them to callee-saved registers or to
  2494. spill them to the stack. On the other hand, for variables that are not
  2495. in-use during a function call, we try the following alternatives in
  2496. order 1) look for an available caller-saved register (to leave room
  2497. for other variables in the callee-saved register), 2) look for a
  2498. callee-saved register, and 3) spill the variable to the stack.
  2499. It is straightforward to implement this approach in a graph coloring
  2500. register allocator. First, we know which variables are in-use during
  2501. every function call because we compute that information for every
  2502. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2503. build the interference graph (Section~\ref{sec:build-interference}),
  2504. we can place an edge between each of these variables and the
  2505. caller-saved registers in the interference graph. This will prevent
  2506. the graph coloring algorithm from assigning those variables to
  2507. caller-saved registers.
  2508. Returning to the example in
  2509. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2510. generated x86 code on the right-hand side, focusing on the
  2511. \code{start} block. Notice that variable \code{x} is assigned to
  2512. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2513. place during the second call to \code{read\_int}. Next, notice that
  2514. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2515. because there are no function calls in the remainder of the block.
  2516. Next we analyze the example from the callee point of view, focusing on
  2517. the prelude and conclusion of the \code{main} function. As usual the
  2518. prelude begins with saving the \code{rbp} register to the stack and
  2519. setting the \code{rbp} to the current stack pointer. We now know why
  2520. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2521. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2522. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2523. (\code{x}). The other callee-saved registers are not saved in the
  2524. prelude because they are not used. The prelude subtracts 8 bytes from
  2525. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2526. \code{start} block. Shifting attention to the \code{conclusion}, we
  2527. see that \code{rbx} is restored from the stack with a \code{popq}
  2528. instruction. \index{prelude}\index{conclusion}
  2529. \begin{figure}[tp]
  2530. \begin{minipage}{0.45\textwidth}
  2531. Example \LangVar{} program:
  2532. %s0_14.rkt
  2533. \begin{lstlisting}
  2534. (let ([x (read)])
  2535. (let ([y (read)])
  2536. (+ (+ x y) 42)))
  2537. \end{lstlisting}
  2538. \end{minipage}
  2539. \begin{minipage}{0.45\textwidth}
  2540. Generated x86 assembly:
  2541. \begin{lstlisting}
  2542. start:
  2543. callq read_int
  2544. movq %rax, %rbx
  2545. callq read_int
  2546. movq %rax, %rcx
  2547. addq %rcx, %rbx
  2548. movq %rbx, %rax
  2549. addq $42, %rax
  2550. jmp _conclusion
  2551. .globl main
  2552. main:
  2553. pushq %rbp
  2554. movq %rsp, %rbp
  2555. pushq %rbx
  2556. subq $8, %rsp
  2557. jmp start
  2558. conclusion:
  2559. addq $8, %rsp
  2560. popq %rbx
  2561. popq %rbp
  2562. retq
  2563. \end{lstlisting}
  2564. \end{minipage}
  2565. \caption{An example with function calls.}
  2566. \label{fig:example-calling-conventions}
  2567. \end{figure}
  2568. \clearpage
  2569. \section{Liveness Analysis}
  2570. \label{sec:liveness-analysis-r1}
  2571. \index{liveness analysis}
  2572. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2573. is, it discovers which variables are in-use in different regions of a
  2574. program.
  2575. %
  2576. A variable or register is \emph{live} at a program point if its
  2577. current value is used at some later point in the program. We
  2578. refer to variables and registers collectively as \emph{locations}.
  2579. %
  2580. Consider the following code fragment in which there are two writes to
  2581. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2582. \begin{center}
  2583. \begin{minipage}{0.96\textwidth}
  2584. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2585. movq $5, a
  2586. movq $30, b
  2587. movq a, c
  2588. movq $10, b
  2589. addq b, c
  2590. \end{lstlisting}
  2591. \end{minipage}
  2592. \end{center}
  2593. The answer is no because \code{a} is live from line 1 to 3 and
  2594. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2595. line 2 is never used because it is overwritten (line 4) before the
  2596. next read (line 5).
  2597. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2598. \small
  2599. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2600. A \emph{set} is an unordered collection of elements without duplicates.
  2601. \index{set}
  2602. \begin{description}
  2603. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2604. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2605. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2606. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2607. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2608. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2609. \end{description}
  2610. \end{tcolorbox}
  2611. \end{wrapfigure}
  2612. The live locations can be computed by traversing the instruction
  2613. sequence back to front (i.e., backwards in execution order). Let
  2614. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2615. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2616. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2617. locations before instruction $I_k$. The live locations after an
  2618. instruction are always the same as the live locations before the next
  2619. instruction. \index{live-after} \index{live-before}
  2620. \begin{equation} \label{eq:live-after-before-next}
  2621. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2622. \end{equation}
  2623. To start things off, there are no live locations after the last
  2624. instruction, so
  2625. \begin{equation}\label{eq:live-last-empty}
  2626. L_{\mathsf{after}}(n) = \emptyset
  2627. \end{equation}
  2628. We then apply the following rule repeatedly, traversing the
  2629. instruction sequence back to front.
  2630. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2631. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2632. \end{equation}
  2633. where $W(k)$ are the locations written to by instruction $I_k$ and
  2634. $R(k)$ are the locations read by instruction $I_k$.
  2635. There is a special case for \code{jmp} instructions. The locations
  2636. that are live before a \code{jmp} should be the locations in
  2637. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2638. maintaining an alist named \code{label->live} that maps each label to
  2639. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2640. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2641. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2642. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2643. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2644. Let us walk through the above example, applying these formulas
  2645. starting with the instruction on line 5. We collect the answers in
  2646. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2647. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2648. instruction (formula~\ref{eq:live-last-empty}). The
  2649. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2650. because it reads from variables \code{b} and \code{c}
  2651. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2652. \[
  2653. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2654. \]
  2655. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2656. the live-before set from line 5 to be the live-after set for this
  2657. instruction (formula~\ref{eq:live-after-before-next}).
  2658. \[
  2659. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2660. \]
  2661. This move instruction writes to \code{b} and does not read from any
  2662. variables, so we have the following live-before set
  2663. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2664. \[
  2665. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2666. \]
  2667. The live-before for instruction \code{movq a, c}
  2668. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2669. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2670. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2671. variable that is not live and does not read from a variable.
  2672. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2673. because it writes to variable \code{a}.
  2674. \begin{figure}[tbp]
  2675. \begin{minipage}{0.45\textwidth}
  2676. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2677. movq $5, a
  2678. movq $30, b
  2679. movq a, c
  2680. movq $10, b
  2681. addq b, c
  2682. \end{lstlisting}
  2683. \end{minipage}
  2684. \vrule\hspace{10pt}
  2685. \begin{minipage}{0.45\textwidth}
  2686. \begin{align*}
  2687. L_{\mathsf{before}}(1)= \emptyset,
  2688. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2689. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2690. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2691. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2692. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2693. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2694. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2695. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2696. L_{\mathsf{after}}(5)= \emptyset
  2697. \end{align*}
  2698. \end{minipage}
  2699. \caption{Example output of liveness analysis on a short example.}
  2700. \label{fig:liveness-example-0}
  2701. \end{figure}
  2702. \begin{exercise}\normalfont
  2703. Perform liveness analysis on the running example in
  2704. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2705. sets for each instruction. Compare your answers to the solution
  2706. shown in Figure~\ref{fig:live-eg}.
  2707. \end{exercise}
  2708. \begin{figure}[tp]
  2709. \hspace{20pt}
  2710. \begin{minipage}{0.45\textwidth}
  2711. \begin{lstlisting}
  2712. |$\{\ttm{rsp}\}$|
  2713. movq $1, v
  2714. |$\{\ttm{v},\ttm{rsp}\}$|
  2715. movq $42, w
  2716. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2717. movq v, x
  2718. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2719. addq $7, x
  2720. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2721. movq x, y
  2722. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2723. movq x, z
  2724. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2725. addq w, z
  2726. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2727. movq y, t
  2728. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2729. negq t
  2730. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2731. movq z, %rax
  2732. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2733. addq t, %rax
  2734. |$\{\ttm{rax},\ttm{rsp}\}$|
  2735. jmp conclusion
  2736. \end{lstlisting}
  2737. \end{minipage}
  2738. \caption{The running example annotated with live-after sets.}
  2739. \label{fig:live-eg}
  2740. \end{figure}
  2741. \begin{exercise}\normalfont
  2742. Implement the \code{uncover-live} pass. Store the sequence of
  2743. live-after sets in the $\itm{info}$ field of the \code{Block}
  2744. structure.
  2745. %
  2746. We recommend creating an auxiliary function that takes a list of
  2747. instructions and an initial live-after set (typically empty) and
  2748. returns the list of live-after sets.
  2749. %
  2750. We also recommend creating auxiliary functions to 1) compute the set
  2751. of locations that appear in an \Arg{}, 2) compute the locations read
  2752. by an instruction (the $R$ function), and 3) the locations written by
  2753. an instruction (the $W$ function). The \code{callq} instruction should
  2754. include all of the caller-saved registers in its write-set $W$ because
  2755. the calling convention says that those registers may be written to
  2756. during the function call. Likewise, the \code{callq} instruction
  2757. should include the appropriate argument-passing registers in its
  2758. read-set $R$, depending on the arity of the function being
  2759. called. (This is why the abstract syntax for \code{callq} includes the
  2760. arity.)
  2761. \end{exercise}
  2762. \section{Building the Interference Graph}
  2763. \label{sec:build-interference}
  2764. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2765. \small
  2766. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2767. A \emph{graph} is a collection of vertices and edges where each
  2768. edge connects two vertices. A graph is \emph{directed} if each
  2769. edge points from a source to a target. Otherwise the graph is
  2770. \emph{undirected}.
  2771. \index{graph}\index{directed graph}\index{undirected graph}
  2772. \begin{description}
  2773. %% We currently don't use directed graphs. We instead use
  2774. %% directed multi-graphs. -Jeremy
  2775. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2776. %% directed graph from a list of edges. Each edge is a list
  2777. %% containing the source and target vertex.
  2778. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2779. undirected graph from a list of edges. Each edge is represented by
  2780. a list containing two vertices.
  2781. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2782. inserts a vertex into the graph.
  2783. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2784. inserts an edge between the two vertices into the graph.
  2785. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2786. returns a sequence of all the neighbors of the given vertex.
  2787. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2788. returns a sequence of all the vertices in the graph.
  2789. \end{description}
  2790. \end{tcolorbox}
  2791. \end{wrapfigure}
  2792. Based on the liveness analysis, we know where each location is live.
  2793. However, during register allocation, we need to answer questions of
  2794. the specific form: are locations $u$ and $v$ live at the same time?
  2795. (And therefore cannot be assigned to the same register.) To make this
  2796. question more efficient to answer, we create an explicit data
  2797. structure, an \emph{interference graph}\index{interference graph}. An
  2798. interference graph is an undirected graph that has an edge between two
  2799. locations if they are live at the same time, that is, if they
  2800. interfere with each other.
  2801. An obvious way to compute the interference graph is to look at the set
  2802. of live location between each instruction and add an edge to the graph
  2803. for every pair of variables in the same set. This approach is less
  2804. than ideal for two reasons. First, it can be expensive because it
  2805. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2806. locations. Second, in the special case where two locations hold the
  2807. same value (because one was assigned to the other), they can be live
  2808. at the same time without interfering with each other.
  2809. A better way to compute the interference graph is to focus on
  2810. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2811. must not overwrite something in a live location. So for each
  2812. instruction, we create an edge between the locations being written to
  2813. and the live locations. (Except that one should not create self
  2814. edges.) Note that for the \key{callq} instruction, we consider all of
  2815. the caller-saved registers as being written to, so an edge is added
  2816. between every live variable and every caller-saved register. For
  2817. \key{movq}, we deal with the above-mentioned special case by not
  2818. adding an edge between a live variable $v$ and the destination if $v$
  2819. matches the source. So we have the following two rules.
  2820. \begin{enumerate}
  2821. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2822. $d$, then add the edge $(d,v)$ for every $v \in
  2823. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2824. \item For any other instruction $I_k$, for every $d \in W(k)$
  2825. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2826. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2827. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2828. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2829. %% \item If instruction $I_k$ is of the form \key{callq}
  2830. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2831. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2832. \end{enumerate}
  2833. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2834. the above rules to each instruction. We highlight a few of the
  2835. instructions. The first instruction is \lstinline{movq $1, v} and the
  2836. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2837. interferes with \code{rsp}.
  2838. %
  2839. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2840. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2841. interferes with \ttm{w} and \ttm{rsp}.
  2842. %
  2843. The next instruction is \lstinline{movq x, y} and the live-after set
  2844. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2845. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2846. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2847. same value. Figure~\ref{fig:interference-results} lists the
  2848. interference results for all of the instructions and the resulting
  2849. interference graph is shown in Figure~\ref{fig:interfere}.
  2850. \begin{figure}[tbp]
  2851. \begin{quote}
  2852. \begin{tabular}{ll}
  2853. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2854. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2855. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2856. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2857. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2858. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2859. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2860. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2861. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2862. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2863. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2864. \lstinline!jmp conclusion!& no interference.
  2865. \end{tabular}
  2866. \end{quote}
  2867. \caption{Interference results for the running example.}
  2868. \label{fig:interference-results}
  2869. \end{figure}
  2870. \begin{figure}[tbp]
  2871. \large
  2872. \[
  2873. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2874. \node (rax) at (0,0) {$\ttm{rax}$};
  2875. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2876. \node (t1) at (0,2) {$\ttm{t}$};
  2877. \node (z) at (3,2) {$\ttm{z}$};
  2878. \node (x) at (6,2) {$\ttm{x}$};
  2879. \node (y) at (3,0) {$\ttm{y}$};
  2880. \node (w) at (6,0) {$\ttm{w}$};
  2881. \node (v) at (9,0) {$\ttm{v}$};
  2882. \draw (t1) to (rax);
  2883. \draw (t1) to (z);
  2884. \draw (z) to (y);
  2885. \draw (z) to (w);
  2886. \draw (x) to (w);
  2887. \draw (y) to (w);
  2888. \draw (v) to (w);
  2889. \draw (v) to (rsp);
  2890. \draw (w) to (rsp);
  2891. \draw (x) to (rsp);
  2892. \draw (y) to (rsp);
  2893. \path[-.,bend left=15] (z) edge node {} (rsp);
  2894. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2895. \draw (rax) to (rsp);
  2896. \end{tikzpicture}
  2897. \]
  2898. \caption{The interference graph of the example program.}
  2899. \label{fig:interfere}
  2900. \end{figure}
  2901. %% Our next concern is to choose a data structure for representing the
  2902. %% interference graph. There are many choices for how to represent a
  2903. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2904. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2905. %% data structure is to study the algorithm that uses the data structure,
  2906. %% determine what operations need to be performed, and then choose the
  2907. %% data structure that provide the most efficient implementations of
  2908. %% those operations. Often times the choice of data structure can have an
  2909. %% effect on the time complexity of the algorithm, as it does here. If
  2910. %% you skim the next section, you will see that the register allocation
  2911. %% algorithm needs to ask the graph for all of its vertices and, given a
  2912. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2913. %% correct choice of graph representation is that of an adjacency
  2914. %% list. There are helper functions in \code{utilities.rkt} for
  2915. %% representing graphs using the adjacency list representation:
  2916. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2917. %% (Appendix~\ref{appendix:utilities}).
  2918. %% %
  2919. %% \margincomment{\footnotesize To do: change to use the
  2920. %% Racket graph library. \\ --Jeremy}
  2921. %% %
  2922. %% In particular, those functions use a hash table to map each vertex to
  2923. %% the set of adjacent vertices, and the sets are represented using
  2924. %% Racket's \key{set}, which is also a hash table.
  2925. \begin{exercise}\normalfont
  2926. Implement the compiler pass named \code{build-interference} according
  2927. to the algorithm suggested above. We recommend using the \code{graph}
  2928. package to create and inspect the interference graph. The output
  2929. graph of this pass should be stored in the $\itm{info}$ field of the
  2930. program, under the key \code{conflicts}.
  2931. \end{exercise}
  2932. \section{Graph Coloring via Sudoku}
  2933. \label{sec:graph-coloring}
  2934. \index{graph coloring}
  2935. \index{Sudoku}
  2936. \index{color}
  2937. We come to the main event, mapping variables to registers and stack
  2938. locations. Variables that interfere with each other must be mapped to
  2939. different locations. In terms of the interference graph, this means
  2940. that adjacent vertices must be mapped to different locations. If we
  2941. think of locations as colors, the register allocation problem becomes
  2942. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2943. The reader may be more familiar with the graph coloring problem than he
  2944. or she realizes; the popular game of Sudoku is an instance of the
  2945. graph coloring problem. The following describes how to build a graph
  2946. out of an initial Sudoku board.
  2947. \begin{itemize}
  2948. \item There is one vertex in the graph for each Sudoku square.
  2949. \item There is an edge between two vertices if the corresponding squares
  2950. are in the same row, in the same column, or if the squares are in
  2951. the same $3\times 3$ region.
  2952. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2953. \item Based on the initial assignment of numbers to squares in the
  2954. Sudoku board, assign the corresponding colors to the corresponding
  2955. vertices in the graph.
  2956. \end{itemize}
  2957. If you can color the remaining vertices in the graph with the nine
  2958. colors, then you have also solved the corresponding game of Sudoku.
  2959. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2960. the corresponding graph with colored vertices. We map the Sudoku
  2961. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2962. sampling of the vertices (the colored ones) because showing edges for
  2963. all of the vertices would make the graph unreadable.
  2964. \begin{figure}[tbp]
  2965. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2966. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2967. \caption{A Sudoku game board and the corresponding colored graph.}
  2968. \label{fig:sudoku-graph}
  2969. \end{figure}
  2970. It turns out that some techniques for playing Sudoku correspond to
  2971. heuristics used in graph coloring algorithms. For example, one of the
  2972. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  2973. a process of elimination to determine what numbers are no longer
  2974. available for a square and write down those numbers in the square
  2975. (writing very small). For example, if the number $1$ is assigned to a
  2976. square, then write the pencil mark $1$ in all the squares in the same
  2977. row, column, and region.
  2978. %
  2979. The Pencil Marks technique corresponds to the notion of
  2980. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  2981. saturation of a vertex, in Sudoku terms, is the set of numbers that
  2982. are no longer available. In graph terminology, we have the following
  2983. definition:
  2984. \begin{equation*}
  2985. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2986. \text{ and } \mathrm{color}(v) = c \}
  2987. \end{equation*}
  2988. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2989. edge with $u$.
  2990. Using the Pencil Marks technique leads to a simple strategy for
  2991. filling in numbers: if there is a square with only one possible number
  2992. left, then choose that number! But what if there are no squares with
  2993. only one possibility left? One brute-force approach is to try them
  2994. all: choose the first one and if it ultimately leads to a solution,
  2995. great. If not, backtrack and choose the next possibility. One good
  2996. thing about Pencil Marks is that it reduces the degree of branching in
  2997. the search tree. Nevertheless, backtracking can be horribly time
  2998. consuming. One way to reduce the amount of backtracking is to use the
  2999. most-constrained-first heuristic. That is, when choosing a square,
  3000. always choose one with the fewest possibilities left (the vertex with
  3001. the highest saturation). The idea is that choosing highly constrained
  3002. squares earlier rather than later is better because later on there may
  3003. not be any possibilities left in the highly saturated squares.
  3004. However, register allocation is easier than Sudoku because the
  3005. register allocator can map variables to stack locations when the
  3006. registers run out. Thus, it makes sense to replace backtracking with
  3007. greedy search: make the best choice at the time and keep going. We
  3008. still wish to minimize the number of colors needed, so we use the
  3009. most-constrained-first heuristic in the greedy search.
  3010. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3011. algorithm for register allocation based on saturation and the
  3012. most-constrained-first heuristic. It is roughly equivalent to the
  3013. DSATUR
  3014. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3015. as in Sudoku, the algorithm represents colors with integers. The
  3016. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3017. for register allocation. The integers $k$ and larger correspond to
  3018. stack locations. The registers that are not used for register
  3019. allocation, such as \code{rax}, are assigned to negative integers. In
  3020. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3021. %% One might wonder why we include registers at all in the liveness
  3022. %% analysis and interference graph, for example, we never allocate a
  3023. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3024. %% leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  3025. %% to use register for passing arguments to functions, it will be
  3026. %% necessary for those registers to appear in the interference graph
  3027. %% because those registers will also be assigned to variables, and we
  3028. %% don't want those two uses to encroach on each other. Regarding
  3029. %% registers such as \code{rax} and \code{rsp} that are not used for
  3030. %% variables, we could omit them from the interference graph but that
  3031. %% would require adding special cases to our algorithm, which would
  3032. %% complicate the logic for little gain.
  3033. \begin{figure}[btp]
  3034. \centering
  3035. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3036. Algorithm: DSATUR
  3037. Input: a graph |$G$|
  3038. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3039. |$W \gets \mathrm{vertices}(G)$|
  3040. while |$W \neq \emptyset$| do
  3041. pick a vertex |$u$| from |$W$| with the highest saturation,
  3042. breaking ties randomly
  3043. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3044. |$\mathrm{color}[u] \gets c$|
  3045. |$W \gets W - \{u\}$|
  3046. \end{lstlisting}
  3047. \caption{The saturation-based greedy graph coloring algorithm.}
  3048. \label{fig:satur-algo}
  3049. \end{figure}
  3050. With the DSATUR algorithm in hand, let us return to the running
  3051. example and consider how to color the interference graph in
  3052. Figure~\ref{fig:interfere}.
  3053. %
  3054. We start by assigning the register nodes to their own color. For
  3055. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3056. assigned $-2$. The variables are not yet colored, so they are
  3057. annotated with a dash. We then update the saturation for vertices that
  3058. are adjacent to a register, obtaining the following annotated
  3059. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3060. it interferes with both \code{rax} and \code{rsp}.
  3061. \[
  3062. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3063. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3064. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3065. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3066. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3067. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3068. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3069. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3070. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3071. \draw (t1) to (rax);
  3072. \draw (t1) to (z);
  3073. \draw (z) to (y);
  3074. \draw (z) to (w);
  3075. \draw (x) to (w);
  3076. \draw (y) to (w);
  3077. \draw (v) to (w);
  3078. \draw (v) to (rsp);
  3079. \draw (w) to (rsp);
  3080. \draw (x) to (rsp);
  3081. \draw (y) to (rsp);
  3082. \path[-.,bend left=15] (z) edge node {} (rsp);
  3083. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3084. \draw (rax) to (rsp);
  3085. \end{tikzpicture}
  3086. \]
  3087. The algorithm says to select a maximally saturated vertex. So we pick
  3088. $\ttm{t}$ and color it with the first available integer, which is
  3089. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3090. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3091. \[
  3092. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3093. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3094. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3095. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3096. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3097. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3098. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3099. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3100. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3101. \draw (t1) to (rax);
  3102. \draw (t1) to (z);
  3103. \draw (z) to (y);
  3104. \draw (z) to (w);
  3105. \draw (x) to (w);
  3106. \draw (y) to (w);
  3107. \draw (v) to (w);
  3108. \draw (v) to (rsp);
  3109. \draw (w) to (rsp);
  3110. \draw (x) to (rsp);
  3111. \draw (y) to (rsp);
  3112. \path[-.,bend left=15] (z) edge node {} (rsp);
  3113. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3114. \draw (rax) to (rsp);
  3115. \end{tikzpicture}
  3116. \]
  3117. We repeat the process, selecting the next maximally saturated vertex,
  3118. which is \code{z}, and color it with the first available number, which
  3119. is $1$. We add $1$ to the saturation for the neighboring vertices
  3120. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3121. \[
  3122. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3123. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3124. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3125. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3126. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3127. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3128. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3129. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3130. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3131. \draw (t1) to (rax);
  3132. \draw (t1) to (z);
  3133. \draw (z) to (y);
  3134. \draw (z) to (w);
  3135. \draw (x) to (w);
  3136. \draw (y) to (w);
  3137. \draw (v) to (w);
  3138. \draw (v) to (rsp);
  3139. \draw (w) to (rsp);
  3140. \draw (x) to (rsp);
  3141. \draw (y) to (rsp);
  3142. \path[-.,bend left=15] (z) edge node {} (rsp);
  3143. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3144. \draw (rax) to (rsp);
  3145. \end{tikzpicture}
  3146. \]
  3147. The most saturated vertices are now \code{w} and \code{y}. We color
  3148. \code{w} with the first available color, which is $0$.
  3149. \[
  3150. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3151. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3152. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3153. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3154. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3155. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3156. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3157. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3158. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3159. \draw (t1) to (rax);
  3160. \draw (t1) to (z);
  3161. \draw (z) to (y);
  3162. \draw (z) to (w);
  3163. \draw (x) to (w);
  3164. \draw (y) to (w);
  3165. \draw (v) to (w);
  3166. \draw (v) to (rsp);
  3167. \draw (w) to (rsp);
  3168. \draw (x) to (rsp);
  3169. \draw (y) to (rsp);
  3170. \path[-.,bend left=15] (z) edge node {} (rsp);
  3171. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3172. \draw (rax) to (rsp);
  3173. \end{tikzpicture}
  3174. \]
  3175. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3176. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3177. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3178. and \code{z}, whose colors are $0$ and $1$ respectively.
  3179. \[
  3180. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3181. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3182. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3183. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3184. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3185. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3186. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3187. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3188. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3189. \draw (t1) to (rax);
  3190. \draw (t1) to (z);
  3191. \draw (z) to (y);
  3192. \draw (z) to (w);
  3193. \draw (x) to (w);
  3194. \draw (y) to (w);
  3195. \draw (v) to (w);
  3196. \draw (v) to (rsp);
  3197. \draw (w) to (rsp);
  3198. \draw (x) to (rsp);
  3199. \draw (y) to (rsp);
  3200. \path[-.,bend left=15] (z) edge node {} (rsp);
  3201. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3202. \draw (rax) to (rsp);
  3203. \end{tikzpicture}
  3204. \]
  3205. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3206. \[
  3207. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3208. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3209. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3210. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3211. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3212. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3213. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3214. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3215. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3216. \draw (t1) to (rax);
  3217. \draw (t1) to (z);
  3218. \draw (z) to (y);
  3219. \draw (z) to (w);
  3220. \draw (x) to (w);
  3221. \draw (y) to (w);
  3222. \draw (v) to (w);
  3223. \draw (v) to (rsp);
  3224. \draw (w) to (rsp);
  3225. \draw (x) to (rsp);
  3226. \draw (y) to (rsp);
  3227. \path[-.,bend left=15] (z) edge node {} (rsp);
  3228. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3229. \draw (rax) to (rsp);
  3230. \end{tikzpicture}
  3231. \]
  3232. In the last step of the algorithm, we color \code{x} with $1$.
  3233. \[
  3234. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3235. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3236. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3237. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3238. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3239. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3240. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3241. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3242. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3243. \draw (t1) to (rax);
  3244. \draw (t1) to (z);
  3245. \draw (z) to (y);
  3246. \draw (z) to (w);
  3247. \draw (x) to (w);
  3248. \draw (y) to (w);
  3249. \draw (v) to (w);
  3250. \draw (v) to (rsp);
  3251. \draw (w) to (rsp);
  3252. \draw (x) to (rsp);
  3253. \draw (y) to (rsp);
  3254. \path[-.,bend left=15] (z) edge node {} (rsp);
  3255. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3256. \draw (rax) to (rsp);
  3257. \end{tikzpicture}
  3258. \]
  3259. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3260. \small
  3261. \begin{tcolorbox}[title=Priority Queue]
  3262. A \emph{priority queue} is a collection of items in which the
  3263. removal of items is governed by priority. In a ``min'' queue,
  3264. lower priority items are removed first. An implementation is in
  3265. \code{priority\_queue.rkt} of the support code. \index{priority
  3266. queue} \index{minimum priority queue}
  3267. \begin{description}
  3268. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3269. priority queue that uses the $\itm{cmp}$ predicate to determine
  3270. whether its first argument has lower or equal priority to its
  3271. second argument.
  3272. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3273. items in the queue.
  3274. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3275. the item into the queue and returns a handle for the item in the
  3276. queue.
  3277. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3278. the lowest priority.
  3279. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3280. notifies the queue that the priority has decreased for the item
  3281. associated with the given handle.
  3282. \end{description}
  3283. \end{tcolorbox}
  3284. \end{wrapfigure}
  3285. We recommend creating an auxiliary function named \code{color-graph}
  3286. that takes an interference graph and a list of all the variables in
  3287. the program. This function should return a mapping of variables to
  3288. their colors (represented as natural numbers). By creating this helper
  3289. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3290. when we add support for functions.
  3291. To prioritize the processing of highly saturated nodes inside the
  3292. \code{color-graph} function, we recommend using the priority queue
  3293. data structure (see the side bar on the right). In addition, you will
  3294. need to maintain a mapping from variables to their ``handles'' in the
  3295. priority queue so that you can notify the priority queue when their
  3296. saturation changes.
  3297. With the coloring complete, we finalize the assignment of variables to
  3298. registers and stack locations. We map the first $k$ colors to the $k$
  3299. registers and the rest of the colors to stack locations. Suppose for
  3300. the moment that we have just one register to use for register
  3301. allocation, \key{rcx}. Then we have the following map from colors to
  3302. locations.
  3303. \[
  3304. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3305. \]
  3306. Composing this mapping with the coloring, we arrive at the following
  3307. assignment of variables to locations.
  3308. \begin{gather*}
  3309. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3310. \ttm{w} \mapsto \key{\%rcx}, \,
  3311. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3312. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3313. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3314. \ttm{t} \mapsto \key{\%rcx} \}
  3315. \end{gather*}
  3316. Adapt the code from the \code{assign-homes} pass
  3317. (Section~\ref{sec:assign-r1}) to replace the variables with their
  3318. assigned location. Applying the above assignment to our running
  3319. example, on the left, yields the program on the right.
  3320. % why frame size of 32? -JGS
  3321. \begin{center}
  3322. \begin{minipage}{0.3\textwidth}
  3323. \begin{lstlisting}
  3324. movq $1, v
  3325. movq $42, w
  3326. movq v, x
  3327. addq $7, x
  3328. movq x, y
  3329. movq x, z
  3330. addq w, z
  3331. movq y, t
  3332. negq t
  3333. movq z, %rax
  3334. addq t, %rax
  3335. jmp conclusion
  3336. \end{lstlisting}
  3337. \end{minipage}
  3338. $\Rightarrow\qquad$
  3339. \begin{minipage}{0.45\textwidth}
  3340. \begin{lstlisting}
  3341. movq $1, -8(%rbp)
  3342. movq $42, %rcx
  3343. movq -8(%rbp), -8(%rbp)
  3344. addq $7, -8(%rbp)
  3345. movq -8(%rbp), -16(%rbp)
  3346. movq -8(%rbp), -8(%rbp)
  3347. addq %rcx, -8(%rbp)
  3348. movq -16(%rbp), %rcx
  3349. negq %rcx
  3350. movq -8(%rbp), %rax
  3351. addq %rcx, %rax
  3352. jmp conclusion
  3353. \end{lstlisting}
  3354. \end{minipage}
  3355. \end{center}
  3356. \begin{exercise}\normalfont
  3357. %
  3358. Implement the compiler pass \code{allocate-registers}.
  3359. %
  3360. Create five programs that exercise all of the register allocation
  3361. algorithm, including spilling variables to the stack.
  3362. %
  3363. Replace \code{assign-homes} in the list of \code{passes} in the
  3364. \code{run-tests.rkt} script with the three new passes:
  3365. \code{uncover-live}, \code{build-interference}, and
  3366. \code{allocate-registers}.
  3367. %
  3368. Temporarily remove the \code{print-x86} pass from the list of passes
  3369. and the call to \code{compiler-tests}.
  3370. %
  3371. Run the script to test the register allocator.
  3372. \end{exercise}
  3373. \section{Patch Instructions}
  3374. \label{sec:patch-instructions}
  3375. The remaining step in the compilation to x86 is to ensure that the
  3376. instructions have at most one argument that is a memory access.
  3377. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3378. is problematic. The fix is to first move \code{-8(\%rbp)}
  3379. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3380. %
  3381. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3382. problematic, but they can be fixed by simply deleting them. In
  3383. general, we recommend deleting all the trivial moves whose source and
  3384. destination are the same location.
  3385. %
  3386. The following is the output of \code{patch-instructions} on the
  3387. running example.
  3388. \begin{center}
  3389. \begin{minipage}{0.4\textwidth}
  3390. \begin{lstlisting}
  3391. movq $1, -8(%rbp)
  3392. movq $42, %rcx
  3393. movq -8(%rbp), -8(%rbp)
  3394. addq $7, -8(%rbp)
  3395. movq -8(%rbp), -16(%rbp)
  3396. movq -8(%rbp), -8(%rbp)
  3397. addq %rcx, -8(%rbp)
  3398. movq -16(%rbp), %rcx
  3399. negq %rcx
  3400. movq -8(%rbp), %rax
  3401. addq %rcx, %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. addq $7, -8(%rbp)
  3411. movq -8(%rbp), %rax
  3412. movq %rax, -16(%rbp)
  3413. addq %rcx, -8(%rbp)
  3414. movq -16(%rbp), %rcx
  3415. negq %rcx
  3416. movq -8(%rbp), %rax
  3417. addq %rcx, %rax
  3418. jmp conclusion
  3419. \end{lstlisting}
  3420. \end{minipage}
  3421. \end{center}
  3422. \begin{exercise}\normalfont
  3423. %
  3424. Implement the \code{patch-instructions} compiler pass.
  3425. %
  3426. Insert it after \code{allocate-registers} in the list of \code{passes}
  3427. in the \code{run-tests.rkt} script.
  3428. %
  3429. Run the script to test the \code{patch-instructions} pass.
  3430. \end{exercise}
  3431. \section{Print x86}
  3432. \label{sec:print-x86-reg-alloc}
  3433. \index{calling conventions}
  3434. \index{prelude}\index{conclusion}
  3435. Recall that the \code{print-x86} pass generates the prelude and
  3436. conclusion instructions to satisfy the x86 calling conventions
  3437. (Section~\ref{sec:calling-conventions}). With the addition of the
  3438. register allocator, the callee-saved registers used by the register
  3439. allocator must be saved in the prelude and restored in the conclusion.
  3440. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3441. of \code{X86Program} named \code{used-callee} that stores the set of
  3442. callee-saved registers that were assigned to variables. The
  3443. \code{print-x86} pass can then access this information to decide which
  3444. callee-saved registers need to be saved and restored.
  3445. %
  3446. When calculating the size of the frame to adjust the \code{rsp} in the
  3447. prelude, make sure to take into account the space used for saving the
  3448. callee-saved registers. Also, don't forget that the frame needs to be
  3449. a multiple of 16 bytes!
  3450. An overview of all of the passes involved in register allocation is
  3451. shown in Figure~\ref{fig:reg-alloc-passes}.
  3452. \begin{figure}[tbp]
  3453. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3454. \node (Rvar) at (0,2) {\large \LangVar{}};
  3455. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3456. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3457. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3458. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3459. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3460. \node (x86-4) at (9,-2) {\large \LangXASTInt{}};
  3461. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3462. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3463. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3464. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3465. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3466. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3467. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3468. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3469. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3470. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3471. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3472. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3473. \end{tikzpicture}
  3474. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3475. \label{fig:reg-alloc-passes}
  3476. \end{figure}
  3477. \begin{exercise}\normalfont
  3478. Update the \code{print-x86} pass as described in this section.
  3479. %
  3480. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3481. list of passes and the call to \code{compiler-tests}.
  3482. %
  3483. Run the script to test the complete compiler for \LangVar{} that
  3484. performs register allocation.
  3485. \end{exercise}
  3486. \section{Challenge: Move Biasing}
  3487. \label{sec:move-biasing}
  3488. \index{move biasing}
  3489. This section describes an enhancement to the register allocator for
  3490. students looking for an extra challenge or who have a deeper interest
  3491. in register allocation.
  3492. To motivate the need for move biasing we return to the running example
  3493. but this time use all of the general purpose registers. So we have
  3494. the following mapping of color numbers to registers.
  3495. \[
  3496. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3497. \]
  3498. Using the same assignment of variables to color numbers that was
  3499. produced by the register allocator described in the last section, we
  3500. get the following program.
  3501. \begin{center}
  3502. \begin{minipage}{0.3\textwidth}
  3503. \begin{lstlisting}
  3504. movq $1, v
  3505. movq $42, w
  3506. movq v, x
  3507. addq $7, x
  3508. movq x, y
  3509. movq x, z
  3510. addq w, z
  3511. movq y, t
  3512. negq t
  3513. movq z, %rax
  3514. addq t, %rax
  3515. jmp conclusion
  3516. \end{lstlisting}
  3517. \end{minipage}
  3518. $\Rightarrow\qquad$
  3519. \begin{minipage}{0.45\textwidth}
  3520. \begin{lstlisting}
  3521. movq $1, %rdx
  3522. movq $42, %rcx
  3523. movq %rdx, %rdx
  3524. addq $7, %rdx
  3525. movq %rdx, %rsi
  3526. movq %rdx, %rdx
  3527. addq %rcx, %rdx
  3528. movq %rsi, %rcx
  3529. negq %rcx
  3530. movq %rdx, %rax
  3531. addq %rcx, %rax
  3532. jmp conclusion
  3533. \end{lstlisting}
  3534. \end{minipage}
  3535. \end{center}
  3536. In the above output code there are two \key{movq} instructions that
  3537. can be removed because their source and target are the same. However,
  3538. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3539. register, we could instead remove three \key{movq} instructions. We
  3540. can accomplish this by taking into account which variables appear in
  3541. \key{movq} instructions with which other variables.
  3542. We say that two variables $p$ and $q$ are \emph{move
  3543. related}\index{move related} if they participate together in a
  3544. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3545. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3546. for a variable, it should prefer a color that has already been used
  3547. for a move-related variable (assuming that they do not interfere). Of
  3548. course, this preference should not override the preference for
  3549. registers over stack locations. This preference should be used as a
  3550. tie breaker when choosing between registers or when choosing between
  3551. stack locations.
  3552. We recommend representing the move relationships in a graph, similar
  3553. to how we represented interference. The following is the \emph{move
  3554. graph} for our running example.
  3555. \[
  3556. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3557. \node (rax) at (0,0) {$\ttm{rax}$};
  3558. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3559. \node (t) at (0,2) {$\ttm{t}$};
  3560. \node (z) at (3,2) {$\ttm{z}$};
  3561. \node (x) at (6,2) {$\ttm{x}$};
  3562. \node (y) at (3,0) {$\ttm{y}$};
  3563. \node (w) at (6,0) {$\ttm{w}$};
  3564. \node (v) at (9,0) {$\ttm{v}$};
  3565. \draw (v) to (x);
  3566. \draw (x) to (y);
  3567. \draw (x) to (z);
  3568. \draw (y) to (t);
  3569. \end{tikzpicture}
  3570. \]
  3571. Now we replay the graph coloring, pausing to see the coloring of
  3572. \code{y}. Recall the following configuration. The most saturated vertices
  3573. were \code{w} and \code{y}.
  3574. \[
  3575. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3576. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3577. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3578. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3579. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3580. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3581. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3582. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3583. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3584. \draw (t1) to (rax);
  3585. \draw (t1) to (z);
  3586. \draw (z) to (y);
  3587. \draw (z) to (w);
  3588. \draw (x) to (w);
  3589. \draw (y) to (w);
  3590. \draw (v) to (w);
  3591. \draw (v) to (rsp);
  3592. \draw (w) to (rsp);
  3593. \draw (x) to (rsp);
  3594. \draw (y) to (rsp);
  3595. \path[-.,bend left=15] (z) edge node {} (rsp);
  3596. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3597. \draw (rax) to (rsp);
  3598. \end{tikzpicture}
  3599. \]
  3600. %
  3601. Last time we chose to color \code{w} with $0$. But this time we see
  3602. that \code{w} is not move related to any vertex, but \code{y} is move
  3603. related to \code{t}. So we choose to color \code{y} the same color as
  3604. \code{t}, $0$.
  3605. \[
  3606. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3607. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3608. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3609. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3610. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3611. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3612. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3613. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3614. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3615. \draw (t1) to (rax);
  3616. \draw (t1) to (z);
  3617. \draw (z) to (y);
  3618. \draw (z) to (w);
  3619. \draw (x) to (w);
  3620. \draw (y) to (w);
  3621. \draw (v) to (w);
  3622. \draw (v) to (rsp);
  3623. \draw (w) to (rsp);
  3624. \draw (x) to (rsp);
  3625. \draw (y) to (rsp);
  3626. \path[-.,bend left=15] (z) edge node {} (rsp);
  3627. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3628. \draw (rax) to (rsp);
  3629. \end{tikzpicture}
  3630. \]
  3631. Now \code{w} is the most saturated, so we color it $2$.
  3632. \[
  3633. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3634. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3635. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3636. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3637. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3638. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3639. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3640. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3641. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3642. \draw (t1) to (rax);
  3643. \draw (t1) to (z);
  3644. \draw (z) to (y);
  3645. \draw (z) to (w);
  3646. \draw (x) to (w);
  3647. \draw (y) to (w);
  3648. \draw (v) to (w);
  3649. \draw (v) to (rsp);
  3650. \draw (w) to (rsp);
  3651. \draw (x) to (rsp);
  3652. \draw (y) to (rsp);
  3653. \path[-.,bend left=15] (z) edge node {} (rsp);
  3654. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3655. \draw (rax) to (rsp);
  3656. \end{tikzpicture}
  3657. \]
  3658. At this point, vertices \code{x} and \code{v} are most saturated, but
  3659. \code{x} is move related to \code{y} and \code{z}, so we color
  3660. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3661. \[
  3662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3663. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3664. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3665. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3666. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3667. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3668. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3669. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3670. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3671. \draw (t1) to (rax);
  3672. \draw (t) to (z);
  3673. \draw (z) to (y);
  3674. \draw (z) to (w);
  3675. \draw (x) to (w);
  3676. \draw (y) to (w);
  3677. \draw (v) to (w);
  3678. \draw (v) to (rsp);
  3679. \draw (w) to (rsp);
  3680. \draw (x) to (rsp);
  3681. \draw (y) to (rsp);
  3682. \path[-.,bend left=15] (z) edge node {} (rsp);
  3683. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3684. \draw (rax) to (rsp);
  3685. \end{tikzpicture}
  3686. \]
  3687. So we have the following assignment of variables to registers.
  3688. \begin{gather*}
  3689. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3690. \ttm{w} \mapsto \key{\%rsi}, \,
  3691. \ttm{x} \mapsto \key{\%rcx}, \,
  3692. \ttm{y} \mapsto \key{\%rcx}, \,
  3693. \ttm{z} \mapsto \key{\%rdx}, \,
  3694. \ttm{t} \mapsto \key{\%rcx} \}
  3695. \end{gather*}
  3696. We apply this register assignment to the running example, on the left,
  3697. to obtain the code in the middle. The \code{patch-instructions} then
  3698. removes the three trivial moves to obtain the code on the right.
  3699. \begin{minipage}{0.25\textwidth}
  3700. \begin{lstlisting}
  3701. movq $1, v
  3702. movq $42, w
  3703. movq v, x
  3704. addq $7, x
  3705. movq x, y
  3706. movq x, z
  3707. addq w, z
  3708. movq y, t
  3709. negq t
  3710. movq z, %rax
  3711. addq t, %rax
  3712. jmp conclusion
  3713. \end{lstlisting}
  3714. \end{minipage}
  3715. $\Rightarrow\qquad$
  3716. \begin{minipage}{0.25\textwidth}
  3717. \begin{lstlisting}
  3718. movq $1, %rcx
  3719. movq $42, %rsi
  3720. movq %rcx, %rcx
  3721. addq $7, %rcx
  3722. movq %rcx, %rcx
  3723. movq %rcx, %rdx
  3724. addq %rsi, %rdx
  3725. movq %rcx, %rcx
  3726. negq %rcx
  3727. movq %rdx, %rax
  3728. addq %rcx, %rax
  3729. jmp conclusion
  3730. \end{lstlisting}
  3731. \end{minipage}
  3732. $\Rightarrow\qquad$
  3733. \begin{minipage}{0.25\textwidth}
  3734. \begin{lstlisting}
  3735. movq $1, %rcx
  3736. movq $42, %rsi
  3737. addq $7, %rcx
  3738. movq %rcx, %rdx
  3739. addq %rsi, %rdx
  3740. negq %rcx
  3741. movq %rdx, %rax
  3742. addq %rcx, %rax
  3743. jmp conclusion
  3744. \end{lstlisting}
  3745. \end{minipage}
  3746. \begin{exercise}\normalfont
  3747. Change your implementation of \code{allocate-registers} to take move
  3748. biasing into account. Create two new tests that include at least one
  3749. opportunity for move biasing and visually inspect the output x86
  3750. programs to make sure that your move biasing is working properly. Make
  3751. sure that your compiler still passes all of the tests.
  3752. \end{exercise}
  3753. \margincomment{\footnotesize To do: another neat challenge would be to do
  3754. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3755. %% \subsection{Output of the Running Example}
  3756. %% \label{sec:reg-alloc-output}
  3757. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3758. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3759. and move biasing. To demonstrate both the use of registers and the
  3760. stack, we have limited the register allocator to use just two
  3761. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3762. of the \code{main} function, we push \code{rbx} onto the stack because
  3763. it is a callee-saved register and it was assigned to variable by the
  3764. register allocator. We subtract \code{8} from the \code{rsp} at the
  3765. end of the prelude to reserve space for the one spilled variable.
  3766. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3767. Moving on the the \code{start} block, we see how the registers were
  3768. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3769. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3770. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3771. that the prelude saved the callee-save register \code{rbx} onto the
  3772. stack. The spilled variables must be placed lower on the stack than
  3773. the saved callee-save registers, so in this case \code{w} is placed at
  3774. \code{-16(\%rbp)}.
  3775. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3776. done in the prelude. We move the stack pointer up by \code{8} bytes
  3777. (the room for spilled variables), then we pop the old values of
  3778. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3779. \code{retq} to return control to the operating system.
  3780. \begin{figure}[tbp]
  3781. % s0_28.rkt
  3782. % (use-minimal-set-of-registers! #t)
  3783. % and only rbx rcx
  3784. % tmp 0 rbx
  3785. % z 1 rcx
  3786. % y 0 rbx
  3787. % w 2 16(%rbp)
  3788. % v 0 rbx
  3789. % x 0 rbx
  3790. \begin{lstlisting}
  3791. start:
  3792. movq $1, %rbx
  3793. movq $42, -16(%rbp)
  3794. addq $7, %rbx
  3795. movq %rbx, %rcx
  3796. addq -16(%rbp), %rcx
  3797. negq %rbx
  3798. movq %rcx, %rax
  3799. addq %rbx, %rax
  3800. jmp conclusion
  3801. .globl main
  3802. main:
  3803. pushq %rbp
  3804. movq %rsp, %rbp
  3805. pushq %rbx
  3806. subq $8, %rsp
  3807. jmp start
  3808. conclusion:
  3809. addq $8, %rsp
  3810. popq %rbx
  3811. popq %rbp
  3812. retq
  3813. \end{lstlisting}
  3814. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3815. \label{fig:running-example-x86}
  3816. \end{figure}
  3817. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3818. \chapter{Booleans and Control Flow}
  3819. \label{ch:bool-types}
  3820. \index{Boolean}
  3821. \index{control flow}
  3822. \index{conditional expression}
  3823. The \LangInt{} and \LangVar{} languages only have a single kind of value, the
  3824. integers. In this chapter we add a second kind of value, the Booleans,
  3825. to create the \LangIf{} language. The Boolean values \emph{true} and
  3826. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3827. Racket. The \LangIf{} language includes several operations that involve
  3828. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3829. conditional \key{if} expression. With the addition of \key{if}
  3830. expressions, programs can have non-trivial control flow which which
  3831. significantly impacts the \code{explicate-control} and the liveness
  3832. analysis for register allocation. Also, because we now have two kinds
  3833. of values, we need to handle programs that apply an operation to the
  3834. wrong kind of value, such as \code{(not 1)}.
  3835. There are two language design options for such situations. One option
  3836. is to signal an error and the other is to provide a wider
  3837. interpretation of the operation. The Racket language uses a mixture of
  3838. these two options, depending on the operation and the kind of
  3839. value. For example, the result of \code{(not 1)} in Racket is
  3840. \code{\#f} because Racket treats non-zero integers as if they were
  3841. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3842. error in Racket stating that \code{car} expects a pair.
  3843. The Typed Racket language makes similar design choices as Racket,
  3844. except much of the error detection happens at compile time instead of
  3845. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3846. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3847. reports a compile-time error because Typed Racket expects the type of
  3848. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3849. For the \LangIf{} language we choose to be more like Typed Racket in that
  3850. we perform type checking during compilation. In
  3851. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3852. is, how to compile a dynamically typed language like Racket. The
  3853. \LangIf{} language is a subset of Typed Racket but by no means includes
  3854. all of Typed Racket. For many operations we take a narrower
  3855. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3856. This chapter is organized as follows. We begin by defining the syntax
  3857. and interpreter for the \LangIf{} language
  3858. (Section~\ref{sec:r2-lang}). We then introduce the idea of type
  3859. checking and build a type checker for \LangIf{}
  3860. (Section~\ref{sec:type-check-r2}). To compile \LangIf{} we need to
  3861. enlarge the intermediate language \LangCVar{} into \LangCIf{}, which
  3862. we do in Section~\ref{sec:c1}. The remaining sections of this chapter
  3863. discuss how our compiler passes change to accommodate Booleans and
  3864. conditional control flow.
  3865. \section{The \LangIf{} Language}
  3866. \label{sec:r2-lang}
  3867. The concrete syntax of the \LangIf{} language is defined in
  3868. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3869. in Figure~\ref{fig:r2-syntax}. The \LangIf{} language includes all of
  3870. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3871. and the conditional \code{if} expression. Also, we expand the
  3872. operators to include
  3873. \begin{enumerate}
  3874. \item subtraction on integers,
  3875. \item the logical operators \key{and}, \key{or} and \key{not},
  3876. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3877. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3878. comparing integers.
  3879. \end{enumerate}
  3880. We reorganize the abstract syntax for the primitive operations in
  3881. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3882. them. This means that the grammar no longer checks whether the arity
  3883. of an operators matches the number of arguments. That responsibility
  3884. is moved to the type checker for \LangIf{}, which we introduce in
  3885. Section~\ref{sec:type-check-r2}.
  3886. \begin{figure}[tp]
  3887. \centering
  3888. \fbox{
  3889. \begin{minipage}{0.96\textwidth}
  3890. \[
  3891. \begin{array}{lcl}
  3892. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3893. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3894. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3895. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3896. &\mid& \itm{bool}
  3897. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3898. \mid (\key{not}\;\Exp) \\
  3899. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3900. \LangIf{} &::=& \Exp
  3901. \end{array}
  3902. \]
  3903. \end{minipage}
  3904. }
  3905. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  3906. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3907. \label{fig:r2-concrete-syntax}
  3908. \end{figure}
  3909. \begin{figure}[tp]
  3910. \centering
  3911. \fbox{
  3912. \begin{minipage}{0.96\textwidth}
  3913. \[
  3914. \begin{array}{lcl}
  3915. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3916. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3917. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3918. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3919. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3920. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3921. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3922. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3923. \end{array}
  3924. \]
  3925. \end{minipage}
  3926. }
  3927. \caption{The abstract syntax of \LangIf{}.}
  3928. \label{fig:r2-syntax}
  3929. \end{figure}
  3930. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  3931. inheriting from the interpreter for \LangVar{}
  3932. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  3933. evaluate to the corresponding Boolean values. The conditional
  3934. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3935. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3936. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3937. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3938. you might expect, but note that the \code{and} operation is
  3939. short-circuiting. That is, given the expression
  3940. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3941. $e_1$ evaluates to \code{\#f}.
  3942. With the increase in the number of primitive operations, the
  3943. interpreter code for them could become repetitive without some
  3944. care. We factor out the different parts of the code for primitive
  3945. operations into the \code{interp-op} method shown in in
  3946. Figure~\ref{fig:interp-op-Rif}. The match clause for \code{Prim} makes
  3947. the recursive calls to interpret the arguments and then passes the
  3948. resulting values to \code{interp-op}. We do not use \code{interp-op}
  3949. for the \code{and} operation because of its short-circuiting behavior.
  3950. \begin{figure}[tbp]
  3951. \begin{lstlisting}
  3952. (define interp-Rif-class
  3953. (class interp-Rvar-class
  3954. (super-new)
  3955. (define/public (interp-op op) ...)
  3956. (define/override ((interp-exp env) e)
  3957. (define recur (interp-exp env))
  3958. (match e
  3959. [(Bool b) b]
  3960. [(If cnd thn els)
  3961. (define b (recur cnd))
  3962. (match b
  3963. [#t (recur thn)]
  3964. [#f (recur els)])]
  3965. [(Prim 'and (list e1 e2))
  3966. (define v1 (recur e1))
  3967. (match v1
  3968. [#t (match (recur e2) [#t #t] [#f #f])]
  3969. [#f #f])]
  3970. [(Prim op args)
  3971. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3972. [else ((super interp-exp env) e)]
  3973. ))
  3974. ))
  3975. (define (interp-Rif p)
  3976. (send (new interp-Rif-class) interp-program p))
  3977. \end{lstlisting}
  3978. \caption{Interpreter for the \LangIf{} language. (See
  3979. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  3980. \label{fig:interp-Rif}
  3981. \end{figure}
  3982. \begin{figure}[tbp]
  3983. \begin{lstlisting}
  3984. (define/public (interp-op op)
  3985. (match op
  3986. ['+ fx+]
  3987. ['- fx-]
  3988. ['read read-fixnum]
  3989. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3990. ['or (lambda (v1 v2)
  3991. (cond [(and (boolean? v1) (boolean? v2))
  3992. (or v1 v2)]))]
  3993. ['eq? (lambda (v1 v2)
  3994. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3995. (and (boolean? v1) (boolean? v2))
  3996. (and (vector? v1) (vector? v2)))
  3997. (eq? v1 v2)]))]
  3998. ['< (lambda (v1 v2)
  3999. (cond [(and (fixnum? v1) (fixnum? v2))
  4000. (< v1 v2)]))]
  4001. ['<= (lambda (v1 v2)
  4002. (cond [(and (fixnum? v1) (fixnum? v2))
  4003. (<= v1 v2)]))]
  4004. ['> (lambda (v1 v2)
  4005. (cond [(and (fixnum? v1) (fixnum? v2))
  4006. (> v1 v2)]))]
  4007. ['>= (lambda (v1 v2)
  4008. (cond [(and (fixnum? v1) (fixnum? v2))
  4009. (>= v1 v2)]))]
  4010. [else (error 'interp-op "unknown operator")]
  4011. ))
  4012. \end{lstlisting}
  4013. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4014. \label{fig:interp-op-Rif}
  4015. \end{figure}
  4016. \section{Type Checking \LangIf{} Programs}
  4017. \label{sec:type-check-r2}
  4018. \index{type checking}
  4019. \index{semantic analysis}
  4020. It is helpful to think about type checking in two complementary
  4021. ways. A type checker predicts the type of value that will be produced
  4022. by each expression in the program. For \LangIf{}, we have just two types,
  4023. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4024. \begin{lstlisting}
  4025. (+ 10 (- (+ 12 20)))
  4026. \end{lstlisting}
  4027. produces an \key{Integer} while
  4028. \begin{lstlisting}
  4029. (and (not #f) #t)
  4030. \end{lstlisting}
  4031. produces a \key{Boolean}.
  4032. Another way to think about type checking is that it enforces a set of
  4033. rules about which operators can be applied to which kinds of
  4034. values. For example, our type checker for \LangIf{} will signal an error
  4035. for the below expression because, as we have seen above, the
  4036. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  4037. checker enforces the rule that the argument of \code{not} must be a
  4038. \key{Boolean}.
  4039. \begin{lstlisting}
  4040. (not (+ 10 (- (+ 12 20))))
  4041. \end{lstlisting}
  4042. We implement type checking using classes and method overriding for the
  4043. same reason that we use them to implement the interpreters. We
  4044. separate the type checker for the \LangVar{} fragment into its own class,
  4045. shown in Figure~\ref{fig:type-check-Rvar}. The type checker for \LangIf{} is
  4046. shown in Figure~\ref{fig:type-check-Rif}; inherits from the one for
  4047. \LangVar{}. The code for these type checkers are in the files
  4048. \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the support
  4049. code.
  4050. %
  4051. Each type checker is a structurally recursive function over the AST.
  4052. Given an input expression \code{e}, the type checker either signals an
  4053. error or returns an expression and its type (\key{Integer} or
  4054. \key{Boolean}). There are situations in which we want to change or
  4055. update the expression.
  4056. %
  4057. The type of an integer literal is \code{Integer} and
  4058. the type of a Boolean literal is \code{Boolean}. To handle variables,
  4059. the type checker uses the environment \code{env} to map variables to
  4060. types. Consider the clause for \key{let}. We type check the
  4061. initializing expression to obtain its type \key{T} and then associate
  4062. type \code{T} with the variable \code{x} in the environment used to
  4063. type check the body of the \key{let}. Thus, when the type checker
  4064. encounters a use of variable \code{x}, it can find its type in the
  4065. environment.
  4066. \begin{figure}[tbp]
  4067. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4068. (define type-check-Rvar-class
  4069. (class object%
  4070. (super-new)
  4071. (define/public (operator-types)
  4072. '((+ . ((Integer Integer) . Integer))
  4073. (- . ((Integer) . Integer))
  4074. (read . (() . Integer))))
  4075. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4076. (define/public (check-type-equal? t1 t2 e)
  4077. (unless (type-equal? t1 t2)
  4078. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4079. (define/public (type-check-op op arg-types e)
  4080. (match (dict-ref (operator-types) op)
  4081. [`(,param-types . ,return-type)
  4082. (for ([at arg-types] [pt param-types])
  4083. (check-type-equal? at pt e))
  4084. return-type]
  4085. [else (error 'type-check-op "unrecognized ~a" op)]))
  4086. (define/public (type-check-exp env)
  4087. (lambda (e)
  4088. (match e
  4089. [(Var x) (values (Var x) (dict-ref env x))]
  4090. [(Int n) (values (Int n) 'Integer)]
  4091. [(Let x e body)
  4092. (define-values (e^ Te) ((type-check-exp env) e))
  4093. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4094. (values (Let x e^ b) Tb)]
  4095. [(Prim op es)
  4096. (define-values (new-es ts)
  4097. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4098. (values (Prim op new-es) (type-check-op op ts e))]
  4099. [else (error 'type-check-exp "couldn't match" e)])))
  4100. (define/public (type-check-program e)
  4101. (match e
  4102. [(Program info body)
  4103. (define-values (body^ Tb) ((type-check-exp '()) body))
  4104. (check-type-equal? Tb 'Integer body)
  4105. (Program info body^)]
  4106. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4107. ))
  4108. (define (type-check-Rvar p)
  4109. (send (new type-check-Rvar-class) type-check-program p))
  4110. \end{lstlisting}
  4111. \caption{Type checker for the \LangVar{} fragment of \LangIf{}.}
  4112. \label{fig:type-check-Rvar}
  4113. \end{figure}
  4114. \begin{figure}[tbp]
  4115. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4116. (define type-check-Rif-class
  4117. (class type-check-Rvar-class
  4118. (super-new)
  4119. (inherit check-type-equal?)
  4120. (define/override (operator-types)
  4121. (append '((- . ((Integer Integer) . Integer))
  4122. (and . ((Boolean Boolean) . Boolean))
  4123. (or . ((Boolean Boolean) . Boolean))
  4124. (< . ((Integer Integer) . Boolean))
  4125. (<= . ((Integer Integer) . Boolean))
  4126. (> . ((Integer Integer) . Boolean))
  4127. (>= . ((Integer Integer) . Boolean))
  4128. (not . ((Boolean) . Boolean))
  4129. )
  4130. (super operator-types)))
  4131. (define/override (type-check-exp env)
  4132. (lambda (e)
  4133. (match e
  4134. [(Bool b) (values (Bool b) 'Boolean)]
  4135. [(If cnd thn els)
  4136. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4137. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4138. (define-values (els^ Te) ((type-check-exp env) els))
  4139. (check-type-equal? Tc 'Boolean e)
  4140. (check-type-equal? Tt Te e)
  4141. (values (If cnd^ thn^ els^) Te)]
  4142. [(Prim 'eq? (list e1 e2))
  4143. (define-values (e1^ T1) ((type-check-exp env) e1))
  4144. (define-values (e2^ T2) ((type-check-exp env) e2))
  4145. (check-type-equal? T1 T2 e)
  4146. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4147. [else ((super type-check-exp env) e)])))
  4148. ))
  4149. (define (type-check-Rif p)
  4150. (send (new type-check-Rif-class) type-check-program p))
  4151. \end{lstlisting}
  4152. \caption{Type checker for the \LangIf{} language.}
  4153. \label{fig:type-check-Rif}
  4154. \end{figure}
  4155. Three auxiliary methods are used in the type checker. The method
  4156. \code{operator-types} defines a dictionary that maps the operator
  4157. names to their parameter and return types. The \code{type-equal?}
  4158. method determines whether two types are equal, which for now simply
  4159. dispatches to \code{equal?} (deep equality). The \code{type-check-op}
  4160. method looks up the operator in the \code{operator-types} dictionary
  4161. and then checks whether the argument types are equal to the parameter
  4162. types. The result is the return type of the operator.
  4163. \begin{exercise}\normalfont
  4164. Create 10 new example programs in \LangIf{}. Half of the example programs
  4165. should have a type error. For those programs, to signal that a type
  4166. error is expected, create an empty file with the same base name but
  4167. with file extension \code{.tyerr}. For example, if the test
  4168. \code{r2\_14.rkt} is expected to error, then create an empty file
  4169. named \code{r2\_14.tyerr}. The other half of the example programs
  4170. should not have type errors. Note that if the type checker does not
  4171. signal an error for a program, then interpreting that program should
  4172. not encounter an error.
  4173. \end{exercise}
  4174. \section{Shrink the \LangIf{} Language}
  4175. \label{sec:shrink-r2}
  4176. The \LangIf{} language includes several operators that are easily
  4177. expressible in terms of other operators. For example, subtraction is
  4178. expressible in terms of addition and negation.
  4179. \[
  4180. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4181. \]
  4182. Several of the comparison operations are expressible in terms of
  4183. less-than and logical negation.
  4184. \[
  4185. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4186. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4187. \]
  4188. The \key{let} is needed in the above translation to ensure that
  4189. expression $e_1$ is evaluated before $e_2$.
  4190. By performing these translations near the front-end of the compiler,
  4191. the later passes of the compiler do not need to deal with these
  4192. constructs, making those passes shorter. On the other hand, sometimes
  4193. these translations make it more difficult to generate the most
  4194. efficient code with respect to the number of instructions. However,
  4195. these differences typically do not affect the number of accesses to
  4196. memory, which is the primary factor that determines execution time on
  4197. modern computer architectures.
  4198. \begin{exercise}\normalfont
  4199. Implement the pass \code{shrink} that removes subtraction,
  4200. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  4201. by translating them to other constructs in \LangIf{}. Create tests to
  4202. make sure that the behavior of all of these constructs stays the
  4203. same after translation.
  4204. \end{exercise}
  4205. \section{The \LangXASTIf{} Language}
  4206. \label{sec:x86-1}
  4207. \index{x86}
  4208. To implement the new logical operations, the comparison operations,
  4209. and the \key{if} expression, we need to delve further into the x86
  4210. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  4211. the concrete and abstract syntax for a larger subset of x86 that
  4212. includes instructions for logical operations, comparisons, and
  4213. conditional jumps.
  4214. One small challenge is that x86 does not provide an instruction that
  4215. directly implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  4216. However, the \code{xorq} instruction can be used to encode \code{not}.
  4217. The \key{xorq} instruction takes two arguments, performs a pairwise
  4218. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  4219. and writes the results into its second argument. Recall the truth
  4220. table for exclusive-or:
  4221. \begin{center}
  4222. \begin{tabular}{l|cc}
  4223. & 0 & 1 \\ \hline
  4224. 0 & 0 & 1 \\
  4225. 1 & 1 & 0
  4226. \end{tabular}
  4227. \end{center}
  4228. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4229. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4230. for the bit $1$, the result is the opposite of the second bit. Thus,
  4231. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4232. the first argument:
  4233. \[
  4234. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4235. \qquad\Rightarrow\qquad
  4236. \begin{array}{l}
  4237. \key{movq}~ \Arg\key{,} \Var\\
  4238. \key{xorq}~ \key{\$1,} \Var
  4239. \end{array}
  4240. \]
  4241. \begin{figure}[tp]
  4242. \fbox{
  4243. \begin{minipage}{0.96\textwidth}
  4244. \[
  4245. \begin{array}{lcl}
  4246. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4247. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4248. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4249. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4250. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4251. \key{subq} \; \Arg\key{,} \Arg \mid
  4252. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4253. && \gray{ \key{callq} \; \itm{label} \mid
  4254. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4255. && \gray{ \itm{label}\key{:}\; \Instr }
  4256. \mid \key{xorq}~\Arg\key{,}~\Arg
  4257. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4258. && \key{set}cc~\Arg
  4259. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4260. \mid \key{j}cc~\itm{label}
  4261. \\
  4262. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4263. & & \gray{ \key{main:} \; \Instr\ldots }
  4264. \end{array}
  4265. \]
  4266. \end{minipage}
  4267. }
  4268. \caption{The concrete syntax of \LangXIf{} (extends \LangXASTInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4269. \label{fig:x86-1-concrete}
  4270. \end{figure}
  4271. \begin{figure}[tp]
  4272. \fbox{
  4273. \begin{minipage}{0.98\textwidth}
  4274. \small
  4275. \[
  4276. \begin{array}{lcl}
  4277. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4278. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4279. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4280. \mid \BYTEREG{\itm{bytereg}} \\
  4281. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4282. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4283. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4284. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4285. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4286. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4287. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4288. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4289. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4290. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4291. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4292. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4293. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4294. \LangXASTIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4295. \end{array}
  4296. \]
  4297. \end{minipage}
  4298. }
  4299. \caption{The abstract syntax of \LangXASTIf{} (extends \LangXASTInt{} of Figure~\ref{fig:x86-int-ast}).}
  4300. \label{fig:x86-1}
  4301. \end{figure}
  4302. Next we consider the x86 instructions that are relevant for compiling
  4303. the comparison operations. The \key{cmpq} instruction compares its two
  4304. arguments to determine whether one argument is less than, equal, or
  4305. greater than the other argument. The \key{cmpq} instruction is unusual
  4306. regarding the order of its arguments and where the result is
  4307. placed. The argument order is backwards: if you want to test whether
  4308. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4309. \key{cmpq} is placed in the special EFLAGS register. This register
  4310. cannot be accessed directly but it can be queried by a number of
  4311. instructions, including the \key{set} instruction. The \key{set}
  4312. instruction puts a \key{1} or \key{0} into its destination depending
  4313. on whether the comparison came out according to the condition code
  4314. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4315. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4316. The \key{set} instruction has an annoying quirk in that its
  4317. destination argument must be single byte register, such as \code{al}
  4318. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4319. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4320. then be used to move from a single byte register to a normal 64-bit
  4321. register.
  4322. The x86 instruction for conditional jump are relevant to the
  4323. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4324. updates the program counter to point to the instruction after the
  4325. indicated label depending on whether the result in the EFLAGS register
  4326. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4327. instruction falls through to the next instruction. The abstract
  4328. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4329. that it separates the instruction name from the condition code. For
  4330. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4331. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4332. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4333. instruction to set the EFLAGS register.
  4334. \section{The \LangCIf{} Intermediate Language}
  4335. \label{sec:c1}
  4336. As with \LangVar{}, we compile \LangIf{} to a C-like intermediate language, but
  4337. we need to grow that intermediate language to handle the new features
  4338. in \LangIf{}: Booleans and conditional expressions.
  4339. Figure~\ref{fig:c1-syntax} defines the abstract syntax of \LangCIf{}. (The
  4340. concrete syntax is in the Appendix,
  4341. Figure~\ref{fig:c1-concrete-syntax}.) The \LangCIf{} language adds logical
  4342. and comparison operators to the $\Exp$ non-terminal and the literals
  4343. \key{\#t} and \key{\#f} to the $\Arg$ non-terminal. Regarding control
  4344. flow, \LangCIf{} differs considerably from \LangIf{}. Instead of \key{if}
  4345. expressions, \LangCIf{} has \key{goto} and conditional \key{goto} in the
  4346. grammar for $\Tail$. This means that a sequence of statements may now
  4347. end with a \code{goto} or a conditional \code{goto}. The conditional
  4348. \code{goto} jumps to one of two labels depending on the outcome of the
  4349. comparison. In Section~\ref{sec:explicate-control-r2} we discuss how
  4350. to translate from \LangIf{} to \LangCIf{}, bridging this gap between \key{if}
  4351. expressions and \key{goto}'s.
  4352. \begin{figure}[tp]
  4353. \fbox{
  4354. \begin{minipage}{0.96\textwidth}
  4355. \small
  4356. \[
  4357. \begin{array}{lcl}
  4358. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4359. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4360. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4361. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4362. &\mid& \UNIOP{\key{'not}}{\Atm}
  4363. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4364. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4365. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4366. \mid \GOTO{\itm{label}} \\
  4367. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4368. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4369. \end{array}
  4370. \]
  4371. \end{minipage}
  4372. }
  4373. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4374. (Figure~\ref{fig:c0-syntax}).}
  4375. \label{fig:c1-syntax}
  4376. \end{figure}
  4377. \clearpage
  4378. \section{Remove Complex Operands}
  4379. \label{sec:remove-complex-opera-Rif}
  4380. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4381. \code{rco-atom} functions according to the definition of the output
  4382. language for this pass, \LangIfANF{}, the administrative normal
  4383. form of \LangIf{}, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4384. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4385. three sub-expressions of an \code{If} are allowed to be complex
  4386. expressions in the output of \code{remove-complex-opera*}, but the
  4387. operands of \code{not} and the comparisons must be atoms. Regarding
  4388. the \code{If} form, it is particularly important to \textbf{not}
  4389. replace its condition with a temporary variable because that would
  4390. interfere with the generation of high-quality output in the
  4391. \code{explicate-control} pass.
  4392. \begin{figure}[tp]
  4393. \centering
  4394. \fbox{
  4395. \begin{minipage}{0.96\textwidth}
  4396. \[
  4397. \begin{array}{rcl}
  4398. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4399. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4400. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4401. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4402. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4403. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4404. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4405. \end{array}
  4406. \]
  4407. \end{minipage}
  4408. }
  4409. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4410. \label{fig:r2-anf-syntax}
  4411. \end{figure}
  4412. \section{Explicate Control}
  4413. \label{sec:explicate-control-r2}
  4414. Recall that the purpose of \code{explicate-control} is to make the
  4415. order of evaluation explicit in the syntax of the program. With the
  4416. addition of \key{if} in \LangIf{} this get more interesting.
  4417. As a motivating example, consider the following program that has an
  4418. \key{if} expression nested in the predicate of another \key{if}.
  4419. % s1_41.rkt
  4420. \begin{center}
  4421. \begin{minipage}{0.96\textwidth}
  4422. \begin{lstlisting}
  4423. (let ([x (read)])
  4424. (let ([y (read)])
  4425. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4426. (+ y 2)
  4427. (+ y 10))))
  4428. \end{lstlisting}
  4429. \end{minipage}
  4430. \end{center}
  4431. %
  4432. The naive way to compile \key{if} and the comparison would be to
  4433. handle each of them in isolation, regardless of their context. Each
  4434. comparison would be translated into a \key{cmpq} instruction followed
  4435. by a couple instructions to move the result from the EFLAGS register
  4436. into a general purpose register or stack location. Each \key{if} would
  4437. be translated into the combination of a \key{cmpq} and a conditional
  4438. jump. The generated code for the inner \key{if} in the above example
  4439. would be as follows.
  4440. \begin{center}
  4441. \begin{minipage}{0.96\textwidth}
  4442. \begin{lstlisting}
  4443. ...
  4444. cmpq $1, x ;; (< x 1)
  4445. setl %al
  4446. movzbq %al, tmp
  4447. cmpq $1, tmp ;; (if (< x 1) ...)
  4448. je then_branch_1
  4449. jmp else_branch_1
  4450. ...
  4451. \end{lstlisting}
  4452. \end{minipage}
  4453. \end{center}
  4454. However, if we take context into account we can do better and reduce
  4455. the use of \key{cmpq} and EFLAG-accessing instructions.
  4456. One idea is to try and reorganize the code at the level of \LangIf{},
  4457. pushing the outer \key{if} inside the inner one. This would yield the
  4458. following code.
  4459. \begin{center}
  4460. \begin{minipage}{0.96\textwidth}
  4461. \begin{lstlisting}
  4462. (let ([x (read)])
  4463. (let ([y (read)])
  4464. (if (< x 1)
  4465. (if (eq? x 0)
  4466. (+ y 2)
  4467. (+ y 10))
  4468. (if (eq? x 2)
  4469. (+ y 2)
  4470. (+ y 10)))))
  4471. \end{lstlisting}
  4472. \end{minipage}
  4473. \end{center}
  4474. Unfortunately, this approach duplicates the two branches, and a
  4475. compiler must never duplicate code!
  4476. We need a way to perform the above transformation, but without
  4477. duplicating code. That is, we need a way for different parts of a
  4478. program to refer to the same piece of code, that is, to \emph{share}
  4479. code. At the level of x86 assembly this is straightforward because we
  4480. can label the code for each of the branches and insert jumps in all
  4481. the places that need to execute the branches. At the higher level of
  4482. our intermediate languages, we need to move away from abstract syntax
  4483. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4484. standard program representation called a \emph{control flow graph}
  4485. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4486. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4487. called a \emph{basic block}, and each edge represents a jump to
  4488. another block. The \key{Program} construct of \LangCVar{} and \LangCIf{} contains
  4489. a control flow graph represented as an alist mapping labels to basic
  4490. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4491. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4492. \code{remove-complex-opera*} pass and then the
  4493. \code{explicate-control} pass on the example program. We walk through
  4494. the output program and then discuss the algorithm.
  4495. %
  4496. Following the order of evaluation in the output of
  4497. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4498. and then the less-than-comparison to \code{1} in the predicate of the
  4499. inner \key{if}. In the output of \code{explicate-control}, in the
  4500. block labeled \code{start}, this becomes two assignment statements
  4501. followed by a conditional \key{goto} to label \code{block40} or
  4502. \code{block41}. The blocks associated with those labels contain the
  4503. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4504. respectively. Regarding the block labeled with \code{block40}, we
  4505. start with the comparison to \code{0} and then have a conditional
  4506. goto, either to label \code{block38} or label \code{block39}, which
  4507. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4508. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4509. similar.
  4510. \begin{figure}[tbp]
  4511. \begin{tabular}{lll}
  4512. \begin{minipage}{0.4\textwidth}
  4513. % s1_41.rkt
  4514. \begin{lstlisting}
  4515. (let ([x (read)])
  4516. (let ([y (read)])
  4517. (if (if (< x 1)
  4518. (eq? x 0)
  4519. (eq? x 2))
  4520. (+ y 2)
  4521. (+ y 10))))
  4522. \end{lstlisting}
  4523. \hspace{40pt}$\Downarrow$
  4524. \begin{lstlisting}
  4525. (let ([x (read)])
  4526. (let ([y (read)])
  4527. (if (if (< x 1)
  4528. (eq? x 0)
  4529. (eq? x 2))
  4530. (+ y 2)
  4531. (+ y 10))))
  4532. \end{lstlisting}
  4533. \end{minipage}
  4534. &
  4535. $\Rightarrow$
  4536. &
  4537. \begin{minipage}{0.55\textwidth}
  4538. \begin{lstlisting}
  4539. start:
  4540. x = (read);
  4541. y = (read);
  4542. if (< x 1)
  4543. goto block40;
  4544. else
  4545. goto block41;
  4546. block40:
  4547. if (eq? x 0)
  4548. goto block38;
  4549. else
  4550. goto block39;
  4551. block41:
  4552. if (eq? x 2)
  4553. goto block38;
  4554. else
  4555. goto block39;
  4556. block38:
  4557. return (+ y 2);
  4558. block39:
  4559. return (+ y 10);
  4560. \end{lstlisting}
  4561. \end{minipage}
  4562. \end{tabular}
  4563. \caption{Translation from \LangIf{} to \LangCIf{}
  4564. via the \code{explicate-control}.}
  4565. \label{fig:explicate-control-s1-38}
  4566. \end{figure}
  4567. %% The nice thing about the output of \code{explicate-control} is that
  4568. %% there are no unnecessary comparisons and every comparison is part of a
  4569. %% conditional jump.
  4570. %% The down-side of this output is that it includes
  4571. %% trivial blocks, such as the blocks labeled \code{block92} through
  4572. %% \code{block95}, that only jump to another block. We discuss a solution
  4573. %% to this problem in Section~\ref{sec:opt-jumps}.
  4574. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4575. \code{explicate-control} for \LangVar{} using two mutually recursive
  4576. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4577. former function translates expressions in tail position whereas the
  4578. later function translates expressions on the right-hand-side of a
  4579. \key{let}. With the addition of \key{if} expression in \LangIf{} we have a
  4580. new kind of context to deal with: the predicate position of the
  4581. \key{if}. We need another function, \code{explicate-pred}, that takes
  4582. an \LangIf{} expression and two blocks for the then-branch and
  4583. else-branch. The output of \code{explicate-pred} is a block.
  4584. %
  4585. %% Note that the three explicate functions need to construct a
  4586. %% control-flow graph, which we recommend they do via updates to a global
  4587. %% variable.
  4588. %
  4589. In the following paragraphs we discuss specific cases in the
  4590. \code{explicate-pred} function as well as the additions to the
  4591. \code{explicate-tail} and \code{explicate-assign} functions.
  4592. The function \code{explicate-pred} will need a case for every
  4593. expression that can have type \code{Boolean}. We detail a few cases
  4594. here and leave the rest for the reader. The input to this function is
  4595. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4596. the enclosing \key{if}, though some care will be needed regarding how
  4597. we represent the blocks. Suppose the expression is the Boolean
  4598. \code{\#t}. Then we can perform a kind of partial evaluation
  4599. \index{partial evaluation} and translate it to the ``then'' branch
  4600. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4601. \[
  4602. \key{\#t} \quad\Rightarrow\quad B_1,
  4603. \qquad\qquad\qquad
  4604. \key{\#f} \quad\Rightarrow\quad B_2
  4605. \]
  4606. These two cases demonstrate that we sometimes discard one of the
  4607. blocks that are input to \code{explicate-pred}. We will need to
  4608. arrange for the blocks that we actually use to appear in the resulting
  4609. control-flow graph, but not the discarded blocks.
  4610. The case for \key{if} in \code{explicate-pred} is particularly
  4611. illuminating as it deals with the challenges that we discussed above
  4612. regarding the example of the nested \key{if} expressions. The
  4613. ``then'' and ``else'' branches of the current \key{if} inherit their
  4614. context from the current one, that is, predicate context. So we
  4615. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4616. branches. For both of those recursive calls, we shall pass the blocks
  4617. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4618. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4619. duplicating code, we need to add these blocks to the control-flow
  4620. graph so that we can instead refer to them by name and execute them
  4621. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4622. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4623. we don't want to prematurely add them to the control-flow graph if
  4624. they end up being discarded.
  4625. The solution to this conundrum is to use \emph{lazy evaluation} to
  4626. delay adding the blocks to the control-flow graph until the points
  4627. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4628. evaluation} Racket provides support for lazy evaluation with the
  4629. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4630. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4631. \index{delay} creates a \emph{promise}\index{promise} in which the
  4632. evaluation of the expressions is postponed. When \key{(force}
  4633. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4634. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4635. $e_n$ is cached in the promise and returned. If \code{force} is
  4636. applied again to the same promise, then the cached result is returned.
  4637. We use lazy evaluation for the input and output blocks of the
  4638. functions \code{explicate-pred} and \code{explicate-assign} and for
  4639. the output block of \code{explicate-tail}. So instead of taking and
  4640. returning blocks, they take and return promised blocks. Furthermore,
  4641. when we come to a situation in which we a block might be used more
  4642. than once, as in the case for \code{if} above, we transform the
  4643. promise into a new promise that will add the block to the control-flow
  4644. graph and return a \code{goto}. The following auxiliary function
  4645. accomplishes this task. It begins with \code{delay} to create a
  4646. promise. When forced, this promise will force the input block. If that
  4647. block is already a \code{goto} (because it was already added to the
  4648. control-flow graph), then we return that \code{goto}. Otherwise we add
  4649. the block to the control-flow graph with another auxiliary function
  4650. named \code{add-node} that returns the new label, and then return the
  4651. \code{goto}.
  4652. \begin{lstlisting}
  4653. (define (block->goto block)
  4654. (delay
  4655. (define b (force block))
  4656. (match b
  4657. [(Goto label) (Goto label)]
  4658. [else (Goto (add-node b))]
  4659. )))
  4660. \end{lstlisting}
  4661. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4662. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4663. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4664. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4665. results from the two recursive calls. We complete the case for
  4666. \code{if} by recursively apply \code{explicate-pred} to the condition
  4667. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4668. the result $B_5$.
  4669. \[
  4670. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4671. \quad\Rightarrow\quad
  4672. B_5
  4673. \]
  4674. Next, consider the case for a less-than comparison in
  4675. \code{explicate-pred}. We translate it to an \code{if} statement,
  4676. whose two branches are required to be \code{goto}'s. So we apply
  4677. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4678. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4679. $G_2$. The translation of the less-than comparison is as follows.
  4680. \[
  4681. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4682. \begin{array}{l}
  4683. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4684. \key{else} \; G_2
  4685. \end{array}
  4686. \]
  4687. The \code{explicate-tail} function needs to be updated to use lazy
  4688. evaluation and it needs an additional case for \key{if}. Each of the
  4689. cases that return an AST node need use \code{delay} to instead return
  4690. a promise of an AST node. Recall that \code{explicate-tail} has an
  4691. accumulator parameter that is a block, which now becomes a promise of
  4692. a block, which we refer to as $B_0$.
  4693. In the case for \code{if} in \code{explicate-tail}, the two branches
  4694. inherit the current context, so they are in tail position. Thus, the
  4695. recursive calls on the ``then'' and ``else'' branch should be calls to
  4696. \code{explicate-tail}.
  4697. %
  4698. We need to pass $B_0$ as the accumulator argument for both of these
  4699. recursive calls, but we need to be careful not to duplicate $B_0$.
  4700. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4701. to the control-flow graph and obtain a promised goto $G_0$.
  4702. %
  4703. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4704. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4705. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4706. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4707. $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4708. \[
  4709. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4710. \]
  4711. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4712. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4713. %% should not be confused with the labels for the blocks that appear in
  4714. %% the generated code. We initially construct unlabeled blocks; we only
  4715. %% attach labels to blocks when we add them to the control-flow graph, as
  4716. %% we see in the next case.
  4717. Next consider the case for \key{if} in the \code{explicate-assign}
  4718. function. The context of the \key{if} is an assignment to some
  4719. variable $x$ and then the control continues to some promised block
  4720. $B_1$. The code that we generate for both the ``then'' and ``else''
  4721. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4722. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4723. branches of the \key{if} inherit the current context, so they are in
  4724. assignment positions. Let $B_2$ be the result of applying
  4725. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4726. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4727. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4728. the result of applying \code{explicate-pred} to the predicate
  4729. $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4730. translates to the promise $B_4$.
  4731. \[
  4732. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4733. \]
  4734. This completes the description of \code{explicate-control} for \LangIf{}.
  4735. The way in which the \code{shrink} pass transforms logical operations
  4736. such as \code{and} and \code{or} can impact the quality of code
  4737. generated by \code{explicate-control}. For example, consider the
  4738. following program.
  4739. % s1_21.rkt
  4740. \begin{lstlisting}
  4741. (if (and (eq? (read) 0) (eq? (read) 1))
  4742. 0
  4743. 42)
  4744. \end{lstlisting}
  4745. The \code{and} operation should transform into something that the
  4746. \code{explicate-pred} function can still analyze and descend through to
  4747. reach the underlying \code{eq?} conditions. Ideally, your
  4748. \code{explicate-control} pass should generate code similar to the
  4749. following for the above program.
  4750. \begin{center}
  4751. \begin{lstlisting}
  4752. start:
  4753. tmp1 = (read);
  4754. if (eq? tmp1 0)
  4755. goto block40;
  4756. else
  4757. goto block39;
  4758. block40:
  4759. tmp2 = (read);
  4760. if (eq? tmp2 1)
  4761. goto block38;
  4762. else
  4763. goto block39;
  4764. block38:
  4765. return 0;
  4766. block39:
  4767. return 42;
  4768. \end{lstlisting}
  4769. \end{center}
  4770. \begin{exercise}\normalfont
  4771. Implement the pass \code{explicate-control} by adding the cases for
  4772. \key{if} to the functions for tail and assignment contexts, and
  4773. implement \code{explicate-pred} for predicate contexts. Create test
  4774. cases that exercise all of the new cases in the code for this pass.
  4775. \end{exercise}
  4776. \section{Select Instructions}
  4777. \label{sec:select-r2}
  4778. \index{instruction selection}
  4779. Recall that the \code{select-instructions} pass lowers from our
  4780. $C$-like intermediate representation to the pseudo-x86 language, which
  4781. is suitable for conducting register allocation. The pass is
  4782. implemented using three auxiliary functions, one for each of the
  4783. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4784. For $\Atm$, we have new cases for the Booleans. We take the usual
  4785. approach of encoding them as integers, with true as 1 and false as 0.
  4786. \[
  4787. \key{\#t} \Rightarrow \key{1}
  4788. \qquad
  4789. \key{\#f} \Rightarrow \key{0}
  4790. \]
  4791. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4792. be implemented in terms of \code{xorq} as we discussed at the
  4793. beginning of this section. Given an assignment
  4794. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4795. if the left-hand side $\itm{var}$ is
  4796. the same as $\Atm$, then just the \code{xorq} suffices.
  4797. \[
  4798. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4799. \quad\Rightarrow\quad
  4800. \key{xorq}~\key{\$}1\key{,}~\Var
  4801. \]
  4802. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4803. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4804. x86. Then we have
  4805. \[
  4806. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4807. \quad\Rightarrow\quad
  4808. \begin{array}{l}
  4809. \key{movq}~\Arg\key{,}~\Var\\
  4810. \key{xorq}~\key{\$}1\key{,}~\Var
  4811. \end{array}
  4812. \]
  4813. Next consider the cases for \code{eq?} and less-than comparison.
  4814. Translating these operations to x86 is slightly involved due to the
  4815. unusual nature of the \key{cmpq} instruction discussed above. We
  4816. recommend translating an assignment from \code{eq?} into the following
  4817. sequence of three instructions. \\
  4818. \begin{tabular}{lll}
  4819. \begin{minipage}{0.4\textwidth}
  4820. \begin{lstlisting}
  4821. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4822. \end{lstlisting}
  4823. \end{minipage}
  4824. &
  4825. $\Rightarrow$
  4826. &
  4827. \begin{minipage}{0.4\textwidth}
  4828. \begin{lstlisting}
  4829. cmpq |$\Arg_2$|, |$\Arg_1$|
  4830. sete %al
  4831. movzbq %al, |$\Var$|
  4832. \end{lstlisting}
  4833. \end{minipage}
  4834. \end{tabular} \\
  4835. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4836. and conditional \key{goto}. Both are straightforward to handle. A
  4837. \key{goto} becomes a jump instruction.
  4838. \[
  4839. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4840. \]
  4841. A conditional \key{goto} becomes a compare instruction followed
  4842. by a conditional jump (for ``then'') and the fall-through is
  4843. to a regular jump (for ``else'').\\
  4844. \begin{tabular}{lll}
  4845. \begin{minipage}{0.4\textwidth}
  4846. \begin{lstlisting}
  4847. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4848. goto |$\ell_1$|;
  4849. else
  4850. goto |$\ell_2$|;
  4851. \end{lstlisting}
  4852. \end{minipage}
  4853. &
  4854. $\Rightarrow$
  4855. &
  4856. \begin{minipage}{0.4\textwidth}
  4857. \begin{lstlisting}
  4858. cmpq |$\Arg_2$|, |$\Arg_1$|
  4859. je |$\ell_1$|
  4860. jmp |$\ell_2$|
  4861. \end{lstlisting}
  4862. \end{minipage}
  4863. \end{tabular} \\
  4864. \begin{exercise}\normalfont
  4865. Expand your \code{select-instructions} pass to handle the new features
  4866. of the \LangIf{} language. Test the pass on all the examples you have
  4867. created and make sure that you have some test programs that use the
  4868. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4869. the output using the \code{interp-x86} interpreter
  4870. (Appendix~\ref{appendix:interp}).
  4871. \end{exercise}
  4872. \section{Register Allocation}
  4873. \label{sec:register-allocation-r2}
  4874. \index{register allocation}
  4875. The changes required for \LangIf{} affect liveness analysis, building the
  4876. interference graph, and assigning homes, but the graph coloring
  4877. algorithm itself does not change.
  4878. \subsection{Liveness Analysis}
  4879. \label{sec:liveness-analysis-r2}
  4880. \index{liveness analysis}
  4881. Recall that for \LangVar{} we implemented liveness analysis for a single
  4882. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4883. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  4884. produces many basic blocks arranged in a control-flow graph. We
  4885. recommend that you create a new auxiliary function named
  4886. \code{uncover-live-CFG} that applies liveness analysis to a
  4887. control-flow graph.
  4888. The first question we need to consider is: what order should we
  4889. process the basic blocks in the control-flow graph? To perform
  4890. liveness analysis on a basic block, we need to know its live-after
  4891. set. If a basic block has no successor blocks (i.e. no out-edges in
  4892. the control flow graph), then it has an empty live-after set and we
  4893. can immediately apply liveness analysis to it. If a basic block has
  4894. some successors, then we need to complete liveness analysis on those
  4895. blocks first. Thankfully, the control flow graph does not contain any
  4896. cycles because \LangIf{} does not include loops. (In
  4897. Chapter~\ref{ch:loop} we add loops and study how to handle cycles in
  4898. the control-flow graph.)
  4899. %
  4900. Returning to the question of what order should we process the basic
  4901. blocks, the answer is reverse topological order. We recommend using
  4902. the \code{tsort} (topological sort) and \code{transpose} functions of
  4903. the Racket \code{graph} package to obtain this ordering.
  4904. \index{topological order}
  4905. \index{topological sort}
  4906. The next question is how to analyze the jump instructions. In
  4907. Section~\ref{sec:liveness-analysis-r1} we recommended that you
  4908. maintain an alist named \code{label->live} that maps each label to the
  4909. set of live locations at the beginning of the associated block. Now
  4910. that we have many basic blocks, the alist needs to be extended as we
  4911. process the blocks. In particular, after performing liveness analysis
  4912. on a block, we can take the live-before set for its first instruction
  4913. and associate that with the block's label in the alist.
  4914. %
  4915. As discussed in Section~\ref{sec:liveness-analysis-r1}, the
  4916. live-before set for a $\JMP{\itm{label}}$ instruction is given by the
  4917. mapping for $\itm{label}$ in \code{label->live}.
  4918. Now for $x86_1$ we also have the conditional jump
  4919. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. This one is
  4920. particularly interesting because during compilation we do not know, in
  4921. general, which way a conditional jump will go, so we do not know
  4922. whether to use the live-before set for the following instruction or
  4923. the live-before set for $\itm{label}$. The solution to this challenge
  4924. is based on the observation that there is no harm to the correctness
  4925. of the compiler if we classify more locations as live than the ones
  4926. that are truly live during a particular execution of the
  4927. instruction. Thus, we can take the union of the live-before sets from
  4928. the following instruction and from the mapping fro $\itm{label}$ in
  4929. \code{label->live}.
  4930. The helper functions for computing the variables in an instruction's
  4931. argument and for computing the variables read-from ($R$) or written-to
  4932. ($W$) by an instruction need to be updated to handle the new kinds of
  4933. arguments and instructions in \LangXASTIf{}.
  4934. \subsection{Build Interference}
  4935. \label{sec:build-interference-r2}
  4936. Many of the new instructions in \LangXASTIf{} can be handled in the same way
  4937. as the instructions in \LangXASTInt{}. Thus, if your code was already quite
  4938. general, it will not need to be changed to handle the new
  4939. instructions. If you code is not general enough, I recommend that you
  4940. change your code to be more general. For example, you can factor out
  4941. the computing of the the read and write sets for each kind of
  4942. instruction into two auxiliary functions.
  4943. Note that the \key{movzbq} instruction requires some special care,
  4944. just like the \key{movq} instruction. See rule number 3 in
  4945. Section~\ref{sec:build-interference}.
  4946. %% \subsection{Assign Homes}
  4947. %% \label{sec:assign-homes-r2}
  4948. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4949. %% to be updated to handle the \key{if} statement, simply by recursively
  4950. %% processing the child nodes. Hopefully your code already handles the
  4951. %% other new instructions, but if not, you can generalize your code.
  4952. \begin{exercise}\normalfont
  4953. Update the \code{register-allocation} pass so that it works for \LangIf{}
  4954. and test your compiler using your previously created programs on the
  4955. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4956. \end{exercise}
  4957. \section{Patch Instructions}
  4958. The second argument of the \key{cmpq} instruction must not be an
  4959. immediate value (such as an integer). So if you are comparing two
  4960. immediates, we recommend inserting a \key{movq} instruction to put the
  4961. second argument in \key{rax}. Also, recall that instructions may have
  4962. at most one memory reference.
  4963. %
  4964. The second argument of the \key{movzbq} must be a register.
  4965. %
  4966. There are no special restrictions on the x86 instructions \key{JmpIf}
  4967. and \key{Jmp}.
  4968. \begin{exercise}\normalfont
  4969. Update \code{patch-instructions} to handle the new x86 instructions.
  4970. Test your compiler using your previously created programs on the
  4971. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4972. \end{exercise}
  4973. \begin{figure}[tbp]
  4974. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4975. \node (Rif) at (0,2) {\large \LangIf{}};
  4976. \node (Rif-2) at (3,2) {\large \LangIf{}};
  4977. \node (Rif-3) at (6,2) {\large \LangIf{}};
  4978. \node (Rif-4) at (9,2) {\large \LangIf{}};
  4979. \node (Rif-5) at (12,2) {\large \LangIf{}};
  4980. \node (C1-1) at (3,0) {\large \LangCIf{}};
  4981. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  4982. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  4983. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  4984. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  4985. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  4986. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  4987. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  4988. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  4989. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  4990. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  4991. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  4992. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  4993. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4994. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4995. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4996. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4997. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  4998. \end{tikzpicture}
  4999. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5000. \label{fig:Rif-passes}
  5001. \end{figure}
  5002. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5003. compilation of \LangIf{}.
  5004. \section{An Example Translation}
  5005. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5006. \LangIf{} translated to x86, showing the results of
  5007. \code{explicate-control}, \code{select-instructions}, and the final
  5008. x86 assembly code.
  5009. \begin{figure}[tbp]
  5010. \begin{tabular}{lll}
  5011. \begin{minipage}{0.5\textwidth}
  5012. % s1_20.rkt
  5013. \begin{lstlisting}
  5014. (if (eq? (read) 1) 42 0)
  5015. \end{lstlisting}
  5016. $\Downarrow$
  5017. \begin{lstlisting}
  5018. start:
  5019. tmp7951 = (read);
  5020. if (eq? tmp7951 1) then
  5021. goto block7952;
  5022. else
  5023. goto block7953;
  5024. block7952:
  5025. return 42;
  5026. block7953:
  5027. return 0;
  5028. \end{lstlisting}
  5029. $\Downarrow$
  5030. \begin{lstlisting}
  5031. start:
  5032. callq read_int
  5033. movq %rax, tmp7951
  5034. cmpq $1, tmp7951
  5035. je block7952
  5036. jmp block7953
  5037. block7953:
  5038. movq $0, %rax
  5039. jmp conclusion
  5040. block7952:
  5041. movq $42, %rax
  5042. jmp conclusion
  5043. \end{lstlisting}
  5044. \end{minipage}
  5045. &
  5046. $\Rightarrow\qquad$
  5047. \begin{minipage}{0.4\textwidth}
  5048. \begin{lstlisting}
  5049. start:
  5050. callq read_int
  5051. movq %rax, %rcx
  5052. cmpq $1, %rcx
  5053. je block7952
  5054. jmp block7953
  5055. block7953:
  5056. movq $0, %rax
  5057. jmp conclusion
  5058. block7952:
  5059. movq $42, %rax
  5060. jmp conclusion
  5061. .globl main
  5062. main:
  5063. pushq %rbp
  5064. movq %rsp, %rbp
  5065. pushq %r13
  5066. pushq %r12
  5067. pushq %rbx
  5068. pushq %r14
  5069. subq $0, %rsp
  5070. jmp start
  5071. conclusion:
  5072. addq $0, %rsp
  5073. popq %r14
  5074. popq %rbx
  5075. popq %r12
  5076. popq %r13
  5077. popq %rbp
  5078. retq
  5079. \end{lstlisting}
  5080. \end{minipage}
  5081. \end{tabular}
  5082. \caption{Example compilation of an \key{if} expression to x86.}
  5083. \label{fig:if-example-x86}
  5084. \end{figure}
  5085. \section{Challenge: Remove Jumps}
  5086. \label{sec:opt-jumps}
  5087. %% Recall that in the example output of \code{explicate-control} in
  5088. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5089. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5090. %% block. The first goal of this challenge assignment is to remove those
  5091. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5092. %% \code{explicate-control} on the left and shows the result of bypassing
  5093. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5094. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5095. %% \code{block55}. The optimized code on the right of
  5096. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5097. %% \code{then} branch jumping directly to \code{block55}. The story is
  5098. %% similar for the \code{else} branch, as well as for the two branches in
  5099. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5100. %% have been optimized in this way, there are no longer any jumps to
  5101. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5102. %% \begin{figure}[tbp]
  5103. %% \begin{tabular}{lll}
  5104. %% \begin{minipage}{0.4\textwidth}
  5105. %% \begin{lstlisting}
  5106. %% block62:
  5107. %% tmp54 = (read);
  5108. %% if (eq? tmp54 2) then
  5109. %% goto block59;
  5110. %% else
  5111. %% goto block60;
  5112. %% block61:
  5113. %% tmp53 = (read);
  5114. %% if (eq? tmp53 0) then
  5115. %% goto block57;
  5116. %% else
  5117. %% goto block58;
  5118. %% block60:
  5119. %% goto block56;
  5120. %% block59:
  5121. %% goto block55;
  5122. %% block58:
  5123. %% goto block56;
  5124. %% block57:
  5125. %% goto block55;
  5126. %% block56:
  5127. %% return (+ 700 77);
  5128. %% block55:
  5129. %% return (+ 10 32);
  5130. %% start:
  5131. %% tmp52 = (read);
  5132. %% if (eq? tmp52 1) then
  5133. %% goto block61;
  5134. %% else
  5135. %% goto block62;
  5136. %% \end{lstlisting}
  5137. %% \end{minipage}
  5138. %% &
  5139. %% $\Rightarrow$
  5140. %% &
  5141. %% \begin{minipage}{0.55\textwidth}
  5142. %% \begin{lstlisting}
  5143. %% block62:
  5144. %% tmp54 = (read);
  5145. %% if (eq? tmp54 2) then
  5146. %% goto block55;
  5147. %% else
  5148. %% goto block56;
  5149. %% block61:
  5150. %% tmp53 = (read);
  5151. %% if (eq? tmp53 0) then
  5152. %% goto block55;
  5153. %% else
  5154. %% goto block56;
  5155. %% block56:
  5156. %% return (+ 700 77);
  5157. %% block55:
  5158. %% return (+ 10 32);
  5159. %% start:
  5160. %% tmp52 = (read);
  5161. %% if (eq? tmp52 1) then
  5162. %% goto block61;
  5163. %% else
  5164. %% goto block62;
  5165. %% \end{lstlisting}
  5166. %% \end{minipage}
  5167. %% \end{tabular}
  5168. %% \caption{Optimize jumps by removing trivial blocks.}
  5169. %% \label{fig:optimize-jumps}
  5170. %% \end{figure}
  5171. %% The name of this pass is \code{optimize-jumps}. We recommend
  5172. %% implementing this pass in two phases. The first phrase builds a hash
  5173. %% table that maps labels to possibly improved labels. The second phase
  5174. %% changes the target of each \code{goto} to use the improved label. If
  5175. %% the label is for a trivial block, then the hash table should map the
  5176. %% label to the first non-trivial block that can be reached from this
  5177. %% label by jumping through trivial blocks. If the label is for a
  5178. %% non-trivial block, then the hash table should map the label to itself;
  5179. %% we do not want to change jumps to non-trivial blocks.
  5180. %% The first phase can be accomplished by constructing an empty hash
  5181. %% table, call it \code{short-cut}, and then iterating over the control
  5182. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5183. %% then update the hash table, mapping the block's source to the target
  5184. %% of the \code{goto}. Also, the hash table may already have mapped some
  5185. %% labels to the block's source, to you must iterate through the hash
  5186. %% table and update all of those so that they instead map to the target
  5187. %% of the \code{goto}.
  5188. %% For the second phase, we recommend iterating through the $\Tail$ of
  5189. %% each block in the program, updating the target of every \code{goto}
  5190. %% according to the mapping in \code{short-cut}.
  5191. %% \begin{exercise}\normalfont
  5192. %% Implement the \code{optimize-jumps} pass as a transformation from
  5193. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5194. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5195. %% example programs. Then check that your compiler still passes all of
  5196. %% your tests.
  5197. %% \end{exercise}
  5198. There is an opportunity for optimizing jumps that is apparent in the
  5199. example of Figure~\ref{fig:if-example-x86}. The \code{start} block end
  5200. with a jump to \code{block7953} and there are no other jumps to
  5201. \code{block7953} in the rest of the program. In this situation we can
  5202. avoid the runtime overhead of this jump by merging \code{block7953}
  5203. into the preceding block, in this case the \code{start} block.
  5204. Figure~\ref{fig:remove-jumps} shows the output of
  5205. \code{select-instructions} on the left and the result of this
  5206. optimization on the right.
  5207. \begin{figure}[tbp]
  5208. \begin{tabular}{lll}
  5209. \begin{minipage}{0.5\textwidth}
  5210. % s1_20.rkt
  5211. \begin{lstlisting}
  5212. start:
  5213. callq read_int
  5214. movq %rax, tmp7951
  5215. cmpq $1, tmp7951
  5216. je block7952
  5217. jmp block7953
  5218. block7953:
  5219. movq $0, %rax
  5220. jmp conclusion
  5221. block7952:
  5222. movq $42, %rax
  5223. jmp conclusion
  5224. \end{lstlisting}
  5225. \end{minipage}
  5226. &
  5227. $\Rightarrow\qquad$
  5228. \begin{minipage}{0.4\textwidth}
  5229. \begin{lstlisting}
  5230. start:
  5231. callq read_int
  5232. movq %rax, tmp7951
  5233. cmpq $1, tmp7951
  5234. je block7952
  5235. movq $0, %rax
  5236. jmp conclusion
  5237. block7952:
  5238. movq $42, %rax
  5239. jmp conclusion
  5240. \end{lstlisting}
  5241. \end{minipage}
  5242. \end{tabular}
  5243. \caption{Merging basic blocks by removing unnecessary jumps.}
  5244. \label{fig:remove-jumps}
  5245. \end{figure}
  5246. \begin{exercise}\normalfont
  5247. Implement a pass named \code{remove-jumps} that merges basic blocks
  5248. into their preceding basic block, when there is only one preceding
  5249. block. The pass should translate from pseudo $x86_1$ to pseudo
  5250. $x86_1$ and it should come immediately after
  5251. \code{select-instructions}. Check that \code{remove-jumps}
  5252. accomplishes the goal of merging basic blocks on several test
  5253. programs and check that your compiler passes all of your tests.
  5254. \end{exercise}
  5255. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5256. \chapter{Tuples and Garbage Collection}
  5257. \label{ch:tuples}
  5258. \index{tuple}
  5259. \index{vector}
  5260. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  5261. add simple structures. \\ --Jeremy}
  5262. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  5263. things to discuss in this chapter. \\ --Jeremy}
  5264. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5265. all the IR grammars are spelled out! \\ --Jeremy}
  5266. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5267. but keep type annotations on vector creation and local variables, function
  5268. parameters, etc. \\ --Jeremy}
  5269. \margincomment{\scriptsize Be more explicit about how to deal with
  5270. the root stack. \\ --Jeremy}
  5271. In this chapter we study the implementation of mutable tuples (called
  5272. ``vectors'' in Racket). This language feature is the first to use the
  5273. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5274. indefinite, that is, a tuple lives forever from the programmer's
  5275. viewpoint. Of course, from an implementer's viewpoint, it is important
  5276. to reclaim the space associated with a tuple when it is no longer
  5277. needed, which is why we also study \emph{garbage collection}
  5278. \emph{garbage collection}
  5279. techniques in this chapter.
  5280. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5281. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5282. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5283. \code{void} value. The reason for including the later is that the
  5284. \code{vector-set!} operation returns a value of type
  5285. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5286. called the \code{Unit} type in the programming languages
  5287. literature. Racket's \code{Void} type is inhabited by a single value
  5288. \code{void} which corresponds to \code{unit} or \code{()} in the
  5289. literature~\citep{Pierce:2002hj}.}.
  5290. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5291. copying live objects back and forth between two halves of the
  5292. heap. The garbage collector requires coordination with the compiler so
  5293. that it can see all of the \emph{root} pointers, that is, pointers in
  5294. registers or on the procedure call stack.
  5295. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5296. discuss all the necessary changes and additions to the compiler
  5297. passes, including a new compiler pass named \code{expose-allocation}.
  5298. \section{The \LangVec{} Language}
  5299. \label{sec:r3}
  5300. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  5301. \LangVec{} and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  5302. \LangVec{} language includes three new forms: \code{vector} for creating a
  5303. tuple, \code{vector-ref} for reading an element of a tuple, and
  5304. \code{vector-set!} for writing to an element of a tuple. The program
  5305. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5306. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5307. the 3-tuple, demonstrating that tuples are first-class values. The
  5308. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5309. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5310. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5311. 1-tuple. So the result of the program is \code{42}.
  5312. \begin{figure}[tbp]
  5313. \centering
  5314. \fbox{
  5315. \begin{minipage}{0.96\textwidth}
  5316. \[
  5317. \begin{array}{lcl}
  5318. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5319. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5320. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5321. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5322. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5323. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5324. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5325. \mid \LP\key{not}\;\Exp\RP } \\
  5326. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5327. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5328. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5329. \mid \LP\key{vector-length}\;\Exp\RP \\
  5330. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5331. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5332. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5333. \LangVec{} &::=& \Exp
  5334. \end{array}
  5335. \]
  5336. \end{minipage}
  5337. }
  5338. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5339. (Figure~\ref{fig:r2-concrete-syntax}).}
  5340. \label{fig:r3-concrete-syntax}
  5341. \end{figure}
  5342. \begin{figure}[tbp]
  5343. \begin{lstlisting}
  5344. (let ([t (vector 40 #t (vector 2))])
  5345. (if (vector-ref t 1)
  5346. (+ (vector-ref t 0)
  5347. (vector-ref (vector-ref t 2) 0))
  5348. 44))
  5349. \end{lstlisting}
  5350. \caption{Example program that creates tuples and reads from them.}
  5351. \label{fig:vector-eg}
  5352. \end{figure}
  5353. \begin{figure}[tp]
  5354. \centering
  5355. \fbox{
  5356. \begin{minipage}{0.96\textwidth}
  5357. \[
  5358. \begin{array}{lcl}
  5359. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5360. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5361. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5362. \mid \BOOL{\itm{bool}}
  5363. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5364. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5365. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5366. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5367. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5368. \end{array}
  5369. \]
  5370. \end{minipage}
  5371. }
  5372. \caption{The abstract syntax of \LangVec{}.}
  5373. \label{fig:r3-syntax}
  5374. \end{figure}
  5375. \index{allocate}
  5376. \index{heap allocate}
  5377. Tuples are our first encounter with heap-allocated data, which raises
  5378. several interesting issues. First, variable binding performs a
  5379. shallow-copy when dealing with tuples, which means that different
  5380. variables can refer to the same tuple, that is, different variables
  5381. can be \emph{aliases} for the same entity. Consider the following
  5382. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5383. Thus, the mutation through \code{t2} is visible when referencing the
  5384. tuple from \code{t1}, so the result of this program is \code{42}.
  5385. \index{alias}\index{mutation}
  5386. \begin{center}
  5387. \begin{minipage}{0.96\textwidth}
  5388. \begin{lstlisting}
  5389. (let ([t1 (vector 3 7)])
  5390. (let ([t2 t1])
  5391. (let ([_ (vector-set! t2 0 42)])
  5392. (vector-ref t1 0))))
  5393. \end{lstlisting}
  5394. \end{minipage}
  5395. \end{center}
  5396. The next issue concerns the lifetime of tuples. Of course, they are
  5397. created by the \code{vector} form, but when does their lifetime end?
  5398. Notice that \LangVec{} does not include an operation for deleting
  5399. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5400. of static scoping. For example, the following program returns
  5401. \code{42} even though the variable \code{w} goes out of scope prior to
  5402. the \code{vector-ref} that reads from the vector it was bound to.
  5403. \begin{center}
  5404. \begin{minipage}{0.96\textwidth}
  5405. \begin{lstlisting}
  5406. (let ([v (vector (vector 44))])
  5407. (let ([x (let ([w (vector 42)])
  5408. (let ([_ (vector-set! v 0 w)])
  5409. 0))])
  5410. (+ x (vector-ref (vector-ref v 0) 0))))
  5411. \end{lstlisting}
  5412. \end{minipage}
  5413. \end{center}
  5414. From the perspective of programmer-observable behavior, tuples live
  5415. forever. Of course, if they really lived forever, then many programs
  5416. would run out of memory.\footnote{The \LangVec{} language does not have
  5417. looping or recursive functions, so it is nigh impossible to write a
  5418. program in \LangVec{} that will run out of memory. However, we add
  5419. recursive functions in the next Chapter!} A Racket implementation
  5420. must therefore perform automatic garbage collection.
  5421. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5422. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5423. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5424. terms of the corresponding operations in Racket. One subtle point is
  5425. that the \code{vector-set!} operation returns the \code{\#<void>}
  5426. value. The \code{\#<void>} value can be passed around just like other
  5427. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5428. compared for equality with another \code{\#<void>} value. However,
  5429. there are no other operations specific to the the \code{\#<void>}
  5430. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5431. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5432. otherwise.
  5433. \begin{figure}[tbp]
  5434. \begin{lstlisting}
  5435. (define interp-Rvec-class
  5436. (class interp-Rif-class
  5437. (super-new)
  5438. (define/override (interp-op op)
  5439. (match op
  5440. ['eq? (lambda (v1 v2)
  5441. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5442. (and (boolean? v1) (boolean? v2))
  5443. (and (vector? v1) (vector? v2))
  5444. (and (void? v1) (void? v2)))
  5445. (eq? v1 v2)]))]
  5446. ['vector vector]
  5447. ['vector-length vector-length]
  5448. ['vector-ref vector-ref]
  5449. ['vector-set! vector-set!]
  5450. [else (super interp-op op)]
  5451. ))
  5452. (define/override ((interp-exp env) e)
  5453. (define recur (interp-exp env))
  5454. (match e
  5455. [(HasType e t) (recur e)]
  5456. [(Void) (void)]
  5457. [else ((super interp-exp env) e)]
  5458. ))
  5459. ))
  5460. (define (interp-Rvec p)
  5461. (send (new interp-Rvec-class) interp-program p))
  5462. \end{lstlisting}
  5463. \caption{Interpreter for the \LangVec{} language.}
  5464. \label{fig:interp-Rvec}
  5465. \end{figure}
  5466. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5467. deserves some explanation. When allocating a vector, we need to know
  5468. which elements of the vector are pointers (i.e. are also vectors). We
  5469. can obtain this information during type checking. The type checker in
  5470. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5471. expression, it also wraps every \key{vector} creation with the form
  5472. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5473. %
  5474. To create the s-expression for the \code{Vector} type in
  5475. Figure~\ref{fig:type-check-Rvec}, we use the
  5476. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5477. operator} \code{,@} to insert the list \code{t*} without its usual
  5478. start and end parentheses. \index{unquote-slicing}
  5479. \begin{figure}[tp]
  5480. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5481. (define type-check-Rvec-class
  5482. (class type-check-Rif-class
  5483. (super-new)
  5484. (inherit check-type-equal?)
  5485. (define/override (type-check-exp env)
  5486. (lambda (e)
  5487. (define recur (type-check-exp env))
  5488. (match e
  5489. [(Void) (values (Void) 'Void)]
  5490. [(Prim 'vector es)
  5491. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5492. (define t `(Vector ,@t*))
  5493. (values (HasType (Prim 'vector e*) t) t)]
  5494. [(Prim 'vector-ref (list e1 (Int i)))
  5495. (define-values (e1^ t) (recur e1))
  5496. (match t
  5497. [`(Vector ,ts ...)
  5498. (unless (and (0 . <= . i) (i . < . (length ts)))
  5499. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5500. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5501. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5502. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5503. (define-values (e-vec t-vec) (recur e1))
  5504. (define-values (e-arg^ t-arg) (recur arg))
  5505. (match t-vec
  5506. [`(Vector ,ts ...)
  5507. (unless (and (0 . <= . i) (i . < . (length ts)))
  5508. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5509. (check-type-equal? (list-ref ts i) t-arg e)
  5510. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5511. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5512. [(Prim 'vector-length (list e))
  5513. (define-values (e^ t) (recur e))
  5514. (match t
  5515. [`(Vector ,ts ...)
  5516. (values (Prim 'vector-length (list e^)) 'Integer)]
  5517. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5518. [(Prim 'eq? (list arg1 arg2))
  5519. (define-values (e1 t1) (recur arg1))
  5520. (define-values (e2 t2) (recur arg2))
  5521. (match* (t1 t2)
  5522. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5523. [(other wise) (check-type-equal? t1 t2 e)])
  5524. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5525. [(HasType (Prim 'vector es) t)
  5526. ((type-check-exp env) (Prim 'vector es))]
  5527. [(HasType e1 t)
  5528. (define-values (e1^ t^) (recur e1))
  5529. (check-type-equal? t t^ e)
  5530. (values (HasType e1^ t) t)]
  5531. [else ((super type-check-exp env) e)]
  5532. )))
  5533. ))
  5534. (define (type-check-Rvec p)
  5535. (send (new type-check-Rvec-class) type-check-program p))
  5536. \end{lstlisting}
  5537. \caption{Type checker for the \LangVec{} language.}
  5538. \label{fig:type-check-Rvec}
  5539. \end{figure}
  5540. \section{Garbage Collection}
  5541. \label{sec:GC}
  5542. Here we study a relatively simple algorithm for garbage collection
  5543. that is the basis of state-of-the-art garbage
  5544. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5545. particular, we describe a two-space copying
  5546. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5547. perform the
  5548. copy~\citep{Cheney:1970aa}.
  5549. \index{copying collector}
  5550. \index{two-space copying collector}
  5551. Figure~\ref{fig:copying-collector} gives a
  5552. coarse-grained depiction of what happens in a two-space collector,
  5553. showing two time steps, prior to garbage collection (on the top) and
  5554. after garbage collection (on the bottom). In a two-space collector,
  5555. the heap is divided into two parts named the FromSpace and the
  5556. ToSpace. Initially, all allocations go to the FromSpace until there is
  5557. not enough room for the next allocation request. At that point, the
  5558. garbage collector goes to work to make more room.
  5559. \index{ToSpace}
  5560. \index{FromSpace}
  5561. The garbage collector must be careful not to reclaim tuples that will
  5562. be used by the program in the future. Of course, it is impossible in
  5563. general to predict what a program will do, but we can over approximate
  5564. the will-be-used tuples by preserving all tuples that could be
  5565. accessed by \emph{any} program given the current computer state. A
  5566. program could access any tuple whose address is in a register or on
  5567. the procedure call stack. These addresses are called the \emph{root
  5568. set}\index{root set}. In addition, a program could access any tuple that is
  5569. transitively reachable from the root set. Thus, it is safe for the
  5570. garbage collector to reclaim the tuples that are not reachable in this
  5571. way.
  5572. So the goal of the garbage collector is twofold:
  5573. \begin{enumerate}
  5574. \item preserve all tuple that are reachable from the root set via a
  5575. path of pointers, that is, the \emph{live} tuples, and
  5576. \item reclaim the memory of everything else, that is, the
  5577. \emph{garbage}.
  5578. \end{enumerate}
  5579. A copying collector accomplishes this by copying all of the live
  5580. objects from the FromSpace into the ToSpace and then performs a sleight
  5581. of hand, treating the ToSpace as the new FromSpace and the old
  5582. FromSpace as the new ToSpace. In the example of
  5583. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5584. root set, one in a register and two on the stack. All of the live
  5585. objects have been copied to the ToSpace (the right-hand side of
  5586. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5587. pointer relationships. For example, the pointer in the register still
  5588. points to a 2-tuple whose first element is a 3-tuple and whose second
  5589. element is a 2-tuple. There are four tuples that are not reachable
  5590. from the root set and therefore do not get copied into the ToSpace.
  5591. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5592. created by a well-typed program in \LangVec{} because it contains a
  5593. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5594. We design the garbage collector to deal with cycles to begin with so
  5595. we will not need to revisit this issue.
  5596. \begin{figure}[tbp]
  5597. \centering
  5598. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5599. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5600. \caption{A copying collector in action.}
  5601. \label{fig:copying-collector}
  5602. \end{figure}
  5603. There are many alternatives to copying collectors (and their bigger
  5604. siblings, the generational collectors) when its comes to garbage
  5605. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5606. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5607. collectors are that allocation is fast (just a comparison and pointer
  5608. increment), there is no fragmentation, cyclic garbage is collected,
  5609. and the time complexity of collection only depends on the amount of
  5610. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5611. main disadvantages of a two-space copying collector is that it uses a
  5612. lot of space and takes a long time to perform the copy, though these
  5613. problems are ameliorated in generational collectors. Racket and
  5614. Scheme programs tend to allocate many small objects and generate a lot
  5615. of garbage, so copying and generational collectors are a good fit.
  5616. Garbage collection is an active research topic, especially concurrent
  5617. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5618. developing new techniques and revisiting old
  5619. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5620. meet every year at the International Symposium on Memory Management to
  5621. present these findings.
  5622. \subsection{Graph Copying via Cheney's Algorithm}
  5623. \label{sec:cheney}
  5624. \index{Cheney's algorithm}
  5625. Let us take a closer look at the copying of the live objects. The
  5626. allocated objects and pointers can be viewed as a graph and we need to
  5627. copy the part of the graph that is reachable from the root set. To
  5628. make sure we copy all of the reachable vertices in the graph, we need
  5629. an exhaustive graph traversal algorithm, such as depth-first search or
  5630. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5631. such algorithms take into account the possibility of cycles by marking
  5632. which vertices have already been visited, so as to ensure termination
  5633. of the algorithm. These search algorithms also use a data structure
  5634. such as a stack or queue as a to-do list to keep track of the vertices
  5635. that need to be visited. We use breadth-first search and a trick
  5636. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5637. and copying tuples into the ToSpace.
  5638. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5639. copy progresses. The queue is represented by a chunk of contiguous
  5640. memory at the beginning of the ToSpace, using two pointers to track
  5641. the front and the back of the queue. The algorithm starts by copying
  5642. all tuples that are immediately reachable from the root set into the
  5643. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5644. old tuple to indicate that it has been visited. We discuss how this
  5645. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5646. pointers inside the copied tuples in the queue still point back to the
  5647. FromSpace. Once the initial queue has been created, the algorithm
  5648. enters a loop in which it repeatedly processes the tuple at the front
  5649. of the queue and pops it off the queue. To process a tuple, the
  5650. algorithm copies all the tuple that are directly reachable from it to
  5651. the ToSpace, placing them at the back of the queue. The algorithm then
  5652. updates the pointers in the popped tuple so they point to the newly
  5653. copied tuples.
  5654. \begin{figure}[tbp]
  5655. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5656. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5657. \label{fig:cheney}
  5658. \end{figure}
  5659. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5660. tuple whose second element is $42$ to the back of the queue. The other
  5661. pointer goes to a tuple that has already been copied, so we do not
  5662. need to copy it again, but we do need to update the pointer to the new
  5663. location. This can be accomplished by storing a \emph{forwarding
  5664. pointer} to the new location in the old tuple, back when we initially
  5665. copied the tuple into the ToSpace. This completes one step of the
  5666. algorithm. The algorithm continues in this way until the front of the
  5667. queue is empty, that is, until the front catches up with the back.
  5668. \subsection{Data Representation}
  5669. \label{sec:data-rep-gc}
  5670. The garbage collector places some requirements on the data
  5671. representations used by our compiler. First, the garbage collector
  5672. needs to distinguish between pointers and other kinds of data. There
  5673. are several ways to accomplish this.
  5674. \begin{enumerate}
  5675. \item Attached a tag to each object that identifies what type of
  5676. object it is~\citep{McCarthy:1960dz}.
  5677. \item Store different types of objects in different
  5678. regions~\citep{Steele:1977ab}.
  5679. \item Use type information from the program to either generate
  5680. type-specific code for collecting or to generate tables that can
  5681. guide the
  5682. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5683. \end{enumerate}
  5684. Dynamically typed languages, such as Lisp, need to tag objects
  5685. anyways, so option 1 is a natural choice for those languages.
  5686. However, \LangVec{} is a statically typed language, so it would be
  5687. unfortunate to require tags on every object, especially small and
  5688. pervasive objects like integers and Booleans. Option 3 is the
  5689. best-performing choice for statically typed languages, but comes with
  5690. a relatively high implementation complexity. To keep this chapter
  5691. within a 2-week time budget, we recommend a combination of options 1
  5692. and 2, using separate strategies for the stack and the heap.
  5693. Regarding the stack, we recommend using a separate stack for pointers,
  5694. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5695. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5696. is, when a local variable needs to be spilled and is of type
  5697. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5698. stack instead of the normal procedure call stack. Furthermore, we
  5699. always spill vector-typed variables if they are live during a call to
  5700. the collector, thereby ensuring that no pointers are in registers
  5701. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5702. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5703. the data layout using a root stack. The root stack contains the two
  5704. pointers from the regular stack and also the pointer in the second
  5705. register.
  5706. \begin{figure}[tbp]
  5707. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5708. \caption{Maintaining a root stack to facilitate garbage collection.}
  5709. \label{fig:shadow-stack}
  5710. \end{figure}
  5711. The problem of distinguishing between pointers and other kinds of data
  5712. also arises inside of each tuple on the heap. We solve this problem by
  5713. attaching a tag, an extra 64-bits, to each
  5714. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5715. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5716. that we have drawn the bits in a big-endian way, from right-to-left,
  5717. with bit location 0 (the least significant bit) on the far right,
  5718. which corresponds to the direction of the x86 shifting instructions
  5719. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5720. is dedicated to specifying which elements of the tuple are pointers,
  5721. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5722. indicates there is a pointer and a 0 bit indicates some other kind of
  5723. data. The pointer mask starts at bit location 7. We have limited
  5724. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5725. the pointer mask. The tag also contains two other pieces of
  5726. information. The length of the tuple (number of elements) is stored in
  5727. bits location 1 through 6. Finally, the bit at location 0 indicates
  5728. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5729. value 1, then this tuple has not yet been copied. If the bit has
  5730. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5731. of a pointer are always zero anyways because our tuples are 8-byte
  5732. aligned.)
  5733. \begin{figure}[tbp]
  5734. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5735. \caption{Representation of tuples in the heap.}
  5736. \label{fig:tuple-rep}
  5737. \end{figure}
  5738. \subsection{Implementation of the Garbage Collector}
  5739. \label{sec:organize-gz}
  5740. \index{prelude}
  5741. An implementation of the copying collector is provided in the
  5742. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5743. interface to the garbage collector that is used by the compiler. The
  5744. \code{initialize} function creates the FromSpace, ToSpace, and root
  5745. stack and should be called in the prelude of the \code{main}
  5746. function. The arguments of \code{initialize} are the root stack size
  5747. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5748. good choice for both. The \code{initialize} function puts the address
  5749. of the beginning of the FromSpace into the global variable
  5750. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5751. the address that is 1-past the last element of the FromSpace. (We use
  5752. half-open intervals to represent chunks of
  5753. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5754. points to the first element of the root stack.
  5755. As long as there is room left in the FromSpace, your generated code
  5756. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5757. %
  5758. The amount of room left in FromSpace is the difference between the
  5759. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5760. function should be called when there is not enough room left in the
  5761. FromSpace for the next allocation. The \code{collect} function takes
  5762. a pointer to the current top of the root stack (one past the last item
  5763. that was pushed) and the number of bytes that need to be
  5764. allocated. The \code{collect} function performs the copying collection
  5765. and leaves the heap in a state such that the next allocation will
  5766. succeed.
  5767. \begin{figure}[tbp]
  5768. \begin{lstlisting}
  5769. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5770. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5771. int64_t* free_ptr;
  5772. int64_t* fromspace_begin;
  5773. int64_t* fromspace_end;
  5774. int64_t** rootstack_begin;
  5775. \end{lstlisting}
  5776. \caption{The compiler's interface to the garbage collector.}
  5777. \label{fig:gc-header}
  5778. \end{figure}
  5779. %% \begin{exercise}
  5780. %% In the file \code{runtime.c} you will find the implementation of
  5781. %% \code{initialize} and a partial implementation of \code{collect}.
  5782. %% The \code{collect} function calls another function, \code{cheney},
  5783. %% to perform the actual copy, and that function is left to the reader
  5784. %% to implement. The following is the prototype for \code{cheney}.
  5785. %% \begin{lstlisting}
  5786. %% static void cheney(int64_t** rootstack_ptr);
  5787. %% \end{lstlisting}
  5788. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5789. %% rootstack (which is an array of pointers). The \code{cheney} function
  5790. %% also communicates with \code{collect} through the global
  5791. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5792. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5793. %% the ToSpace:
  5794. %% \begin{lstlisting}
  5795. %% static int64_t* tospace_begin;
  5796. %% static int64_t* tospace_end;
  5797. %% \end{lstlisting}
  5798. %% The job of the \code{cheney} function is to copy all the live
  5799. %% objects (reachable from the root stack) into the ToSpace, update
  5800. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5801. %% update the root stack so that it points to the objects in the
  5802. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5803. %% and ToSpace.
  5804. %% \end{exercise}
  5805. %% \section{Compiler Passes}
  5806. %% \label{sec:code-generation-gc}
  5807. The introduction of garbage collection has a non-trivial impact on our
  5808. compiler passes. We introduce a new compiler pass named
  5809. \code{expose-allocation}. We make
  5810. significant changes to \code{select-instructions},
  5811. \code{build-interference}, \code{allocate-registers}, and
  5812. \code{print-x86} and make minor changes in several more passes. The
  5813. following program will serve as our running example. It creates two
  5814. tuples, one nested inside the other. Both tuples have length one. The
  5815. program accesses the element in the inner tuple tuple via two vector
  5816. references.
  5817. % tests/s2_17.rkt
  5818. \begin{lstlisting}
  5819. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5820. \end{lstlisting}
  5821. \section{Shrink}
  5822. \label{sec:shrink-Rvec}
  5823. Recall that the \code{shrink} pass translates the primitives operators
  5824. into a smaller set of primitives. Because this pass comes after type
  5825. checking, but before the passes that require the type information in
  5826. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5827. to wrap \code{HasType} around each AST node that it generates.
  5828. \section{Expose Allocation}
  5829. \label{sec:expose-allocation}
  5830. The pass \code{expose-allocation} lowers the \code{vector} creation
  5831. form into a conditional call to the collector followed by the
  5832. allocation. We choose to place the \code{expose-allocation} pass
  5833. before \code{remove-complex-opera*} because the code generated by
  5834. \code{expose-allocation} contains complex operands. We also place
  5835. \code{expose-allocation} before \code{explicate-control} because
  5836. \code{expose-allocation} introduces new variables using \code{let},
  5837. but \code{let} is gone after \code{explicate-control}.
  5838. The output of \code{expose-allocation} is a language \LangAlloc{} that
  5839. extends \LangVec{} with the three new forms that we use in the translation
  5840. of the \code{vector} form.
  5841. \[
  5842. \begin{array}{lcl}
  5843. \Exp &::=& \cdots
  5844. \mid (\key{collect} \,\itm{int})
  5845. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5846. \mid (\key{global-value} \,\itm{name})
  5847. \end{array}
  5848. \]
  5849. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5850. $n$ bytes. It will become a call to the \code{collect} function in
  5851. \code{runtime.c} in \code{select-instructions}. The
  5852. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5853. \index{allocate}
  5854. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5855. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5856. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5857. a global variable, such as \code{free\_ptr}.
  5858. In the following, we show the transformation for the \code{vector}
  5859. form into 1) a sequence of let-bindings for the initializing
  5860. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5861. \code{allocate}, and 4) the initialization of the vector. In the
  5862. following, \itm{len} refers to the length of the vector and
  5863. \itm{bytes} is how many total bytes need to be allocated for the
  5864. vector, which is 8 for the tag plus \itm{len} times 8.
  5865. \begin{lstlisting}
  5866. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5867. |$\Longrightarrow$|
  5868. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5869. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5870. (global-value fromspace_end))
  5871. (void)
  5872. (collect |\itm{bytes}|))])
  5873. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5874. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5875. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5876. |$v$|) ... )))) ...)
  5877. \end{lstlisting}
  5878. In the above, we suppressed all of the \code{has-type} forms in the
  5879. output for the sake of readability. The placement of the initializing
  5880. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5881. sequence of \code{vector-set!} is important, as those expressions may
  5882. trigger garbage collection and we cannot have an allocated but
  5883. uninitialized tuple on the heap during a collection.
  5884. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5885. \code{expose-allocation} pass on our running example.
  5886. \begin{figure}[tbp]
  5887. % tests/s2_17.rkt
  5888. \begin{lstlisting}
  5889. (vector-ref
  5890. (vector-ref
  5891. (let ([vecinit7976
  5892. (let ([vecinit7972 42])
  5893. (let ([collectret7974
  5894. (if (< (+ (global-value free_ptr) 16)
  5895. (global-value fromspace_end))
  5896. (void)
  5897. (collect 16)
  5898. )])
  5899. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5900. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5901. alloc7971)
  5902. )
  5903. )
  5904. )
  5905. ])
  5906. (let ([collectret7978
  5907. (if (< (+ (global-value free_ptr) 16)
  5908. (global-value fromspace_end))
  5909. (void)
  5910. (collect 16)
  5911. )])
  5912. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5913. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5914. alloc7975)
  5915. )
  5916. )
  5917. )
  5918. 0)
  5919. 0)
  5920. \end{lstlisting}
  5921. \caption{Output of the \code{expose-allocation} pass, minus
  5922. all of the \code{has-type} forms.}
  5923. \label{fig:expose-alloc-output}
  5924. \end{figure}
  5925. \section{Remove Complex Operands}
  5926. \label{sec:remove-complex-opera-Rvec}
  5927. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5928. should all be treated as complex operands.
  5929. %% A new case for
  5930. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  5931. %% handled carefully to prevent the \code{Prim} node from being separated
  5932. %% from its enclosing \code{HasType}.
  5933. Figure~\ref{fig:r3-anf-syntax}
  5934. shows the grammar for the output language \LangVecANF{} of this
  5935. pass, which is \LangVec{} in administrative normal form.
  5936. \begin{figure}[tp]
  5937. \centering
  5938. \fbox{
  5939. \begin{minipage}{0.96\textwidth}
  5940. \small
  5941. \[
  5942. \begin{array}{rcl}
  5943. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  5944. \mid \VOID{} \\
  5945. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5946. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5947. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5948. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  5949. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  5950. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  5951. \mid \LP\key{GlobalValue}~\Var\RP\\
  5952. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  5953. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  5954. \end{array}
  5955. \]
  5956. \end{minipage}
  5957. }
  5958. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  5959. \label{fig:r3-anf-syntax}
  5960. \end{figure}
  5961. \section{Explicate Control and the \LangCVec{} language}
  5962. \label{sec:explicate-control-r3}
  5963. \begin{figure}[tp]
  5964. \fbox{
  5965. \begin{minipage}{0.96\textwidth}
  5966. \small
  5967. \[
  5968. \begin{array}{lcl}
  5969. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5970. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5971. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5972. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5973. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5974. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  5975. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5976. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  5977. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  5978. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5979. \mid \LP\key{Collect} \,\itm{int}\RP \\
  5980. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5981. \mid \GOTO{\itm{label}} } \\
  5982. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5983. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  5984. \end{array}
  5985. \]
  5986. \end{minipage}
  5987. }
  5988. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  5989. (Figure~\ref{fig:c1-syntax}).}
  5990. \label{fig:c2-syntax}
  5991. \end{figure}
  5992. The output of \code{explicate-control} is a program in the
  5993. intermediate language \LangCVec{}, whose abstract syntax is defined in
  5994. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  5995. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  5996. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  5997. \key{vector-set!}, and \key{global-value} expressions and the
  5998. \code{collect} statement. The \code{explicate-control} pass can treat
  5999. these new forms much like the other expression forms that we've
  6000. already encoutered.
  6001. \section{Select Instructions and the \LangXASTGlobal{} Language}
  6002. \label{sec:select-instructions-gc}
  6003. \index{instruction selection}
  6004. %% void (rep as zero)
  6005. %% allocate
  6006. %% collect (callq collect)
  6007. %% vector-ref
  6008. %% vector-set!
  6009. %% global (postpone)
  6010. In this pass we generate x86 code for most of the new operations that
  6011. were needed to compile tuples, including \code{Allocate},
  6012. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6013. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6014. the later has a different concrete syntax (see
  6015. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6016. \index{x86}
  6017. The \code{vector-ref} and \code{vector-set!} forms translate into
  6018. \code{movq} instructions. (The plus one in the offset is to get past
  6019. the tag at the beginning of the tuple representation.)
  6020. \begin{lstlisting}
  6021. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6022. |$\Longrightarrow$|
  6023. movq |$\itm{vec}'$|, %r11
  6024. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6025. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6026. |$\Longrightarrow$|
  6027. movq |$\itm{vec}'$|, %r11
  6028. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6029. movq $0, |$\itm{lhs'}$|
  6030. \end{lstlisting}
  6031. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6032. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6033. register \code{r11} ensures that offset expression
  6034. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6035. removing \code{r11} from consideration by the register allocating.
  6036. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6037. \code{rax}. Then the generated code for \code{vector-set!} would be
  6038. \begin{lstlisting}
  6039. movq |$\itm{vec}'$|, %rax
  6040. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6041. movq $0, |$\itm{lhs}'$|
  6042. \end{lstlisting}
  6043. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6044. \code{patch-instructions} would insert a move through \code{rax}
  6045. as follows.
  6046. \begin{lstlisting}
  6047. movq |$\itm{vec}'$|, %rax
  6048. movq |$\itm{arg}'$|, %rax
  6049. movq %rax, |$8(n+1)$|(%rax)
  6050. movq $0, |$\itm{lhs}'$|
  6051. \end{lstlisting}
  6052. But the above sequence of instructions does not work because we're
  6053. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6054. $\itm{arg}'$) at the same time!
  6055. We compile the \code{allocate} form to operations on the
  6056. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6057. is the next free address in the FromSpace, so we copy it into
  6058. \code{r11} and then move it forward by enough space for the tuple
  6059. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6060. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6061. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6062. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6063. tag is organized. We recommend using the Racket operations
  6064. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6065. during compilation. The type annotation in the \code{vector} form is
  6066. used to determine the pointer mask region of the tag.
  6067. \begin{lstlisting}
  6068. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6069. |$\Longrightarrow$|
  6070. movq free_ptr(%rip), %r11
  6071. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6072. movq $|$\itm{tag}$|, 0(%r11)
  6073. movq %r11, |$\itm{lhs}'$|
  6074. \end{lstlisting}
  6075. The \code{collect} form is compiled to a call to the \code{collect}
  6076. function in the runtime. The arguments to \code{collect} are 1) the
  6077. top of the root stack and 2) the number of bytes that need to be
  6078. allocated. We use another dedicated register, \code{r15}, to
  6079. store the pointer to the top of the root stack. So \code{r15} is not
  6080. available for use by the register allocator.
  6081. \begin{lstlisting}
  6082. (collect |$\itm{bytes}$|)
  6083. |$\Longrightarrow$|
  6084. movq %r15, %rdi
  6085. movq $|\itm{bytes}|, %rsi
  6086. callq collect
  6087. \end{lstlisting}
  6088. \begin{figure}[tp]
  6089. \fbox{
  6090. \begin{minipage}{0.96\textwidth}
  6091. \[
  6092. \begin{array}{lcl}
  6093. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6094. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6095. & & \gray{ \key{main:} \; \Instr\ldots }
  6096. \end{array}
  6097. \]
  6098. \end{minipage}
  6099. }
  6100. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXASTIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6101. \label{fig:x86-2-concrete}
  6102. \end{figure}
  6103. \begin{figure}[tp]
  6104. \fbox{
  6105. \begin{minipage}{0.96\textwidth}
  6106. \small
  6107. \[
  6108. \begin{array}{lcl}
  6109. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6110. \mid \BYTEREG{\Reg}} \\
  6111. &\mid& (\key{Global}~\Var) \\
  6112. \LangXASTGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6113. \end{array}
  6114. \]
  6115. \end{minipage}
  6116. }
  6117. \caption{The abstract syntax of \LangXASTGlobal{} (extends \LangXASTIf{} of Figure~\ref{fig:x86-1}).}
  6118. \label{fig:x86-2}
  6119. \end{figure}
  6120. The concrete and abstract syntax of the \LangXASTGlobal{} language is
  6121. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6122. differs from \LangXASTIf{} just in the addition of the form for global
  6123. variables.
  6124. %
  6125. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6126. \code{select-instructions} pass on the running example.
  6127. \begin{figure}[tbp]
  6128. \centering
  6129. % tests/s2_17.rkt
  6130. \begin{minipage}[t]{0.5\textwidth}
  6131. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6132. block35:
  6133. movq free_ptr(%rip), alloc9024
  6134. addq $16, free_ptr(%rip)
  6135. movq alloc9024, %r11
  6136. movq $131, 0(%r11)
  6137. movq alloc9024, %r11
  6138. movq vecinit9025, 8(%r11)
  6139. movq $0, initret9026
  6140. movq alloc9024, %r11
  6141. movq 8(%r11), tmp9034
  6142. movq tmp9034, %r11
  6143. movq 8(%r11), %rax
  6144. jmp conclusion
  6145. block36:
  6146. movq $0, collectret9027
  6147. jmp block35
  6148. block38:
  6149. movq free_ptr(%rip), alloc9020
  6150. addq $16, free_ptr(%rip)
  6151. movq alloc9020, %r11
  6152. movq $3, 0(%r11)
  6153. movq alloc9020, %r11
  6154. movq vecinit9021, 8(%r11)
  6155. movq $0, initret9022
  6156. movq alloc9020, vecinit9025
  6157. movq free_ptr(%rip), tmp9031
  6158. movq tmp9031, tmp9032
  6159. addq $16, tmp9032
  6160. movq fromspace_end(%rip), tmp9033
  6161. cmpq tmp9033, tmp9032
  6162. jl block36
  6163. jmp block37
  6164. block37:
  6165. movq %r15, %rdi
  6166. movq $16, %rsi
  6167. callq 'collect
  6168. jmp block35
  6169. block39:
  6170. movq $0, collectret9023
  6171. jmp block38
  6172. \end{lstlisting}
  6173. \end{minipage}
  6174. \begin{minipage}[t]{0.45\textwidth}
  6175. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6176. start:
  6177. movq $42, vecinit9021
  6178. movq free_ptr(%rip), tmp9028
  6179. movq tmp9028, tmp9029
  6180. addq $16, tmp9029
  6181. movq fromspace_end(%rip), tmp9030
  6182. cmpq tmp9030, tmp9029
  6183. jl block39
  6184. jmp block40
  6185. block40:
  6186. movq %r15, %rdi
  6187. movq $16, %rsi
  6188. callq 'collect
  6189. jmp block38
  6190. \end{lstlisting}
  6191. \end{minipage}
  6192. \caption{Output of the \code{select-instructions} pass.}
  6193. \label{fig:select-instr-output-gc}
  6194. \end{figure}
  6195. \clearpage
  6196. \section{Register Allocation}
  6197. \label{sec:reg-alloc-gc}
  6198. \index{register allocation}
  6199. As discussed earlier in this chapter, the garbage collector needs to
  6200. access all the pointers in the root set, that is, all variables that
  6201. are vectors. It will be the responsibility of the register allocator
  6202. to make sure that:
  6203. \begin{enumerate}
  6204. \item the root stack is used for spilling vector-typed variables, and
  6205. \item if a vector-typed variable is live during a call to the
  6206. collector, it must be spilled to ensure it is visible to the
  6207. collector.
  6208. \end{enumerate}
  6209. The later responsibility can be handled during construction of the
  6210. interference graph, by adding interference edges between the call-live
  6211. vector-typed variables and all the callee-saved registers. (They
  6212. already interfere with the caller-saved registers.) The type
  6213. information for variables is in the \code{Program} form, so we
  6214. recommend adding another parameter to the \code{build-interference}
  6215. function to communicate this alist.
  6216. The spilling of vector-typed variables to the root stack can be
  6217. handled after graph coloring, when choosing how to assign the colors
  6218. (integers) to registers and stack locations. The \code{Program} output
  6219. of this pass changes to also record the number of spills to the root
  6220. stack.
  6221. % build-interference
  6222. %
  6223. % callq
  6224. % extra parameter for var->type assoc. list
  6225. % update 'program' and 'if'
  6226. % allocate-registers
  6227. % allocate spilled vectors to the rootstack
  6228. % don't change color-graph
  6229. \section{Print x86}
  6230. \label{sec:print-x86-gc}
  6231. \index{prelude}\index{conclusion}
  6232. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6233. \code{print-x86} pass on the running example. In the prelude and
  6234. conclusion of the \code{main} function, we treat the root stack very
  6235. much like the regular stack in that we move the root stack pointer
  6236. (\code{r15}) to make room for the spills to the root stack, except
  6237. that the root stack grows up instead of down. For the running
  6238. example, there was just one spill so we increment \code{r15} by 8
  6239. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6240. One issue that deserves special care is that there may be a call to
  6241. \code{collect} prior to the initializing assignments for all the
  6242. variables in the root stack. We do not want the garbage collector to
  6243. accidentally think that some uninitialized variable is a pointer that
  6244. needs to be followed. Thus, we zero-out all locations on the root
  6245. stack in the prelude of \code{main}. In
  6246. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6247. %
  6248. \lstinline{movq $0, (%r15)}
  6249. %
  6250. accomplishes this task. The garbage collector tests each root to see
  6251. if it is null prior to dereferencing it.
  6252. \begin{figure}[htbp]
  6253. \begin{minipage}[t]{0.5\textwidth}
  6254. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6255. block35:
  6256. movq free_ptr(%rip), %rcx
  6257. addq $16, free_ptr(%rip)
  6258. movq %rcx, %r11
  6259. movq $131, 0(%r11)
  6260. movq %rcx, %r11
  6261. movq -8(%r15), %rax
  6262. movq %rax, 8(%r11)
  6263. movq $0, %rdx
  6264. movq %rcx, %r11
  6265. movq 8(%r11), %rcx
  6266. movq %rcx, %r11
  6267. movq 8(%r11), %rax
  6268. jmp conclusion
  6269. block36:
  6270. movq $0, %rcx
  6271. jmp block35
  6272. block38:
  6273. movq free_ptr(%rip), %rcx
  6274. addq $16, free_ptr(%rip)
  6275. movq %rcx, %r11
  6276. movq $3, 0(%r11)
  6277. movq %rcx, %r11
  6278. movq %rbx, 8(%r11)
  6279. movq $0, %rdx
  6280. movq %rcx, -8(%r15)
  6281. movq free_ptr(%rip), %rcx
  6282. addq $16, %rcx
  6283. movq fromspace_end(%rip), %rdx
  6284. cmpq %rdx, %rcx
  6285. jl block36
  6286. movq %r15, %rdi
  6287. movq $16, %rsi
  6288. callq collect
  6289. jmp block35
  6290. block39:
  6291. movq $0, %rcx
  6292. jmp block38
  6293. \end{lstlisting}
  6294. \end{minipage}
  6295. \begin{minipage}[t]{0.45\textwidth}
  6296. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6297. start:
  6298. movq $42, %rbx
  6299. movq free_ptr(%rip), %rdx
  6300. addq $16, %rdx
  6301. movq fromspace_end(%rip), %rcx
  6302. cmpq %rcx, %rdx
  6303. jl block39
  6304. movq %r15, %rdi
  6305. movq $16, %rsi
  6306. callq collect
  6307. jmp block38
  6308. .globl main
  6309. main:
  6310. pushq %rbp
  6311. movq %rsp, %rbp
  6312. pushq %r13
  6313. pushq %r12
  6314. pushq %rbx
  6315. pushq %r14
  6316. subq $0, %rsp
  6317. movq $16384, %rdi
  6318. movq $16384, %rsi
  6319. callq initialize
  6320. movq rootstack_begin(%rip), %r15
  6321. movq $0, (%r15)
  6322. addq $8, %r15
  6323. jmp start
  6324. conclusion:
  6325. subq $8, %r15
  6326. addq $0, %rsp
  6327. popq %r14
  6328. popq %rbx
  6329. popq %r12
  6330. popq %r13
  6331. popq %rbp
  6332. retq
  6333. \end{lstlisting}
  6334. \end{minipage}
  6335. \caption{Output of the \code{print-x86} pass.}
  6336. \label{fig:print-x86-output-gc}
  6337. \end{figure}
  6338. \begin{figure}[p]
  6339. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6340. \node (Rvec) at (0,2) {\large \LangVec{}};
  6341. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6342. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6343. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6344. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6345. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6346. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6347. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6348. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6349. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6350. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6351. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6352. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6353. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6354. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6355. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6356. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6357. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6358. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6359. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6360. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6361. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6362. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6363. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6364. \end{tikzpicture}
  6365. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6366. \label{fig:Rvec-passes}
  6367. \end{figure}
  6368. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6369. for the compilation of \LangVec{}.
  6370. \section{Challenge: Simple Structures}
  6371. \label{sec:simple-structures}
  6372. \index{struct}
  6373. \index{structure}
  6374. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6375. $R^s_3$, which extends $R^3$ with support for simple structures.
  6376. Recall that a \code{struct} in Typed Racket is a user-defined data
  6377. type that contains named fields and that is heap allocated, similar to
  6378. a vector. The following is an example of a structure definition, in
  6379. this case the definition of a \code{point} type.
  6380. \begin{lstlisting}
  6381. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6382. \end{lstlisting}
  6383. \begin{figure}[tbp]
  6384. \centering
  6385. \fbox{
  6386. \begin{minipage}{0.96\textwidth}
  6387. \[
  6388. \begin{array}{lcl}
  6389. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6390. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6391. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6392. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6393. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6394. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6395. \mid (\key{and}\;\Exp\;\Exp)
  6396. \mid (\key{or}\;\Exp\;\Exp)
  6397. \mid (\key{not}\;\Exp) } \\
  6398. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6399. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6400. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6401. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6402. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6403. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6404. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6405. R^s_3 &::=& \Def \ldots \; \Exp
  6406. \end{array}
  6407. \]
  6408. \end{minipage}
  6409. }
  6410. \caption{The concrete syntax of $R^s_3$, extending \LangVec{}
  6411. (Figure~\ref{fig:r3-concrete-syntax}).}
  6412. \label{fig:r3s-concrete-syntax}
  6413. \end{figure}
  6414. An instance of a structure is created using function call syntax, with
  6415. the name of the structure in the function position:
  6416. \begin{lstlisting}
  6417. (point 7 12)
  6418. \end{lstlisting}
  6419. Function-call syntax is also used to read the value in a field of a
  6420. structure. The function name is formed by the structure name, a dash,
  6421. and the field name. The following example uses \code{point-x} and
  6422. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6423. instances.
  6424. \begin{center}
  6425. \begin{lstlisting}
  6426. (let ([pt1 (point 7 12)])
  6427. (let ([pt2 (point 4 3)])
  6428. (+ (- (point-x pt1) (point-x pt2))
  6429. (- (point-y pt1) (point-y pt2)))))
  6430. \end{lstlisting}
  6431. \end{center}
  6432. Similarly, to write to a field of a structure, use its set function,
  6433. whose name starts with \code{set-}, followed by the structure name,
  6434. then a dash, then the field name, and concluded with an exclamation
  6435. mark. The following example uses \code{set-point-x!} to change the
  6436. \code{x} field from \code{7} to \code{42}.
  6437. \begin{center}
  6438. \begin{lstlisting}
  6439. (let ([pt (point 7 12)])
  6440. (let ([_ (set-point-x! pt 42)])
  6441. (point-x pt)))
  6442. \end{lstlisting}
  6443. \end{center}
  6444. \begin{exercise}\normalfont
  6445. Extend your compiler with support for simple structures, compiling
  6446. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6447. structures and test your compiler.
  6448. \end{exercise}
  6449. \section{Challenge: Generational Collection}
  6450. The copying collector described in Section~\ref{sec:GC} can incur
  6451. significant runtime overhead because the call to \code{collect} takes
  6452. time proportional to all of the live data. One way to reduce this
  6453. overhead is to reduce how much data is inspected in each call to
  6454. \code{collect}. In particular, researchers have observed that recently
  6455. allocated data is more likely to become garbage then data that has
  6456. survived one or more previous calls to \code{collect}. This insight
  6457. motivated the creation of \emph{generational garbage collectors}
  6458. \index{generational garbage collector} that
  6459. 1) segregates data according to its age into two or more generations,
  6460. 2) allocates less space for younger generations, so collecting them is
  6461. faster, and more space for the older generations, and 3) performs
  6462. collection on the younger generations more frequently then for older
  6463. generations~\citep{Wilson:1992fk}.
  6464. For this challenge assignment, the goal is to adapt the copying
  6465. collector implemented in \code{runtime.c} to use two generations, one
  6466. for young data and one for old data. Each generation consists of a
  6467. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6468. \code{collect} function to use the two generations.
  6469. \begin{enumerate}
  6470. \item Copy the young generation's FromSpace to its ToSpace then switch
  6471. the role of the ToSpace and FromSpace
  6472. \item If there is enough space for the requested number of bytes in
  6473. the young FromSpace, then return from \code{collect}.
  6474. \item If there is not enough space in the young FromSpace for the
  6475. requested bytes, then move the data from the young generation to the
  6476. old one with the following steps:
  6477. \begin{enumerate}
  6478. \item If there is enough room in the old FromSpace, copy the young
  6479. FromSpace to the old FromSpace and then return.
  6480. \item If there is not enough room in the old FromSpace, then collect
  6481. the old generation by copying the old FromSpace to the old ToSpace
  6482. and swap the roles of the old FromSpace and ToSpace.
  6483. \item If there is enough room now, copy the young FromSpace to the
  6484. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6485. and ToSpace for the old generation. Copy the young FromSpace and
  6486. the old FromSpace into the larger FromSpace for the old
  6487. generation and then return.
  6488. \end{enumerate}
  6489. \end{enumerate}
  6490. We recommend that you generalize the \code{cheney} function so that it
  6491. can be used for all the copies mentioned above: between the young
  6492. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6493. between the young FromSpace and old FromSpace. This can be
  6494. accomplished by adding parameters to \code{cheney} that replace its
  6495. use of the global variables \code{fromspace\_begin},
  6496. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6497. Note that the collection of the young generation does not traverse the
  6498. old generation. This introduces a potential problem: there may be
  6499. young data that is only reachable through pointers in the old
  6500. generation. If these pointers are not taken into account, the
  6501. collector could throw away young data that is live! One solution,
  6502. called \emph{pointer recording}, is to maintain a set of all the
  6503. pointers from the old generation into the new generation and consider
  6504. this set as part of the root set. To maintain this set, the compiler
  6505. must insert extra instructions around every \code{vector-set!}. If the
  6506. vector being modified is in the old generation, and if the value being
  6507. written is a pointer into the new generation, than that pointer must
  6508. be added to the set. Also, if the value being overwritten was a
  6509. pointer into the new generation, then that pointer should be removed
  6510. from the set.
  6511. \begin{exercise}\normalfont
  6512. Adapt the \code{collect} function in \code{runtime.c} to implement
  6513. generational garbage collection, as outlined in this section.
  6514. Update the code generation for \code{vector-set!} to implement
  6515. pointer recording. Make sure that your new compiler and runtime
  6516. passes your test suite.
  6517. \end{exercise}
  6518. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6519. \chapter{Functions}
  6520. \label{ch:functions}
  6521. \index{function}
  6522. This chapter studies the compilation of functions similar to those
  6523. found in the C language. This corresponds to a subset of Typed Racket
  6524. in which only top-level function definitions are allowed. This kind of
  6525. function is an important stepping stone to implementing
  6526. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6527. is the topic of Chapter~\ref{ch:lambdas}.
  6528. \section{The \LangFun{} Language}
  6529. The concrete and abstract syntax for function definitions and function
  6530. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6531. \ref{fig:r4-syntax}, where we define the \LangFun{} language. Programs in
  6532. \LangFun{} begin with zero or more function definitions. The function
  6533. names from these definitions are in-scope for the entire program,
  6534. including all other function definitions (so the ordering of function
  6535. definitions does not matter). The concrete syntax for function
  6536. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6537. where the first expression must
  6538. evaluate to a function and the rest are the arguments.
  6539. The abstract syntax for function application is
  6540. $\APPLY{\Exp}{\Exp\ldots}$.
  6541. %% The syntax for function application does not include an explicit
  6542. %% keyword, which is error prone when using \code{match}. To alleviate
  6543. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6544. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6545. Functions are first-class in the sense that a function pointer
  6546. \index{function pointer} is data and can be stored in memory or passed
  6547. as a parameter to another function. Thus, we introduce a function
  6548. type, written
  6549. \begin{lstlisting}
  6550. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6551. \end{lstlisting}
  6552. for a function whose $n$ parameters have the types $\Type_1$ through
  6553. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6554. these functions (with respect to Racket functions) is that they are
  6555. not lexically scoped. That is, the only external entities that can be
  6556. referenced from inside a function body are other globally-defined
  6557. functions. The syntax of \LangFun{} prevents functions from being nested
  6558. inside each other.
  6559. \begin{figure}[tp]
  6560. \centering
  6561. \fbox{
  6562. \begin{minipage}{0.96\textwidth}
  6563. \small
  6564. \[
  6565. \begin{array}{lcl}
  6566. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6567. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6568. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6569. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6570. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6571. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6572. \mid (\key{and}\;\Exp\;\Exp)
  6573. \mid (\key{or}\;\Exp\;\Exp)
  6574. \mid (\key{not}\;\Exp)} \\
  6575. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6576. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6577. (\key{vector-ref}\;\Exp\;\Int)} \\
  6578. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6579. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6580. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6581. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6582. \LangFun{} &::=& \Def \ldots \; \Exp
  6583. \end{array}
  6584. \]
  6585. \end{minipage}
  6586. }
  6587. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:r3-concrete-syntax}).}
  6588. \label{fig:r4-concrete-syntax}
  6589. \end{figure}
  6590. \begin{figure}[tp]
  6591. \centering
  6592. \fbox{
  6593. \begin{minipage}{0.96\textwidth}
  6594. \small
  6595. \[
  6596. \begin{array}{lcl}
  6597. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6598. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6599. &\mid& \gray{ \BOOL{\itm{bool}}
  6600. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6601. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6602. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6603. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6604. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6605. \end{array}
  6606. \]
  6607. \end{minipage}
  6608. }
  6609. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:r3-syntax}).}
  6610. \label{fig:r4-syntax}
  6611. \end{figure}
  6612. The program in Figure~\ref{fig:r4-function-example} is a
  6613. representative example of defining and using functions in \LangFun{}. We
  6614. define a function \code{map-vec} that applies some other function
  6615. \code{f} to both elements of a vector and returns a new
  6616. vector containing the results. We also define a function \code{add1}.
  6617. The program applies
  6618. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6619. \code{(vector 1 42)}, from which we return the \code{42}.
  6620. \begin{figure}[tbp]
  6621. \begin{lstlisting}
  6622. (define (map-vec [f : (Integer -> Integer)]
  6623. [v : (Vector Integer Integer)])
  6624. : (Vector Integer Integer)
  6625. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6626. (define (add1 [x : Integer]) : Integer
  6627. (+ x 1))
  6628. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6629. \end{lstlisting}
  6630. \caption{Example of using functions in \LangFun{}.}
  6631. \label{fig:r4-function-example}
  6632. \end{figure}
  6633. The definitional interpreter for \LangFun{} is in
  6634. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6635. responsible for setting up the mutual recursion between the top-level
  6636. function definitions. We use the classic back-patching \index{back-patching}
  6637. approach that uses mutable variables and makes two passes over the function
  6638. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6639. top-level environment using a mutable cons cell for each function
  6640. definition. Note that the \code{lambda} value for each function is
  6641. incomplete; it does not yet include the environment. Once the
  6642. top-level environment is constructed, we then iterate over it and
  6643. update the \code{lambda} values to use the top-level environment.
  6644. \begin{figure}[tp]
  6645. \begin{lstlisting}
  6646. (define interp-Rfun-class
  6647. (class interp-Rvec-class
  6648. (super-new)
  6649. (define/override ((interp-exp env) e)
  6650. (define recur (interp-exp env))
  6651. (match e
  6652. [(Var x) (unbox (dict-ref env x))]
  6653. [(Let x e body)
  6654. (define new-env (dict-set env x (box (recur e))))
  6655. ((interp-exp new-env) body)]
  6656. [(Apply fun args)
  6657. (define fun-val (recur fun))
  6658. (define arg-vals (for/list ([e args]) (recur e)))
  6659. (match fun-val
  6660. [`(function (,xs ...) ,body ,fun-env)
  6661. (define params-args (for/list ([x xs] [arg arg-vals])
  6662. (cons x (box arg))))
  6663. (define new-env (append params-args fun-env))
  6664. ((interp-exp new-env) body)]
  6665. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6666. [else ((super interp-exp env) e)]
  6667. ))
  6668. (define/public (interp-def d)
  6669. (match d
  6670. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6671. (cons f (box `(function ,xs ,body ())))]))
  6672. (define/override (interp-program p)
  6673. (match p
  6674. [(ProgramDefsExp info ds body)
  6675. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6676. (for/list ([f (in-dict-values top-level)])
  6677. (set-box! f (match (unbox f)
  6678. [`(function ,xs ,body ())
  6679. `(function ,xs ,body ,top-level)])))
  6680. ((interp-exp top-level) body))]))
  6681. ))
  6682. (define (interp-Rfun p)
  6683. (send (new interp-Rfun-class) interp-program p))
  6684. \end{lstlisting}
  6685. \caption{Interpreter for the \LangFun{} language.}
  6686. \label{fig:interp-Rfun}
  6687. \end{figure}
  6688. \margincomment{TODO: explain type checker}
  6689. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  6690. \begin{figure}[tp]
  6691. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6692. (define type-check-Rfun-class
  6693. (class type-check-Rvec-class
  6694. (super-new)
  6695. (inherit check-type-equal?)
  6696. (define/public (type-check-apply env e es)
  6697. (define-values (e^ ty) ((type-check-exp env) e))
  6698. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6699. ((type-check-exp env) e)))
  6700. (match ty
  6701. [`(,ty^* ... -> ,rt)
  6702. (for ([arg-ty ty*] [param-ty ty^*])
  6703. (check-type-equal? arg-ty param-ty (Apply e es)))
  6704. (values e^ e* rt)]))
  6705. (define/override (type-check-exp env)
  6706. (lambda (e)
  6707. (match e
  6708. [(FunRef f)
  6709. (values (FunRef f) (dict-ref env f))]
  6710. [(Apply e es)
  6711. (define-values (e^ es^ rt) (type-check-apply env e es))
  6712. (values (Apply e^ es^) rt)]
  6713. [(Call e es)
  6714. (define-values (e^ es^ rt) (type-check-apply env e es))
  6715. (values (Call e^ es^) rt)]
  6716. [else ((super type-check-exp env) e)])))
  6717. (define/public (type-check-def env)
  6718. (lambda (e)
  6719. (match e
  6720. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6721. (define new-env (append (map cons xs ps) env))
  6722. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6723. (check-type-equal? ty^ rt body)
  6724. (Def f p:t* rt info body^)])))
  6725. (define/public (fun-def-type d)
  6726. (match d
  6727. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6728. (define/override (type-check-program e)
  6729. (match e
  6730. [(ProgramDefsExp info ds body)
  6731. (define new-env (for/list ([d ds])
  6732. (cons (Def-name d) (fun-def-type d))))
  6733. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  6734. (define-values (body^ ty) ((type-check-exp new-env) body))
  6735. (check-type-equal? ty 'Integer body)
  6736. (ProgramDefsExp info ds^ body^)]))))
  6737. (define (type-check-Rfun p)
  6738. (send (new type-check-Rfun-class) type-check-program p))
  6739. \end{lstlisting}
  6740. \caption{Type checker for the \LangFun{} language.}
  6741. \label{fig:type-check-Rfun}
  6742. \end{figure}
  6743. \section{Functions in x86}
  6744. \label{sec:fun-x86}
  6745. \margincomment{\tiny Make sure callee-saved registers are discussed
  6746. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6747. \margincomment{\tiny Talk about the return address on the
  6748. stack and what callq and retq does.\\ --Jeremy }
  6749. The x86 architecture provides a few features to support the
  6750. implementation of functions. We have already seen that x86 provides
  6751. labels so that one can refer to the location of an instruction, as is
  6752. needed for jump instructions. Labels can also be used to mark the
  6753. beginning of the instructions for a function. Going further, we can
  6754. obtain the address of a label by using the \key{leaq} instruction and
  6755. PC-relative addressing. For example, the following puts the
  6756. address of the \code{add1} label into the \code{rbx} register.
  6757. \begin{lstlisting}
  6758. leaq add1(%rip), %rbx
  6759. \end{lstlisting}
  6760. The instruction pointer register \key{rip} (aka. the program counter
  6761. \index{program counter}) always points to the next instruction to be
  6762. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6763. linker computes the distance $d$ between the address of \code{add1}
  6764. and where the \code{rip} would be at that moment and then changes
  6765. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6766. the address of \code{add1}.
  6767. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6768. jump to a function whose location is given by a label. To support
  6769. function calls in this chapter we instead will be jumping to a
  6770. function whose location is given by an address in a register, that is,
  6771. we need to make an \emph{indirect function call}. The x86 syntax for
  6772. this is a \code{callq} instruction but with an asterisk before the
  6773. register name.\index{indirect function call}
  6774. \begin{lstlisting}
  6775. callq *%rbx
  6776. \end{lstlisting}
  6777. \subsection{Calling Conventions}
  6778. \index{calling conventions}
  6779. The \code{callq} instruction provides partial support for implementing
  6780. functions: it pushes the return address on the stack and it jumps to
  6781. the target. However, \code{callq} does not handle
  6782. \begin{enumerate}
  6783. \item parameter passing,
  6784. \item pushing frames on the procedure call stack and popping them off,
  6785. or
  6786. \item determining how registers are shared by different functions.
  6787. \end{enumerate}
  6788. Regarding (1) parameter passing, recall that the following six
  6789. registers are used to pass arguments to a function, in this order.
  6790. \begin{lstlisting}
  6791. rdi rsi rdx rcx r8 r9
  6792. \end{lstlisting}
  6793. If there are
  6794. more than six arguments, then the convention is to use space on the
  6795. frame of the caller for the rest of the arguments. However, to ease
  6796. the implementation of efficient tail calls
  6797. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6798. arguments.
  6799. %
  6800. Also recall that the register \code{rax} is for the return value of
  6801. the function.
  6802. \index{prelude}\index{conclusion}
  6803. Regarding (2) frames \index{frame} and the procedure call stack,
  6804. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6805. the stack grows down, with each function call using a chunk of space
  6806. called a frame. The caller sets the stack pointer, register
  6807. \code{rsp}, to the last data item in its frame. The callee must not
  6808. change anything in the caller's frame, that is, anything that is at or
  6809. above the stack pointer. The callee is free to use locations that are
  6810. below the stack pointer.
  6811. Recall that we are storing variables of vector type on the root stack.
  6812. So the prelude needs to move the root stack pointer \code{r15} up and
  6813. the conclusion needs to move the root stack pointer back down. Also,
  6814. the prelude must initialize to \code{0} this frame's slots in the root
  6815. stack to signal to the garbage collector that those slots do not yet
  6816. contain a pointer to a vector. Otherwise the garbage collector will
  6817. interpret the garbage bits in those slots as memory addresses and try
  6818. to traverse them, causing serious mayhem!
  6819. Regarding (3) the sharing of registers between different functions,
  6820. recall from Section~\ref{sec:calling-conventions} that the registers
  6821. are divided into two groups, the caller-saved registers and the
  6822. callee-saved registers. The caller should assume that all the
  6823. caller-saved registers get overwritten with arbitrary values by the
  6824. callee. That is why we recommend in
  6825. Section~\ref{sec:calling-conventions} that variables that are live
  6826. during a function call should not be assigned to caller-saved
  6827. registers.
  6828. On the flip side, if the callee wants to use a callee-saved register,
  6829. the callee must save the contents of those registers on their stack
  6830. frame and then put them back prior to returning to the caller. That
  6831. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6832. the register allocator assigns a variable to a callee-saved register,
  6833. then the prelude of the \code{main} function must save that register
  6834. to the stack and the conclusion of \code{main} must restore it. This
  6835. recommendation now generalizes to all functions.
  6836. Also recall that the base pointer, register \code{rbp}, is used as a
  6837. point-of-reference within a frame, so that each local variable can be
  6838. accessed at a fixed offset from the base pointer
  6839. (Section~\ref{sec:x86}).
  6840. %
  6841. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6842. and callee frames.
  6843. \begin{figure}[tbp]
  6844. \centering
  6845. \begin{tabular}{r|r|l|l} \hline
  6846. Caller View & Callee View & Contents & Frame \\ \hline
  6847. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6848. 0(\key{\%rbp}) & & old \key{rbp} \\
  6849. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6850. \ldots & & \ldots \\
  6851. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6852. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6853. \ldots & & \ldots \\
  6854. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6855. %% & & \\
  6856. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6857. %% & \ldots & \ldots \\
  6858. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6859. \hline
  6860. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6861. & 0(\key{\%rbp}) & old \key{rbp} \\
  6862. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6863. & \ldots & \ldots \\
  6864. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6865. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6866. & \ldots & \ldots \\
  6867. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6868. \end{tabular}
  6869. \caption{Memory layout of caller and callee frames.}
  6870. \label{fig:call-frames}
  6871. \end{figure}
  6872. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6873. %% local variables and for storing the values of callee-saved registers
  6874. %% (we shall refer to all of these collectively as ``locals''), and that
  6875. %% at the beginning of a function we move the stack pointer \code{rsp}
  6876. %% down to make room for them.
  6877. %% We recommend storing the local variables
  6878. %% first and then the callee-saved registers, so that the local variables
  6879. %% can be accessed using \code{rbp} the same as before the addition of
  6880. %% functions.
  6881. %% To make additional room for passing arguments, we shall
  6882. %% move the stack pointer even further down. We count how many stack
  6883. %% arguments are needed for each function call that occurs inside the
  6884. %% body of the function and find their maximum. Adding this number to the
  6885. %% number of locals gives us how much the \code{rsp} should be moved at
  6886. %% the beginning of the function. In preparation for a function call, we
  6887. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6888. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6889. %% so on.
  6890. %% Upon calling the function, the stack arguments are retrieved by the
  6891. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6892. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6893. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6894. %% the layout of the caller and callee frames. Notice how important it is
  6895. %% that we correctly compute the maximum number of arguments needed for
  6896. %% function calls; if that number is too small then the arguments and
  6897. %% local variables will smash into each other!
  6898. \subsection{Efficient Tail Calls}
  6899. \label{sec:tail-call}
  6900. In general, the amount of stack space used by a program is determined
  6901. by the longest chain of nested function calls. That is, if function
  6902. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6903. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6904. $n$ can grow quite large in the case of recursive or mutually
  6905. recursive functions. However, in some cases we can arrange to use only
  6906. constant space, i.e. $O(1)$, instead of $O(n)$.
  6907. If a function call is the last action in a function body, then that
  6908. call is said to be a \emph{tail call}\index{tail call}.
  6909. For example, in the following
  6910. program, the recursive call to \code{tail-sum} is a tail call.
  6911. \begin{center}
  6912. \begin{lstlisting}
  6913. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6914. (if (eq? n 0)
  6915. r
  6916. (tail-sum (- n 1) (+ n r))))
  6917. (+ (tail-sum 5 0) 27)
  6918. \end{lstlisting}
  6919. \end{center}
  6920. At a tail call, the frame of the caller is no longer needed, so we
  6921. can pop the caller's frame before making the tail call. With this
  6922. approach, a recursive function that only makes tail calls will only
  6923. use $O(1)$ stack space. Functional languages like Racket typically
  6924. rely heavily on recursive functions, so they typically guarantee that
  6925. all tail calls will be optimized in this way.
  6926. \index{frame}
  6927. However, some care is needed with regards to argument passing in tail
  6928. calls. As mentioned above, for arguments beyond the sixth, the
  6929. convention is to use space in the caller's frame for passing
  6930. arguments. But for a tail call we pop the caller's frame and can no
  6931. longer use it. Another alternative is to use space in the callee's
  6932. frame for passing arguments. However, this option is also problematic
  6933. because the caller and callee's frame overlap in memory. As we begin
  6934. to copy the arguments from their sources in the caller's frame, the
  6935. target locations in the callee's frame might overlap with the sources
  6936. for later arguments! We solve this problem by not using the stack for
  6937. passing more than six arguments but instead using the heap, as we
  6938. describe in the Section~\ref{sec:limit-functions-r4}.
  6939. As mentioned above, for a tail call we pop the caller's frame prior to
  6940. making the tail call. The instructions for popping a frame are the
  6941. instructions that we usually place in the conclusion of a
  6942. function. Thus, we also need to place such code immediately before
  6943. each tail call. These instructions include restoring the callee-saved
  6944. registers, so it is good that the argument passing registers are all
  6945. caller-saved registers.
  6946. One last note regarding which instruction to use to make the tail
  6947. call. When the callee is finished, it should not return to the current
  6948. function, but it should return to the function that called the current
  6949. one. Thus, the return address that is already on the stack is the
  6950. right one, and we should not use \key{callq} to make the tail call, as
  6951. that would unnecessarily overwrite the return address. Instead we can
  6952. simply use the \key{jmp} instruction. Like the indirect function call,
  6953. we write an \emph{indirect jump}\index{indirect jump} with a register
  6954. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6955. jump target because the preceding conclusion overwrites just about
  6956. everything else.
  6957. \begin{lstlisting}
  6958. jmp *%rax
  6959. \end{lstlisting}
  6960. \section{Shrink \LangFun{}}
  6961. \label{sec:shrink-r4}
  6962. The \code{shrink} pass performs a minor modification to ease the
  6963. later passes. This pass introduces an explicit \code{main} function
  6964. and changes the top \code{ProgramDefsExp} form to
  6965. \code{ProgramDefs} as follows.
  6966. \begin{lstlisting}
  6967. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6968. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6969. \end{lstlisting}
  6970. where $\itm{mainDef}$ is
  6971. \begin{lstlisting}
  6972. (Def 'main '() 'Integer '() |$\Exp'$|)
  6973. \end{lstlisting}
  6974. \section{Reveal Functions and the \LangFunRef{} language}
  6975. \label{sec:reveal-functions-r4}
  6976. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  6977. respect: it conflates the use of function names and local
  6978. variables. This is a problem because we need to compile the use of a
  6979. function name differently than the use of a local variable; we need to
  6980. use \code{leaq} to convert the function name (a label in x86) to an
  6981. address in a register. Thus, it is a good idea to create a new pass
  6982. that changes function references from just a symbol $f$ to
  6983. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6984. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  6985. The concrete syntax for a function reference is $\CFUNREF{f}$.
  6986. \begin{figure}[tp]
  6987. \centering
  6988. \fbox{
  6989. \begin{minipage}{0.96\textwidth}
  6990. \[
  6991. \begin{array}{lcl}
  6992. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  6993. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6994. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6995. \end{array}
  6996. \]
  6997. \end{minipage}
  6998. }
  6999. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7000. (Figure~\ref{fig:r4-syntax}).}
  7001. \label{fig:f1-syntax}
  7002. \end{figure}
  7003. %% Distinguishing between calls in tail position and non-tail position
  7004. %% requires the pass to have some notion of context. We recommend using
  7005. %% two mutually recursive functions, one for processing expressions in
  7006. %% tail position and another for the rest.
  7007. Placing this pass after \code{uniquify} will make sure that there are
  7008. no local variables and functions that share the same name. On the
  7009. other hand, \code{reveal-functions} needs to come before the
  7010. \code{explicate-control} pass because that pass helps us compile
  7011. \code{FunRef} forms into assignment statements.
  7012. \section{Limit Functions}
  7013. \label{sec:limit-functions-r4}
  7014. Recall that we wish to limit the number of function parameters to six
  7015. so that we do not need to use the stack for argument passing, which
  7016. makes it easier to implement efficient tail calls. However, because
  7017. the input language \LangFun{} supports arbitrary numbers of function
  7018. arguments, we have some work to do!
  7019. This pass transforms functions and function calls that involve more
  7020. than six arguments to pass the first five arguments as usual, but it
  7021. packs the rest of the arguments into a vector and passes it as the
  7022. sixth argument.
  7023. Each function definition with too many parameters is transformed as
  7024. follows.
  7025. \begin{lstlisting}
  7026. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7027. |$\Rightarrow$|
  7028. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7029. \end{lstlisting}
  7030. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7031. the occurrences of the later parameters with vector references.
  7032. \begin{lstlisting}
  7033. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7034. \end{lstlisting}
  7035. For function calls with too many arguments, the \code{limit-functions}
  7036. pass transforms them in the following way.
  7037. \begin{tabular}{lll}
  7038. \begin{minipage}{0.2\textwidth}
  7039. \begin{lstlisting}
  7040. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7041. \end{lstlisting}
  7042. \end{minipage}
  7043. &
  7044. $\Rightarrow$
  7045. &
  7046. \begin{minipage}{0.4\textwidth}
  7047. \begin{lstlisting}
  7048. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7049. \end{lstlisting}
  7050. \end{minipage}
  7051. \end{tabular}
  7052. \section{Remove Complex Operands}
  7053. \label{sec:rco-r4}
  7054. The primary decisions to make for this pass is whether to classify
  7055. \code{FunRef} and \code{Apply} as either atomic or complex
  7056. expressions. Recall that a simple expression will eventually end up as
  7057. just an immediate argument of an x86 instruction. Function
  7058. application will be translated to a sequence of instructions, so
  7059. \code{Apply} must be classified as complex expression.
  7060. On the other hand, the arguments of \code{Apply} should be
  7061. atomic expressions.
  7062. %
  7063. Regarding \code{FunRef}, as discussed above, the function label needs
  7064. to be converted to an address using the \code{leaq} instruction. Thus,
  7065. even though \code{FunRef} seems rather simple, it needs to be
  7066. classified as a complex expression so that we generate an assignment
  7067. statement with a left-hand side that can serve as the target of the
  7068. \code{leaq}. Figure~\ref{fig:r4-anf-syntax} defines the
  7069. output language \LangFunANF{} of this pass.
  7070. \begin{figure}[tp]
  7071. \centering
  7072. \fbox{
  7073. \begin{minipage}{0.96\textwidth}
  7074. \small
  7075. \[
  7076. \begin{array}{rcl}
  7077. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7078. \mid \VOID{} } \\
  7079. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7080. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7081. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7082. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7083. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7084. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7085. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7086. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7087. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7088. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7089. \end{array}
  7090. \]
  7091. \end{minipage}
  7092. }
  7093. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7094. \label{fig:r4-anf-syntax}
  7095. \end{figure}
  7096. \section{Explicate Control and the \LangCFun{} language}
  7097. \label{sec:explicate-control-r4}
  7098. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7099. output of \key{explicate-control}. (The concrete syntax is given in
  7100. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7101. functions for assignment and tail contexts should be updated with
  7102. cases for \code{Apply} and \code{FunRef} and the function for
  7103. predicate context should be updated for \code{Apply} but not
  7104. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7105. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7106. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7107. defining a new auxiliary function for processing function definitions.
  7108. This code is similar to the case for \code{Program} in \LangVec{}. The
  7109. top-level \code{explicate-control} function that handles the
  7110. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7111. all the function definitions.
  7112. \begin{figure}[tp]
  7113. \fbox{
  7114. \begin{minipage}{0.96\textwidth}
  7115. \small
  7116. \[
  7117. \begin{array}{lcl}
  7118. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7119. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7120. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7121. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7122. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7123. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7124. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7125. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7126. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7127. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7128. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7129. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7130. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7131. \mid \GOTO{\itm{label}} } \\
  7132. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7133. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7134. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7135. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7136. \end{array}
  7137. \]
  7138. \end{minipage}
  7139. }
  7140. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7141. \label{fig:c3-syntax}
  7142. \end{figure}
  7143. \section{Select Instructions and the \LangXIndCall{} Language}
  7144. \label{sec:select-r4}
  7145. \index{instruction selection}
  7146. The output of select instructions is a program in the \LangXIndCall{}
  7147. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7148. \index{x86}
  7149. \begin{figure}[tp]
  7150. \fbox{
  7151. \begin{minipage}{0.96\textwidth}
  7152. \small
  7153. \[
  7154. \begin{array}{lcl}
  7155. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7156. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7157. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7158. \Instr &::=& \ldots
  7159. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7160. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7161. \Block &::= & \Instr\ldots \\
  7162. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7163. \LangXIndCall{} &::= & \Def\ldots
  7164. \end{array}
  7165. \]
  7166. \end{minipage}
  7167. }
  7168. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7169. \label{fig:x86-3-concrete}
  7170. \end{figure}
  7171. \begin{figure}[tp]
  7172. \fbox{
  7173. \begin{minipage}{0.96\textwidth}
  7174. \small
  7175. \[
  7176. \begin{array}{lcl}
  7177. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7178. \mid \BYTEREG{\Reg} } \\
  7179. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7180. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7181. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7182. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7183. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7184. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7185. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7186. \end{array}
  7187. \]
  7188. \end{minipage}
  7189. }
  7190. \caption{The abstract syntax of \LangXIndCall{} (extends \LangXASTGlobal{} of Figure~\ref{fig:x86-2}).}
  7191. \label{fig:x86-3}
  7192. \end{figure}
  7193. An assignment of a function reference to a variable becomes a
  7194. load-effective-address instruction as follows: \\
  7195. \begin{tabular}{lcl}
  7196. \begin{minipage}{0.35\textwidth}
  7197. \begin{lstlisting}
  7198. |$\itm{lhs}$| = (fun-ref |$f$|);
  7199. \end{lstlisting}
  7200. \end{minipage}
  7201. &
  7202. $\Rightarrow$\qquad\qquad
  7203. &
  7204. \begin{minipage}{0.3\textwidth}
  7205. \begin{lstlisting}
  7206. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7207. \end{lstlisting}
  7208. \end{minipage}
  7209. \end{tabular} \\
  7210. Regarding function definitions, we need to remove the parameters and
  7211. instead perform parameter passing using the conventions discussed in
  7212. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7213. registers. We recommend turning the parameters into local variables
  7214. and generating instructions at the beginning of the function to move
  7215. from the argument passing registers to these local variables.
  7216. \begin{lstlisting}
  7217. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7218. |$\Rightarrow$|
  7219. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7220. \end{lstlisting}
  7221. The $G'$ control-flow graph is the same as $G$ except that the
  7222. \code{start} block is modified to add the instructions for moving from
  7223. the argument registers to the parameter variables. So the \code{start}
  7224. block of $G$ shown on the left is changed to the code on the right.
  7225. \begin{center}
  7226. \begin{minipage}{0.3\textwidth}
  7227. \begin{lstlisting}
  7228. start:
  7229. |$\itm{instr}_1$|
  7230. |$\vdots$|
  7231. |$\itm{instr}_n$|
  7232. \end{lstlisting}
  7233. \end{minipage}
  7234. $\Rightarrow$
  7235. \begin{minipage}{0.3\textwidth}
  7236. \begin{lstlisting}
  7237. start:
  7238. movq %rdi, |$x_1$|
  7239. movq %rsi, |$x_2$|
  7240. |$\vdots$|
  7241. |$\itm{instr}_1$|
  7242. |$\vdots$|
  7243. |$\itm{instr}_n$|
  7244. \end{lstlisting}
  7245. \end{minipage}
  7246. \end{center}
  7247. By changing the parameters to local variables, we are giving the
  7248. register allocator control over which registers or stack locations to
  7249. use for them. If you implemented the move-biasing challenge
  7250. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7251. assign the parameter variables to the corresponding argument register,
  7252. in which case the \code{patch-instructions} pass will remove the
  7253. \code{movq} instruction. This happens in the example translation in
  7254. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7255. the \code{add} function.
  7256. %
  7257. Also, note that the register allocator will perform liveness analysis
  7258. on this sequence of move instructions and build the interference
  7259. graph. So, for example, $x_1$ will be marked as interfering with
  7260. \code{rsi} and that will prevent the assignment of $x_1$ to
  7261. \code{rsi}, which is good, because that would overwrite the argument
  7262. that needs to move into $x_2$.
  7263. Next, consider the compilation of function calls. In the mirror image
  7264. of handling the parameters of function definitions, the arguments need
  7265. to be moved to the argument passing registers. The function call
  7266. itself is performed with an indirect function call. The return value
  7267. from the function is stored in \code{rax}, so it needs to be moved
  7268. into the \itm{lhs}.
  7269. \begin{lstlisting}
  7270. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7271. |$\Rightarrow$|
  7272. movq |$\itm{arg}_1$|, %rdi
  7273. movq |$\itm{arg}_2$|, %rsi
  7274. |$\vdots$|
  7275. callq *|\itm{fun}|
  7276. movq %rax, |\itm{lhs}|
  7277. \end{lstlisting}
  7278. The \code{IndirectCallq} AST node includes an integer for the arity of
  7279. the function, i.e., the number of parameters. That information is
  7280. useful in the \code{uncover-live} pass for determining which
  7281. argument-passing registers are potentially read during the call.
  7282. For tail calls, the parameter passing is the same as non-tail calls:
  7283. generate instructions to move the arguments into to the argument
  7284. passing registers. After that we need to pop the frame from the
  7285. procedure call stack. However, we do not yet know how big the frame
  7286. is; that gets determined during register allocation. So instead of
  7287. generating those instructions here, we invent a new instruction that
  7288. means ``pop the frame and then do an indirect jump'', which we name
  7289. \code{TailJmp}. The abstract syntax for this instruction includes an
  7290. argument that specifies where to jump and an integer that represents
  7291. the arity of the function being called.
  7292. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7293. using the label \code{start} for the initial block of a program, and
  7294. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7295. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7296. can be compiled to an assignment to \code{rax} followed by a jump to
  7297. \code{conclusion}. With the addition of function definitions, we will
  7298. have a starting block and conclusion for each function, but their
  7299. labels need to be unique. We recommend prepending the function's name
  7300. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7301. labels. (Alternatively, one could \code{gensym} labels for the start
  7302. and conclusion and store them in the $\itm{info}$ field of the
  7303. function definition.)
  7304. \section{Register Allocation}
  7305. \label{sec:register-allocation-r4}
  7306. \subsection{Liveness Analysis}
  7307. \label{sec:liveness-analysis-r4}
  7308. \index{liveness analysis}
  7309. %% The rest of the passes need only minor modifications to handle the new
  7310. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7311. %% \code{leaq}.
  7312. The \code{IndirectCallq} instruction should be treated like
  7313. \code{Callq} regarding its written locations $W$, in that they should
  7314. include all the caller-saved registers. Recall that the reason for
  7315. that is to force call-live variables to be assigned to callee-saved
  7316. registers or to be spilled to the stack.
  7317. Regarding the set of read locations $R$ the arity field of
  7318. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7319. argument-passing registers should be considered as read by those
  7320. instructions.
  7321. \subsection{Build Interference Graph}
  7322. \label{sec:build-interference-r4}
  7323. With the addition of function definitions, we compute an interference
  7324. graph for each function (not just one for the whole program).
  7325. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7326. spill vector-typed variables that are live during a call to the
  7327. \code{collect}. With the addition of functions to our language, we
  7328. need to revisit this issue. Many functions perform allocation and
  7329. therefore have calls to the collector inside of them. Thus, we should
  7330. not only spill a vector-typed variable when it is live during a call
  7331. to \code{collect}, but we should spill the variable if it is live
  7332. during any function call. Thus, in the \code{build-interference} pass,
  7333. we recommend adding interference edges between call-live vector-typed
  7334. variables and the callee-saved registers (in addition to the usual
  7335. addition of edges between call-live variables and the caller-saved
  7336. registers).
  7337. \subsection{Allocate Registers}
  7338. The primary change to the \code{allocate-registers} pass is adding an
  7339. auxiliary function for handling definitions (the \Def{} non-terminal
  7340. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7341. logic is the same as described in
  7342. Chapter~\ref{ch:register-allocation-r1}, except now register
  7343. allocation is performed many times, once for each function definition,
  7344. instead of just once for the whole program.
  7345. \section{Patch Instructions}
  7346. In \code{patch-instructions}, you should deal with the x86
  7347. idiosyncrasy that the destination argument of \code{leaq} must be a
  7348. register. Additionally, you should ensure that the argument of
  7349. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7350. code generation more convenient, because we trample many registers
  7351. before the tail call (as explained in the next section).
  7352. \section{Print x86}
  7353. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7354. \code{IndirectCallq} are straightforward: output their concrete
  7355. syntax.
  7356. \begin{lstlisting}
  7357. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7358. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7359. \end{lstlisting}
  7360. The \code{TailJmp} node requires a bit work. A straightforward
  7361. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7362. before the jump we need to pop the current frame. This sequence of
  7363. instructions is the same as the code for the conclusion of a function,
  7364. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7365. Regarding function definitions, you will need to generate a prelude
  7366. and conclusion for each one. This code is similar to the prelude and
  7367. conclusion that you generated for the \code{main} function in
  7368. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7369. should carry out the following steps.
  7370. \begin{enumerate}
  7371. \item Start with \code{.global} and \code{.align} directives followed
  7372. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7373. example.)
  7374. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7375. pointer.
  7376. \item Push to the stack all of the callee-saved registers that were
  7377. used for register allocation.
  7378. \item Move the stack pointer \code{rsp} down by the size of the stack
  7379. frame for this function, which depends on the number of regular
  7380. spills. (Aligned to 16 bytes.)
  7381. \item Move the root stack pointer \code{r15} up by the size of the
  7382. root-stack frame for this function, which depends on the number of
  7383. spilled vectors. \label{root-stack-init}
  7384. \item Initialize to zero all of the entries in the root-stack frame.
  7385. \item Jump to the start block.
  7386. \end{enumerate}
  7387. The prelude of the \code{main} function has one additional task: call
  7388. the \code{initialize} function to set up the garbage collector and
  7389. move the value of the global \code{rootstack\_begin} in
  7390. \code{r15}. This should happen before step \ref{root-stack-init}
  7391. above, which depends on \code{r15}.
  7392. The conclusion of every function should do the following.
  7393. \begin{enumerate}
  7394. \item Move the stack pointer back up by the size of the stack frame
  7395. for this function.
  7396. \item Restore the callee-saved registers by popping them from the
  7397. stack.
  7398. \item Move the root stack pointer back down by the size of the
  7399. root-stack frame for this function.
  7400. \item Restore \code{rbp} by popping it from the stack.
  7401. \item Return to the caller with the \code{retq} instruction.
  7402. \end{enumerate}
  7403. \begin{exercise}\normalfont
  7404. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7405. Create 5 new programs that use functions, including examples that pass
  7406. functions and return functions from other functions, recursive
  7407. functions, functions that create vectors, and functions that make tail
  7408. calls. Test your compiler on these new programs and all of your
  7409. previously created test programs.
  7410. \end{exercise}
  7411. \begin{figure}[tbp]
  7412. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7413. \node (Rfun) at (0,2) {\large \LangFun{}};
  7414. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7415. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7416. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7417. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7418. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7419. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7420. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7421. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7422. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7423. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7424. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7425. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7426. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7427. \path[->,bend left=15] (Rfun) edge [above] node
  7428. {\ttfamily\footnotesize shrink} (Rfun-1);
  7429. \path[->,bend left=15] (Rfun-1) edge [above] node
  7430. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7431. \path[->,bend left=15] (Rfun-2) edge [right] node
  7432. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7433. \path[->,bend left=15] (F1-1) edge [below] node
  7434. {\ttfamily\footnotesize limit-functions} (F1-2);
  7435. \path[->,bend right=15] (F1-2) edge [above] node
  7436. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7437. \path[->,bend right=15] (F1-3) edge [above] node
  7438. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7439. \path[->,bend left=15] (F1-4) edge [right] node
  7440. {\ttfamily\footnotesize explicate-control} (C3-2);
  7441. \path[->,bend right=15] (C3-2) edge [left] node
  7442. {\ttfamily\footnotesize select-instr.} (x86-2);
  7443. \path[->,bend left=15] (x86-2) edge [left] node
  7444. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7445. \path[->,bend right=15] (x86-2-1) edge [below] node
  7446. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7447. \path[->,bend right=15] (x86-2-2) edge [left] node
  7448. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7449. \path[->,bend left=15] (x86-3) edge [above] node
  7450. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7451. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7452. \end{tikzpicture}
  7453. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7454. \label{fig:Rfun-passes}
  7455. \end{figure}
  7456. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7457. compiling \LangFun{} to x86.
  7458. \section{An Example Translation}
  7459. \label{sec:functions-example}
  7460. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7461. function in \LangFun{} to x86. The figure also includes the results of the
  7462. \code{explicate-control} and \code{select-instructions} passes.
  7463. \begin{figure}[htbp]
  7464. \begin{tabular}{ll}
  7465. \begin{minipage}{0.5\textwidth}
  7466. % s3_2.rkt
  7467. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7468. (define (add [x : Integer] [y : Integer])
  7469. : Integer
  7470. (+ x y))
  7471. (add 40 2)
  7472. \end{lstlisting}
  7473. $\Downarrow$
  7474. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7475. (define (add86 [x87 : Integer]
  7476. [y88 : Integer]) : Integer
  7477. add86start:
  7478. return (+ x87 y88);
  7479. )
  7480. (define (main) : Integer ()
  7481. mainstart:
  7482. tmp89 = (fun-ref add86);
  7483. (tail-call tmp89 40 2)
  7484. )
  7485. \end{lstlisting}
  7486. \end{minipage}
  7487. &
  7488. $\Rightarrow$
  7489. \begin{minipage}{0.5\textwidth}
  7490. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7491. (define (add86) : Integer
  7492. add86start:
  7493. movq %rdi, x87
  7494. movq %rsi, y88
  7495. movq x87, %rax
  7496. addq y88, %rax
  7497. jmp add11389conclusion
  7498. )
  7499. (define (main) : Integer
  7500. mainstart:
  7501. leaq (fun-ref add86), tmp89
  7502. movq $40, %rdi
  7503. movq $2, %rsi
  7504. tail-jmp tmp89
  7505. )
  7506. \end{lstlisting}
  7507. $\Downarrow$
  7508. \end{minipage}
  7509. \end{tabular}
  7510. \begin{tabular}{ll}
  7511. \begin{minipage}{0.3\textwidth}
  7512. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7513. .globl add86
  7514. .align 16
  7515. add86:
  7516. pushq %rbp
  7517. movq %rsp, %rbp
  7518. jmp add86start
  7519. add86start:
  7520. movq %rdi, %rax
  7521. addq %rsi, %rax
  7522. jmp add86conclusion
  7523. add86conclusion:
  7524. popq %rbp
  7525. retq
  7526. \end{lstlisting}
  7527. \end{minipage}
  7528. &
  7529. \begin{minipage}{0.5\textwidth}
  7530. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7531. .globl main
  7532. .align 16
  7533. main:
  7534. pushq %rbp
  7535. movq %rsp, %rbp
  7536. movq $16384, %rdi
  7537. movq $16384, %rsi
  7538. callq initialize
  7539. movq rootstack_begin(%rip), %r15
  7540. jmp mainstart
  7541. mainstart:
  7542. leaq add86(%rip), %rcx
  7543. movq $40, %rdi
  7544. movq $2, %rsi
  7545. movq %rcx, %rax
  7546. popq %rbp
  7547. jmp *%rax
  7548. mainconclusion:
  7549. popq %rbp
  7550. retq
  7551. \end{lstlisting}
  7552. \end{minipage}
  7553. \end{tabular}
  7554. \caption{Example compilation of a simple function to x86.}
  7555. \label{fig:add-fun}
  7556. \end{figure}
  7557. % Challenge idea: inlining! (simple version)
  7558. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7559. \chapter{Lexically Scoped Functions}
  7560. \label{ch:lambdas}
  7561. \index{lambda}
  7562. \index{lexical scoping}
  7563. This chapter studies lexically scoped functions as they appear in
  7564. functional languages such as Racket. By lexical scoping we mean that a
  7565. function's body may refer to variables whose binding site is outside
  7566. of the function, in an enclosing scope.
  7567. %
  7568. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7569. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7570. \key{lambda} form. The body of the \key{lambda}, refers to three
  7571. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7572. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7573. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7574. parameter of function \code{f}. The \key{lambda} is returned from the
  7575. function \code{f}. The main expression of the program includes two
  7576. calls to \code{f} with different arguments for \code{x}, first
  7577. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7578. to variables \code{g} and \code{h}. Even though these two functions
  7579. were created by the same \code{lambda}, they are really different
  7580. functions because they use different values for \code{x}. Applying
  7581. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7582. \code{15} produces \code{22}. The result of this program is \code{42}.
  7583. \begin{figure}[btp]
  7584. % s4_6.rkt
  7585. \begin{lstlisting}
  7586. (define (f [x : Integer]) : (Integer -> Integer)
  7587. (let ([y 4])
  7588. (lambda: ([z : Integer]) : Integer
  7589. (+ x (+ y z)))))
  7590. (let ([g (f 5)])
  7591. (let ([h (f 3)])
  7592. (+ (g 11) (h 15))))
  7593. \end{lstlisting}
  7594. \caption{Example of a lexically scoped function.}
  7595. \label{fig:lexical-scoping}
  7596. \end{figure}
  7597. The approach that we take for implementing lexically scoped
  7598. functions is to compile them into top-level function definitions,
  7599. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7600. provide special treatment for variable occurrences such as \code{x}
  7601. and \code{y} in the body of the \code{lambda} of
  7602. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7603. refer to variables defined outside of it. To identify such variable
  7604. occurrences, we review the standard notion of free variable.
  7605. \begin{definition}
  7606. A variable is \emph{free in expression} $e$ if the variable occurs
  7607. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7608. variable}
  7609. \end{definition}
  7610. For example, in the expression \code{(+ x (+ y z))} the variables
  7611. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7612. only \code{x} and \code{y} are free in the following expression
  7613. because \code{z} is bound by the \code{lambda}.
  7614. \begin{lstlisting}
  7615. (lambda: ([z : Integer]) : Integer
  7616. (+ x (+ y z)))
  7617. \end{lstlisting}
  7618. So the free variables of a \code{lambda} are the ones that will need
  7619. special treatment. We need to arrange for some way to transport, at
  7620. runtime, the values of those variables from the point where the
  7621. \code{lambda} was created to the point where the \code{lambda} is
  7622. applied. An efficient solution to the problem, due to
  7623. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7624. free variables together with the function pointer for the lambda's
  7625. code, an arrangement called a \emph{flat closure} (which we shorten to
  7626. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7627. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7628. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7629. pointers. The function pointer resides at index $0$ and the
  7630. values for the free variables will fill in the rest of the vector.
  7631. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7632. how closures work. It's a three-step dance. The program first calls
  7633. function \code{f}, which creates a closure for the \code{lambda}. The
  7634. closure is a vector whose first element is a pointer to the top-level
  7635. function that we will generate for the \code{lambda}, the second
  7636. element is the value of \code{x}, which is \code{5}, and the third
  7637. element is \code{4}, the value of \code{y}. The closure does not
  7638. contain an element for \code{z} because \code{z} is not a free
  7639. variable of the \code{lambda}. Creating the closure is step 1 of the
  7640. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7641. shown in Figure~\ref{fig:closures}.
  7642. %
  7643. The second call to \code{f} creates another closure, this time with
  7644. \code{3} in the second slot (for \code{x}). This closure is also
  7645. returned from \code{f} but bound to \code{h}, which is also shown in
  7646. Figure~\ref{fig:closures}.
  7647. \begin{figure}[tbp]
  7648. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7649. \caption{Example closure representation for the \key{lambda}'s
  7650. in Figure~\ref{fig:lexical-scoping}.}
  7651. \label{fig:closures}
  7652. \end{figure}
  7653. Continuing with the example, consider the application of \code{g} to
  7654. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7655. obtain the function pointer in the first element of the closure and
  7656. call it, passing in the closure itself and then the regular arguments,
  7657. in this case \code{11}. This technique for applying a closure is step
  7658. 2 of the dance.
  7659. %
  7660. But doesn't this \code{lambda} only take 1 argument, for parameter
  7661. \code{z}? The third and final step of the dance is generating a
  7662. top-level function for a \code{lambda}. We add an additional
  7663. parameter for the closure and we insert a \code{let} at the beginning
  7664. of the function for each free variable, to bind those variables to the
  7665. appropriate elements from the closure parameter.
  7666. %
  7667. This three-step dance is known as \emph{closure conversion}. We
  7668. discuss the details of closure conversion in
  7669. Section~\ref{sec:closure-conversion} and the code generated from the
  7670. example in Section~\ref{sec:example-lambda}. But first we define the
  7671. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7672. \section{The \LangLam{} Language}
  7673. \label{sec:r5}
  7674. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7675. functions and lexical scoping, is defined in
  7676. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7677. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7678. syntax for function application.
  7679. \begin{figure}[tp]
  7680. \centering
  7681. \fbox{
  7682. \begin{minipage}{0.96\textwidth}
  7683. \small
  7684. \[
  7685. \begin{array}{lcl}
  7686. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7687. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7688. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7689. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7690. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7691. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7692. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7693. \mid (\key{and}\;\Exp\;\Exp)
  7694. \mid (\key{or}\;\Exp\;\Exp)
  7695. \mid (\key{not}\;\Exp) } \\
  7696. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7697. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7698. (\key{vector-ref}\;\Exp\;\Int)} \\
  7699. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7700. \mid (\Exp \; \Exp\ldots) } \\
  7701. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7702. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7703. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7704. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  7705. \end{array}
  7706. \]
  7707. \end{minipage}
  7708. }
  7709. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:r4-concrete-syntax})
  7710. with \key{lambda}.}
  7711. \label{fig:r5-concrete-syntax}
  7712. \end{figure}
  7713. \begin{figure}[tp]
  7714. \centering
  7715. \fbox{
  7716. \begin{minipage}{0.96\textwidth}
  7717. \small
  7718. \[
  7719. \begin{array}{lcl}
  7720. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7721. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7722. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7723. &\mid& \gray{ \BOOL{\itm{bool}}
  7724. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7725. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7726. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7727. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7728. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7729. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7730. \end{array}
  7731. \]
  7732. \end{minipage}
  7733. }
  7734. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:r4-syntax}).}
  7735. \label{fig:r5-syntax}
  7736. \end{figure}
  7737. \index{interpreter}
  7738. \label{sec:interp-Rlambda}
  7739. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  7740. \LangLam{}. The clause for \key{lambda} saves the current environment
  7741. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7742. the environment from the \key{lambda}, the \code{lam-env}, when
  7743. interpreting the body of the \key{lambda}. The \code{lam-env}
  7744. environment is extended with the mapping of parameters to argument
  7745. values.
  7746. \begin{figure}[tbp]
  7747. \begin{lstlisting}
  7748. (define interp-Rlambda-class
  7749. (class interp-Rfun-class
  7750. (super-new)
  7751. (define/override (interp-op op)
  7752. (match op
  7753. ['procedure-arity
  7754. (lambda (v)
  7755. (match v
  7756. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  7757. [else (error 'interp-op "expected a function, not ~a" v)]))]
  7758. [else (super interp-op op)]))
  7759. (define/override ((interp-exp env) e)
  7760. (define recur (interp-exp env))
  7761. (match e
  7762. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7763. `(function ,xs ,body ,env)]
  7764. [else ((super interp-exp env) e)]))
  7765. ))
  7766. (define (interp-Rlambda p)
  7767. (send (new interp-Rlambda-class) interp-program p))
  7768. \end{lstlisting}
  7769. \caption{Interpreter for \LangLam{}.}
  7770. \label{fig:interp-Rlambda}
  7771. \end{figure}
  7772. \label{sec:type-check-r5}
  7773. \index{type checking}
  7774. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  7775. \key{lambda} form. The body of the \key{lambda} is checked in an
  7776. environment that includes the current environment (because it is
  7777. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7778. require the body's type to match the declared return type.
  7779. \begin{figure}[tbp]
  7780. \begin{lstlisting}
  7781. (define (type-check-Rlambda env)
  7782. (lambda (e)
  7783. (match e
  7784. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7785. (define-values (new-body bodyT)
  7786. ((type-check-exp (append (map cons xs Ts) env)) body))
  7787. (define ty `(,@Ts -> ,rT))
  7788. (cond
  7789. [(equal? rT bodyT)
  7790. (values (HasType (Lambda params rT new-body) ty) ty)]
  7791. [else
  7792. (error "mismatch in return type" bodyT rT)])]
  7793. ...
  7794. )))
  7795. \end{lstlisting}
  7796. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  7797. \label{fig:type-check-Rlambda}
  7798. \end{figure}
  7799. \section{Reveal Functions and the $F_2$ language}
  7800. \label{sec:reveal-functions-r5}
  7801. To support the \code{procedure-arity} operator we need to communicate
  7802. the arity of a function to the point of closure creation. We can
  7803. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7804. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7805. output of this pass is the language $F_2$, whose syntax is defined in
  7806. Figure~\ref{fig:f2-syntax}.
  7807. \begin{figure}[tp]
  7808. \centering
  7809. \fbox{
  7810. \begin{minipage}{0.96\textwidth}
  7811. \[
  7812. \begin{array}{lcl}
  7813. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7814. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7815. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7816. \end{array}
  7817. \]
  7818. \end{minipage}
  7819. }
  7820. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  7821. (Figure~\ref{fig:r5-syntax}).}
  7822. \label{fig:f2-syntax}
  7823. \end{figure}
  7824. \section{Closure Conversion}
  7825. \label{sec:closure-conversion}
  7826. \index{closure conversion}
  7827. The compiling of lexically-scoped functions into top-level function
  7828. definitions is accomplished in the pass \code{convert-to-closures}
  7829. that comes after \code{reveal-functions} and before
  7830. \code{limit-functions}.
  7831. As usual, we implement the pass as a recursive function over the
  7832. AST. All of the action is in the clauses for \key{Lambda} and
  7833. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7834. that creates a closure, that is, a vector whose first element is a
  7835. function pointer and the rest of the elements are the free variables
  7836. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7837. using \code{vector} so that we can distinguish closures from vectors
  7838. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7839. the generated code below, the \itm{name} is a unique symbol generated
  7840. to identify the function and the \itm{arity} is the number of
  7841. parameters (the length of \itm{ps}).
  7842. \begin{lstlisting}
  7843. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7844. |$\Rightarrow$|
  7845. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7846. \end{lstlisting}
  7847. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7848. create a top-level function definition for each \key{Lambda}, as
  7849. shown below.\\
  7850. \begin{minipage}{0.8\textwidth}
  7851. \begin{lstlisting}
  7852. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  7853. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  7854. ...
  7855. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  7856. |\itm{body'}|)...))
  7857. \end{lstlisting}
  7858. \end{minipage}\\
  7859. The \code{clos} parameter refers to the closure. Translate the type
  7860. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  7861. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  7862. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7863. underscore \code{\_} is a dummy type that we use because it is rather
  7864. difficult to give a type to the function in the closure's
  7865. type.\footnote{To give an accurate type to a closure, we would need to
  7866. add existential types to the type checker~\citep{Minamide:1996ys}.}
  7867. The dummy type is considered to be equal to any other type during type
  7868. checking. The sequence of \key{Let} forms bind the free variables to
  7869. their values obtained from the closure.
  7870. Closure conversion turns functions into vectors, so the type
  7871. annotations in the program must also be translated. We recommend
  7872. defining a auxiliary recursive function for this purpose. Function
  7873. types should be translated as follows.
  7874. \begin{lstlisting}
  7875. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  7876. |$\Rightarrow$|
  7877. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  7878. \end{lstlisting}
  7879. The above type says that the first thing in the vector is a function
  7880. pointer. The first parameter of the function pointer is a vector (a
  7881. closure) and the rest of the parameters are the ones from the original
  7882. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  7883. the closure omits the types of the free variables because 1) those
  7884. types are not available in this context and 2) we do not need them in
  7885. the code that is generated for function application.
  7886. We transform function application into code that retrieves the
  7887. function pointer from the closure and then calls the function, passing
  7888. in the closure as the first argument. We bind $e'$ to a temporary
  7889. variable to avoid code duplication.
  7890. \begin{lstlisting}
  7891. (Apply |$e$| |\itm{es}|)
  7892. |$\Rightarrow$|
  7893. (Let |\itm{tmp}| |$e'$|
  7894. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  7895. \end{lstlisting}
  7896. There is also the question of what to do with references top-level
  7897. function definitions. To maintain a uniform translation of function
  7898. application, we turn function references into closures.
  7899. \begin{tabular}{lll}
  7900. \begin{minipage}{0.3\textwidth}
  7901. \begin{lstlisting}
  7902. (FunRefArity |$f$| |$n$|)
  7903. \end{lstlisting}
  7904. \end{minipage}
  7905. &
  7906. $\Rightarrow$
  7907. &
  7908. \begin{minipage}{0.5\textwidth}
  7909. \begin{lstlisting}
  7910. (Closure |$n$| (FunRef |$f$|) '())
  7911. \end{lstlisting}
  7912. \end{minipage}
  7913. \end{tabular} \\
  7914. %
  7915. The top-level function definitions need to be updated as well to take
  7916. an extra closure parameter.
  7917. \section{An Example Translation}
  7918. \label{sec:example-lambda}
  7919. Figure~\ref{fig:lexical-functions-example} shows the result of
  7920. \code{reveal-functions} and \code{convert-to-closures} for the example
  7921. program demonstrating lexical scoping that we discussed at the
  7922. beginning of this chapter.
  7923. \begin{figure}[tbp]
  7924. \begin{minipage}{0.8\textwidth}
  7925. % tests/lambda_test_6.rkt
  7926. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7927. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  7928. (let ([y8 4])
  7929. (lambda: ([z9 : Integer]) : Integer
  7930. (+ x7 (+ y8 z9)))))
  7931. (define (main) : Integer
  7932. (let ([g0 ((fun-ref-arity f6 1) 5)])
  7933. (let ([h1 ((fun-ref-arity f6 1) 3)])
  7934. (+ (g0 11) (h1 15)))))
  7935. \end{lstlisting}
  7936. $\Rightarrow$
  7937. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7938. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7939. (let ([y8 4])
  7940. (closure 1 (list (fun-ref lambda2) x7 y8))))
  7941. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  7942. (let ([x7 (vector-ref fvs3 1)])
  7943. (let ([y8 (vector-ref fvs3 2)])
  7944. (+ x7 (+ y8 z9)))))
  7945. (define (main) : Integer
  7946. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  7947. ((vector-ref clos5 0) clos5 5))])
  7948. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  7949. ((vector-ref clos6 0) clos6 3))])
  7950. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  7951. \end{lstlisting}
  7952. \end{minipage}
  7953. \caption{Example of closure conversion.}
  7954. \label{fig:lexical-functions-example}
  7955. \end{figure}
  7956. \begin{exercise}\normalfont
  7957. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  7958. Create 5 new programs that use \key{lambda} functions and make use of
  7959. lexical scoping. Test your compiler on these new programs and all of
  7960. your previously created test programs.
  7961. \end{exercise}
  7962. \section{Expose Allocation}
  7963. \label{sec:expose-allocation-r5}
  7964. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  7965. that allocates and initializes a vector, similar to the translation of
  7966. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  7967. The only difference is replacing the use of
  7968. \ALLOC{\itm{len}}{\itm{type}} with
  7969. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  7970. \section{Explicate Control and \LangCLam{}}
  7971. \label{sec:explicate-r5}
  7972. The output language of \code{explicate-control} is \LangCLam{} whose
  7973. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  7974. difference with respect to \LangCFun{} is the addition of the
  7975. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  7976. of \code{AllocateClosure} in the \code{explicate-control} pass is
  7977. similar to the handling of other expressions such as primitive
  7978. operators.
  7979. \begin{figure}[tp]
  7980. \fbox{
  7981. \begin{minipage}{0.96\textwidth}
  7982. \small
  7983. \[
  7984. \begin{array}{lcl}
  7985. \Exp &::= & \ldots
  7986. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  7987. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7988. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7989. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7990. \mid \GOTO{\itm{label}} } \\
  7991. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7992. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  7993. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  7994. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  7995. \end{array}
  7996. \]
  7997. \end{minipage}
  7998. }
  7999. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8000. \label{fig:c4-syntax}
  8001. \end{figure}
  8002. \section{Select Instructions}
  8003. \label{sec:select-instructions-Rlambda}
  8004. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8005. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8006. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8007. that you should place the \itm{arity} in the tag that is stored at
  8008. position $0$ of the vector. Recall that in
  8009. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  8010. of the 64-bit tag, but that the rest were unused. So the arity goes
  8011. into the tag in bit positions $57$ through $63$.
  8012. Compile the \code{procedure-arity} operator into a sequence of
  8013. instructions that access the tag from position $0$ of the vector and
  8014. shift it by $57$ bits to the right.
  8015. \begin{figure}[p]
  8016. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8017. \node (Rfun) at (0,2) {\large \LangFun{}};
  8018. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8019. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8020. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8021. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8022. \node (F1-3) at (6,0) {\large $F_1$};
  8023. \node (F1-4) at (3,0) {\large $F_1$};
  8024. \node (F1-5) at (0,0) {\large $F_1$};
  8025. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8026. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8027. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8028. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8029. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8030. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8031. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8032. \path[->,bend left=15] (Rfun) edge [above] node
  8033. {\ttfamily\footnotesize shrink} (Rfun-2);
  8034. \path[->,bend left=15] (Rfun-2) edge [above] node
  8035. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8036. \path[->,bend left=15] (Rfun-3) edge [right] node
  8037. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8038. \path[->,bend left=15] (F1-1) edge [below] node
  8039. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8040. \path[->,bend right=15] (F1-2) edge [above] node
  8041. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8042. \path[->,bend right=15] (F1-3) edge [above] node
  8043. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8044. \path[->,bend right=15] (F1-4) edge [above] node
  8045. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8046. \path[->,bend right=15] (F1-5) edge [right] node
  8047. {\ttfamily\footnotesize explicate-control} (C3-2);
  8048. \path[->,bend left=15] (C3-2) edge [left] node
  8049. {\ttfamily\footnotesize select-instr.} (x86-2);
  8050. \path[->,bend right=15] (x86-2) edge [left] node
  8051. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8052. \path[->,bend right=15] (x86-2-1) edge [below] node
  8053. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8054. \path[->,bend right=15] (x86-2-2) edge [left] node
  8055. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8056. \path[->,bend left=15] (x86-3) edge [above] node
  8057. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8058. \path[->,bend left=15] (x86-4) edge [right] node
  8059. {\ttfamily\footnotesize print-x86} (x86-5);
  8060. \end{tikzpicture}
  8061. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8062. functions.}
  8063. \label{fig:Rlambda-passes}
  8064. \end{figure}
  8065. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8066. for the compilation of \LangLam{}.
  8067. \clearpage
  8068. \section{Challenge: Optimize Closures}
  8069. \label{sec:optimize-closures}
  8070. In this chapter we compiled lexically-scoped functions into a
  8071. relatively efficient representation: flat closures. However, even this
  8072. representation comes with some overhead. For example, consider the
  8073. following program with a function \code{tail-sum} that does not have
  8074. any free variables and where all the uses of \code{tail-sum} are in
  8075. applications where we know that only \code{tail-sum} is being applied
  8076. (and not any other functions).
  8077. \begin{center}
  8078. \begin{minipage}{0.95\textwidth}
  8079. \begin{lstlisting}
  8080. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8081. (if (eq? n 0)
  8082. r
  8083. (tail-sum (- n 1) (+ n r))))
  8084. (+ (tail-sum 5 0) 27)
  8085. \end{lstlisting}
  8086. \end{minipage}
  8087. \end{center}
  8088. As described in this chapter, we uniformly apply closure conversion to
  8089. all functions, obtaining the following output for this program.
  8090. \begin{center}
  8091. \begin{minipage}{0.95\textwidth}
  8092. \begin{lstlisting}
  8093. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8094. (if (eq? n2 0)
  8095. r3
  8096. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8097. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8098. (define (main) : Integer
  8099. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8100. ((vector-ref clos6 0) clos6 5 0)) 27))
  8101. \end{lstlisting}
  8102. \end{minipage}
  8103. \end{center}
  8104. In the previous Chapter, there would be no allocation in the program
  8105. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8106. the above program allocates memory for each \code{closure} and the
  8107. calls to \code{tail-sum} are indirect. These two differences incur
  8108. considerable overhead in a program such as this one, where the
  8109. allocations and indirect calls occur inside a tight loop.
  8110. One might think that this problem is trivial to solve: can't we just
  8111. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8112. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8113. e'_n$)} instead of treating it like a call to a closure? We would
  8114. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8115. %
  8116. However, this problem is not so trivial because a global function may
  8117. ``escape'' and become involved in applications that also involve
  8118. closures. Consider the following example in which the application
  8119. \code{(f 41)} needs to be compiled into a closure application, because
  8120. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8121. function might also get bound to \code{f}.
  8122. \begin{lstlisting}
  8123. (define (add1 [x : Integer]) : Integer
  8124. (+ x 1))
  8125. (let ([y (read)])
  8126. (let ([f (if (eq? (read) 0)
  8127. add1
  8128. (lambda: ([x : Integer]) : Integer (- x y)))])
  8129. (f 41)))
  8130. \end{lstlisting}
  8131. If a global function name is used in any way other than as the
  8132. operator in a direct call, then we say that the function
  8133. \emph{escapes}. If a global function does not escape, then we do not
  8134. need to perform closure conversion on the function.
  8135. \begin{exercise}\normalfont
  8136. Implement an auxiliary function for detecting which global
  8137. functions escape. Using that function, implement an improved version
  8138. of closure conversion that does not apply closure conversion to
  8139. global functions that do not escape but instead compiles them as
  8140. regular functions. Create several new test cases that check whether
  8141. you properly detect whether global functions escape or not.
  8142. \end{exercise}
  8143. So far we have reduced the overhead of calling global functions, but
  8144. it would also be nice to reduce the overhead of calling a
  8145. \code{lambda} when we can determine at compile time which
  8146. \code{lambda} will be called. We refer to such calls as \emph{known
  8147. calls}. Consider the following example in which a \code{lambda} is
  8148. bound to \code{f} and then applied.
  8149. \begin{lstlisting}
  8150. (let ([y (read)])
  8151. (let ([f (lambda: ([x : Integer]) : Integer
  8152. (+ x y))])
  8153. (f 21)))
  8154. \end{lstlisting}
  8155. Closure conversion compiles \code{(f 21)} into an indirect call:
  8156. \begin{lstlisting}
  8157. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8158. (let ([y2 (vector-ref fvs6 1)])
  8159. (+ x3 y2)))
  8160. (define (main) : Integer
  8161. (let ([y2 (read)])
  8162. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8163. ((vector-ref f4 0) f4 21))))
  8164. \end{lstlisting}
  8165. but we can instead compile the application \code{(f 21)} into a direct call
  8166. to \code{lambda5}:
  8167. \begin{lstlisting}
  8168. (define (main) : Integer
  8169. (let ([y2 (read)])
  8170. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8171. ((fun-ref lambda5) f4 21))))
  8172. \end{lstlisting}
  8173. The problem of determining which lambda will be called from a
  8174. particular application is quite challenging in general and the topic
  8175. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8176. following exercise we recommend that you compile an application to a
  8177. direct call when the operator is a variable and the variable is
  8178. \code{let}-bound to a closure. This can be accomplished by maintaining
  8179. an environment mapping \code{let}-bound variables to function names.
  8180. Extend the environment whenever you encounter a closure on the
  8181. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8182. to the name of the global function for the closure. This pass should
  8183. come after closure conversion.
  8184. \begin{exercise}\normalfont
  8185. Implement a compiler pass, named \code{optimize-known-calls}, that
  8186. compiles known calls into direct calls. Verify that your compiler is
  8187. successful in this regard on several example programs.
  8188. \end{exercise}
  8189. These exercises only scratches the surface of optimizing of
  8190. closures. A good next step for the interested reader is to look at the
  8191. work of \citet{Keep:2012ab}.
  8192. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8193. \chapter{Dynamic Typing}
  8194. \label{ch:type-dynamic}
  8195. \index{dynamic typing}
  8196. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8197. typed language that is a subset of Racket. This is in contrast to the
  8198. previous chapters, which have studied the compilation of Typed
  8199. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8200. expression may produce a value of a different type each time it is
  8201. executed. Consider the following example with a conditional \code{if}
  8202. expression that may return a Boolean or an integer depending on the
  8203. input to the program.
  8204. % part of dynamic_test_25.rkt
  8205. \begin{lstlisting}
  8206. (not (if (eq? (read) 1) #f 0))
  8207. \end{lstlisting}
  8208. Languages that allow expressions to produce different kinds of values
  8209. are called \emph{polymorphic}, a word composed of the Greek roots
  8210. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8211. are several kinds of polymorphism in programming languages, such as
  8212. subtype polymorphism and parametric
  8213. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8214. study in this chapter does not have a special name but it is the kind
  8215. that arises in dynamically typed languages.
  8216. Another characteristic of dynamically typed languages is that
  8217. primitive operations, such as \code{not}, are often defined to operate
  8218. on many different types of values. In fact, in Racket, the \code{not}
  8219. operator produces a result for any kind of value: given \code{\#f} it
  8220. returns \code{\#t} and given anything else it returns \code{\#f}.
  8221. Furthermore, even when primitive operations restrict their inputs to
  8222. values of a certain type, this restriction is enforced at runtime
  8223. instead of during compilation. For example, the following vector
  8224. reference results in a run-time contract violation because the index
  8225. must be in integer, not a Boolean such as \code{\#t}.
  8226. \begin{lstlisting}
  8227. (vector-ref (vector 42) #t)
  8228. \end{lstlisting}
  8229. \begin{figure}[tp]
  8230. \centering
  8231. \fbox{
  8232. \begin{minipage}{0.97\textwidth}
  8233. \[
  8234. \begin{array}{rcl}
  8235. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8236. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8237. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8238. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8239. &\mid& \key{\#t} \mid \key{\#f}
  8240. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8241. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8242. \mid \CUNIOP{\key{not}}{\Exp} \\
  8243. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8244. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8245. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8246. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8247. &\mid& \LP\Exp \; \Exp\ldots\RP
  8248. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8249. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8250. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8251. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8252. \LangDyn{} &::=& \Def\ldots\; \Exp
  8253. \end{array}
  8254. \]
  8255. \end{minipage}
  8256. }
  8257. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8258. \label{fig:r7-concrete-syntax}
  8259. \end{figure}
  8260. \begin{figure}[tp]
  8261. \centering
  8262. \fbox{
  8263. \begin{minipage}{0.96\textwidth}
  8264. \small
  8265. \[
  8266. \begin{array}{lcl}
  8267. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8268. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8269. &\mid& \BOOL{\itm{bool}}
  8270. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8271. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8272. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8273. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8274. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8275. \end{array}
  8276. \]
  8277. \end{minipage}
  8278. }
  8279. \caption{The abstract syntax of \LangDyn{}.}
  8280. \label{fig:r7-syntax}
  8281. \end{figure}
  8282. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8283. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8284. \ref{fig:r7-syntax}.
  8285. %
  8286. There is no type checker for \LangDyn{} because it is not a statically
  8287. typed language (it's dynamically typed!).
  8288. The definitional interpreter for \LangDyn{} is presented in
  8289. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined in
  8290. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match clause for
  8291. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8292. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8293. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8294. value} that combines an underlying value with a tag that identifies
  8295. what kind of value it is. We define the following struct
  8296. to represented tagged values.
  8297. \begin{lstlisting}
  8298. (struct Tagged (value tag) #:transparent)
  8299. \end{lstlisting}
  8300. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8301. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8302. but don't always capture all the information that a type does. For
  8303. example, a vector of type \code{(Vector Any Any)} is tagged with
  8304. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8305. is tagged with \code{Procedure}.
  8306. Next consider the match clause for \code{vector-ref}. The
  8307. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8308. is used to ensure that the first argument is a vector and the second
  8309. is an integer. If they are not, a \code{trapped-error} is raised.
  8310. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8311. interpreter raises a \code{trapped-error} error, the compiled code
  8312. must also signal an error by exiting with return code \code{255}. A
  8313. \code{trapped-error} is also raised if the index is not less than
  8314. length of the vector.
  8315. \begin{figure}[tbp]
  8316. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8317. (define ((interp-Rdyn-exp env) ast)
  8318. (define recur (interp-Rdyn-exp env))
  8319. (match ast
  8320. [(Var x) (lookup x env)]
  8321. [(Int n) (Tagged n 'Integer)]
  8322. [(Bool b) (Tagged b 'Boolean)]
  8323. [(Lambda xs rt body)
  8324. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8325. [(Prim 'vector es)
  8326. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8327. [(Prim 'vector-ref (list e1 e2))
  8328. (define vec (recur e1)) (define i (recur e2))
  8329. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8330. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8331. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8332. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8333. [(Prim 'vector-set! (list e1 e2 e3))
  8334. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8335. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8336. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8337. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8338. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8339. (Tagged (void) 'Void)]
  8340. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8341. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8342. [(Prim 'or (list e1 e2))
  8343. (define v1 (recur e1))
  8344. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8345. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8346. [(Prim op (list e1))
  8347. #:when (set-member? type-predicates op)
  8348. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8349. [(Prim op es)
  8350. (define args (map recur es))
  8351. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8352. (unless (for/or ([expected-tags (op-tags op)])
  8353. (equal? expected-tags tags))
  8354. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8355. (tag-value
  8356. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8357. [(If q t f)
  8358. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8359. [(Apply f es)
  8360. (define new-f (recur f)) (define args (map recur es))
  8361. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8362. (match f-val
  8363. [`(function ,xs ,body ,lam-env)
  8364. (unless (eq? (length xs) (length args))
  8365. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8366. (define new-env (append (map cons xs args) lam-env))
  8367. ((interp-Rdyn-exp new-env) body)]
  8368. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8369. \end{lstlisting}
  8370. \caption{Interpreter for the \LangDyn{} language.}
  8371. \label{fig:interp-Rdyn}
  8372. \end{figure}
  8373. \begin{figure}[tbp]
  8374. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8375. (define (interp-op op)
  8376. (match op
  8377. ['+ fx+]
  8378. ['- fx-]
  8379. ['read read-fixnum]
  8380. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8381. ['< (lambda (v1 v2)
  8382. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8383. ['<= (lambda (v1 v2)
  8384. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8385. ['> (lambda (v1 v2)
  8386. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8387. ['>= (lambda (v1 v2)
  8388. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8389. ['boolean? boolean?]
  8390. ['integer? fixnum?]
  8391. ['void? void?]
  8392. ['vector? vector?]
  8393. ['vector-length vector-length]
  8394. ['procedure? (match-lambda
  8395. [`(functions ,xs ,body ,env) #t] [else #f])]
  8396. [else (error 'interp-op "unknown operator" op)]))
  8397. (define (op-tags op)
  8398. (match op
  8399. ['+ '((Integer Integer))]
  8400. ['- '((Integer Integer) (Integer))]
  8401. ['read '(())]
  8402. ['not '((Boolean))]
  8403. ['< '((Integer Integer))]
  8404. ['<= '((Integer Integer))]
  8405. ['> '((Integer Integer))]
  8406. ['>= '((Integer Integer))]
  8407. ['vector-length '((Vector))]))
  8408. (define type-predicates
  8409. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8410. (define (tag-value v)
  8411. (cond [(boolean? v) (Tagged v 'Boolean)]
  8412. [(fixnum? v) (Tagged v 'Integer)]
  8413. [(procedure? v) (Tagged v 'Procedure)]
  8414. [(vector? v) (Tagged v 'Vector)]
  8415. [(void? v) (Tagged v 'Void)]
  8416. [else (error 'tag-value "unidentified value ~a" v)]))
  8417. (define (check-tag val expected ast)
  8418. (define tag (Tagged-tag val))
  8419. (unless (eq? tag expected)
  8420. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8421. \end{lstlisting}
  8422. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8423. \label{fig:interp-Rdyn-aux}
  8424. \end{figure}
  8425. \clearpage
  8426. \section{Representation of Tagged Values}
  8427. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8428. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8429. values at the bit level. Because almost every operation in \LangDyn{}
  8430. involves manipulating tagged values, the representation must be
  8431. efficient. Recall that all of our values are 64 bits. We shall steal
  8432. the 3 right-most bits to encode the tag. We use $001$ to identify
  8433. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8434. and $101$ for the void value. We define the following auxiliary
  8435. function for mapping types to tag codes.
  8436. \begin{align*}
  8437. \itm{tagof}(\key{Integer}) &= 001 \\
  8438. \itm{tagof}(\key{Boolean}) &= 100 \\
  8439. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8440. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8441. \itm{tagof}(\key{Void}) &= 101
  8442. \end{align*}
  8443. This stealing of 3 bits comes at some price: our integers are reduced
  8444. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8445. affect vectors and procedures because those values are addresses, and
  8446. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8447. they are always $000$. Thus, we do not lose information by overwriting
  8448. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8449. to recover the original address.
  8450. To make tagged values into first-class entities, we can give them a
  8451. type, called \code{Any}, and define operations such as \code{Inject}
  8452. and \code{Project} for creating and using them, yielding the \LangAny{}
  8453. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8454. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8455. in greater detail.
  8456. \section{The \LangAny{} Language}
  8457. \label{sec:r6-lang}
  8458. \begin{figure}[tp]
  8459. \centering
  8460. \fbox{
  8461. \begin{minipage}{0.96\textwidth}
  8462. \small
  8463. \[
  8464. \begin{array}{lcl}
  8465. \Type &::= & \ldots \mid \key{Any} \\
  8466. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8467. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8468. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8469. \mid \code{procedure?} \mid \code{void?} \\
  8470. \Exp &::=& \ldots
  8471. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8472. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8473. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8474. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8475. \end{array}
  8476. \]
  8477. \end{minipage}
  8478. }
  8479. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:r5-syntax}).}
  8480. \label{fig:r6-syntax}
  8481. \end{figure}
  8482. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:r6-syntax}.
  8483. (The concrete syntax of \LangAny{} is in the Appendix,
  8484. Figure~\ref{fig:r6-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8485. converts the value produced by expression $e$ of type $T$ into a
  8486. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8487. produced by expression $e$ into a value of type $T$ or else halts the
  8488. program if the type tag is not equivalent to $T$.
  8489. %
  8490. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8491. restricted to a flat type $\FType$, which simplifies the
  8492. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8493. The \code{any-vector} operators adapt the vector operations so that
  8494. they can be applied to a value of type \code{Any}. They also
  8495. generalize the vector operations in that the index is not restricted
  8496. to be a literal integer in the grammar but is allowed to be any
  8497. expression.
  8498. The type predicates such as \key{boolean?} expect their argument to
  8499. produce a tagged value; they return \key{\#t} if the tag corresponds
  8500. to the predicate and they return \key{\#f} otherwise.
  8501. The type checker for \LangAny{} is shown in
  8502. Figures~\ref{fig:type-check-Rany-part-1} and
  8503. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8504. Figure~\ref{fig:type-check-Rany-aux}.
  8505. %
  8506. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8507. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8508. in Figure~\ref{fig:apply-project}.
  8509. \begin{figure}[btp]
  8510. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8511. (define type-check-Rany-class
  8512. (class type-check-Rlambda-class
  8513. (super-new)
  8514. (inherit check-type-equal?)
  8515. (define/override (type-check-exp env)
  8516. (lambda (e)
  8517. (define recur (type-check-exp env))
  8518. (match e
  8519. [(Inject e1 ty)
  8520. (unless (flat-ty? ty)
  8521. (error 'type-check "may only inject from flat type, not ~a" ty))
  8522. (define-values (new-e1 e-ty) (recur e1))
  8523. (check-type-equal? e-ty ty e)
  8524. (values (Inject new-e1 ty) 'Any)]
  8525. [(Project e1 ty)
  8526. (unless (flat-ty? ty)
  8527. (error 'type-check "may only project to flat type, not ~a" ty))
  8528. (define-values (new-e1 e-ty) (recur e1))
  8529. (check-type-equal? e-ty 'Any e)
  8530. (values (Project new-e1 ty) ty)]
  8531. [(Prim 'any-vector-length (list e1))
  8532. (define-values (e1^ t1) (recur e1))
  8533. (check-type-equal? t1 'Any e)
  8534. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8535. [(Prim 'any-vector-ref (list e1 e2))
  8536. (define-values (e1^ t1) (recur e1))
  8537. (define-values (e2^ t2) (recur e2))
  8538. (check-type-equal? t1 'Any e)
  8539. (check-type-equal? t2 'Integer e)
  8540. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8541. [(Prim 'any-vector-set! (list e1 e2 e3))
  8542. (define-values (e1^ t1) (recur e1))
  8543. (define-values (e2^ t2) (recur e2))
  8544. (define-values (e3^ t3) (recur e3))
  8545. (check-type-equal? t1 'Any e)
  8546. (check-type-equal? t2 'Integer e)
  8547. (check-type-equal? t3 'Any e)
  8548. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8549. \end{lstlisting}
  8550. \caption{Type checker for the \LangAny{} language, part 1.}
  8551. \label{fig:type-check-Rany-part-1}
  8552. \end{figure}
  8553. \begin{figure}[btp]
  8554. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8555. [(ValueOf e ty)
  8556. (define-values (new-e e-ty) (recur e))
  8557. (values (ValueOf new-e ty) ty)]
  8558. [(Prim pred (list e1))
  8559. #:when (set-member? (type-predicates) pred)
  8560. (define-values (new-e1 e-ty) (recur e1))
  8561. (check-type-equal? e-ty 'Any e)
  8562. (values (Prim pred (list new-e1)) 'Boolean)]
  8563. [(If cnd thn els)
  8564. (define-values (cnd^ Tc) (recur cnd))
  8565. (define-values (thn^ Tt) (recur thn))
  8566. (define-values (els^ Te) (recur els))
  8567. (check-type-equal? Tc 'Boolean cnd)
  8568. (check-type-equal? Tt Te e)
  8569. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8570. [(Exit) (values (Exit) '_)]
  8571. [(Prim 'eq? (list arg1 arg2))
  8572. (define-values (e1 t1) (recur arg1))
  8573. (define-values (e2 t2) (recur arg2))
  8574. (match* (t1 t2)
  8575. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8576. [(other wise) (check-type-equal? t1 t2 e)])
  8577. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8578. [else ((super type-check-exp env) e)])))
  8579. ))
  8580. \end{lstlisting}
  8581. \caption{Type checker for the \LangAny{} language, part 2.}
  8582. \label{fig:type-check-Rany-part-2}
  8583. \end{figure}
  8584. \begin{figure}[tbp]
  8585. \begin{lstlisting}
  8586. (define/override (operator-types)
  8587. (append
  8588. '((integer? . ((Any) . Boolean))
  8589. (vector? . ((Any) . Boolean))
  8590. (procedure? . ((Any) . Boolean))
  8591. (void? . ((Any) . Boolean))
  8592. (tag-of-any . ((Any) . Integer))
  8593. (make-any . ((_ Integer) . Any))
  8594. )
  8595. (super operator-types)))
  8596. (define/public (type-predicates)
  8597. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8598. (define/public (combine-types t1 t2)
  8599. (match (list t1 t2)
  8600. [(list '_ t2) t2]
  8601. [(list t1 '_) t1]
  8602. [(list `(Vector ,ts1 ...)
  8603. `(Vector ,ts2 ...))
  8604. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8605. (combine-types t1 t2)))]
  8606. [(list `(,ts1 ... -> ,rt1)
  8607. `(,ts2 ... -> ,rt2))
  8608. `(,@(for/list ([t1 ts1] [t2 ts2])
  8609. (combine-types t1 t2))
  8610. -> ,(combine-types rt1 rt2))]
  8611. [else t1]))
  8612. (define/public (flat-ty? ty)
  8613. (match ty
  8614. [(or `Integer `Boolean '_ `Void) #t]
  8615. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8616. [`(,ts ... -> ,rt)
  8617. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8618. [else #f]))
  8619. \end{lstlisting}
  8620. \caption{Auxiliary methods for type checking \LangAny{}.}
  8621. \label{fig:type-check-Rany-aux}
  8622. \end{figure}
  8623. \begin{figure}[btp]
  8624. \begin{lstlisting}
  8625. (define interp-Rany-class
  8626. (class interp-Rlambda-class
  8627. (super-new)
  8628. (define/override (interp-op op)
  8629. (match op
  8630. ['boolean? (match-lambda
  8631. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8632. [else #f])]
  8633. ['integer? (match-lambda
  8634. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8635. [else #f])]
  8636. ['vector? (match-lambda
  8637. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8638. [else #f])]
  8639. ['procedure? (match-lambda
  8640. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8641. [else #f])]
  8642. ['eq? (match-lambda*
  8643. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8644. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8645. [ls (apply (super interp-op op) ls)])]
  8646. ['any-vector-ref (lambda (v i)
  8647. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8648. ['any-vector-set! (lambda (v i a)
  8649. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8650. ['any-vector-length (lambda (v)
  8651. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8652. [else (super interp-op op)]))
  8653. (define/override ((interp-exp env) e)
  8654. (define recur (interp-exp env))
  8655. (match e
  8656. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8657. [(Project e ty2) (apply-project (recur e) ty2)]
  8658. [else ((super interp-exp env) e)]))
  8659. ))
  8660. (define (interp-Rany p)
  8661. (send (new interp-Rany-class) interp-program p))
  8662. \end{lstlisting}
  8663. \caption{Interpreter for \LangAny{}.}
  8664. \label{fig:interp-Rany}
  8665. \end{figure}
  8666. \begin{figure}[tbp]
  8667. \begin{lstlisting}
  8668. (define/public (apply-inject v tg) (Tagged v tg))
  8669. (define/public (apply-project v ty2)
  8670. (define tag2 (any-tag ty2))
  8671. (match v
  8672. [(Tagged v1 tag1)
  8673. (cond
  8674. [(eq? tag1 tag2)
  8675. (match ty2
  8676. [`(Vector ,ts ...)
  8677. (define l1 ((interp-op 'vector-length) v1))
  8678. (cond
  8679. [(eq? l1 (length ts)) v1]
  8680. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8681. l1 (length ts))])]
  8682. [`(,ts ... -> ,rt)
  8683. (match v1
  8684. [`(function ,xs ,body ,env)
  8685. (cond [(eq? (length xs) (length ts)) v1]
  8686. [else
  8687. (error 'apply-project "arity mismatch ~a != ~a"
  8688. (length xs) (length ts))])]
  8689. [else (error 'apply-project "expected function not ~a" v1)])]
  8690. [else v1])]
  8691. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8692. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8693. \end{lstlisting}
  8694. \caption{Auxiliary functions for injection and projection.}
  8695. \label{fig:apply-project}
  8696. \end{figure}
  8697. \clearpage
  8698. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  8699. \label{sec:compile-r7}
  8700. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  8701. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8702. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  8703. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  8704. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  8705. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8706. the Boolean \code{\#t}, which must be injected to produce an
  8707. expression of type \key{Any}.
  8708. %
  8709. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8710. addition, is representative of compilation for many primitive
  8711. operations: the arguments have type \key{Any} and must be projected to
  8712. \key{Integer} before the addition can be performed.
  8713. The compilation of \key{lambda} (third row of
  8714. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8715. produce type annotations: we simply use \key{Any}.
  8716. %
  8717. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8718. has to account for some differences in behavior between \LangDyn{} and
  8719. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  8720. kind of values can be used in various places. For example, the
  8721. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8722. the arguments need not be of the same type (in that case the
  8723. result is \code{\#f}).
  8724. \begin{figure}[btp]
  8725. \centering
  8726. \begin{tabular}{|lll|} \hline
  8727. \begin{minipage}{0.27\textwidth}
  8728. \begin{lstlisting}
  8729. #t
  8730. \end{lstlisting}
  8731. \end{minipage}
  8732. &
  8733. $\Rightarrow$
  8734. &
  8735. \begin{minipage}{0.65\textwidth}
  8736. \begin{lstlisting}
  8737. (inject #t Boolean)
  8738. \end{lstlisting}
  8739. \end{minipage}
  8740. \\[2ex]\hline
  8741. \begin{minipage}{0.27\textwidth}
  8742. \begin{lstlisting}
  8743. (+ |$e_1$| |$e_2$|)
  8744. \end{lstlisting}
  8745. \end{minipage}
  8746. &
  8747. $\Rightarrow$
  8748. &
  8749. \begin{minipage}{0.65\textwidth}
  8750. \begin{lstlisting}
  8751. (inject
  8752. (+ (project |$e'_1$| Integer)
  8753. (project |$e'_2$| Integer))
  8754. Integer)
  8755. \end{lstlisting}
  8756. \end{minipage}
  8757. \\[2ex]\hline
  8758. \begin{minipage}{0.27\textwidth}
  8759. \begin{lstlisting}
  8760. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  8761. \end{lstlisting}
  8762. \end{minipage}
  8763. &
  8764. $\Rightarrow$
  8765. &
  8766. \begin{minipage}{0.65\textwidth}
  8767. \begin{lstlisting}
  8768. (inject
  8769. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  8770. (Any|$\ldots$|Any -> Any))
  8771. \end{lstlisting}
  8772. \end{minipage}
  8773. \\[2ex]\hline
  8774. \begin{minipage}{0.27\textwidth}
  8775. \begin{lstlisting}
  8776. (|$e_0$| |$e_1 \ldots e_n$|)
  8777. \end{lstlisting}
  8778. \end{minipage}
  8779. &
  8780. $\Rightarrow$
  8781. &
  8782. \begin{minipage}{0.65\textwidth}
  8783. \begin{lstlisting}
  8784. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  8785. \end{lstlisting}
  8786. \end{minipage}
  8787. \\[2ex]\hline
  8788. \begin{minipage}{0.27\textwidth}
  8789. \begin{lstlisting}
  8790. (vector-ref |$e_1$| |$e_2$|)
  8791. \end{lstlisting}
  8792. \end{minipage}
  8793. &
  8794. $\Rightarrow$
  8795. &
  8796. \begin{minipage}{0.65\textwidth}
  8797. \begin{lstlisting}
  8798. (any-vector-ref |$e_1'$| |$e_2'$|)
  8799. \end{lstlisting}
  8800. \end{minipage}
  8801. \\[2ex]\hline
  8802. \begin{minipage}{0.27\textwidth}
  8803. \begin{lstlisting}
  8804. (if |$e_1$| |$e_2$| |$e_3$|)
  8805. \end{lstlisting}
  8806. \end{minipage}
  8807. &
  8808. $\Rightarrow$
  8809. &
  8810. \begin{minipage}{0.65\textwidth}
  8811. \begin{lstlisting}
  8812. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  8813. \end{lstlisting}
  8814. \end{minipage}
  8815. \\[2ex]\hline
  8816. \begin{minipage}{0.27\textwidth}
  8817. \begin{lstlisting}
  8818. (eq? |$e_1$| |$e_2$|)
  8819. \end{lstlisting}
  8820. \end{minipage}
  8821. &
  8822. $\Rightarrow$
  8823. &
  8824. \begin{minipage}{0.65\textwidth}
  8825. \begin{lstlisting}
  8826. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8827. \end{lstlisting}
  8828. \end{minipage}
  8829. \\[2ex]\hline
  8830. \begin{minipage}{0.27\textwidth}
  8831. \begin{lstlisting}
  8832. (not |$e_1$|)
  8833. \end{lstlisting}
  8834. \end{minipage}
  8835. &
  8836. $\Rightarrow$
  8837. &
  8838. \begin{minipage}{0.65\textwidth}
  8839. \begin{lstlisting}
  8840. (if (eq? |$e'_1$| (inject #f Boolean))
  8841. (inject #t Boolean) (inject #f Boolean))
  8842. \end{lstlisting}
  8843. \end{minipage}
  8844. \\[2ex]\hline
  8845. \end{tabular}
  8846. \caption{Cast Insertion}
  8847. \label{fig:compile-r7-r6}
  8848. \end{figure}
  8849. \section{Reveal Casts}
  8850. \label{sec:reveal-casts-r6}
  8851. % TODO: define R'_6
  8852. In the \code{reveal-casts} pass we recommend compiling \code{project}
  8853. into an \code{if} expression that checks whether the value's tag
  8854. matches the target type; if it does, the value is converted to a value
  8855. of the target type by removing the tag; if it does not, the program
  8856. exits. To perform these actions we need a new primitive operation,
  8857. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  8858. The \code{tag-of-any} operation retrieves the type tag from a tagged
  8859. value of type \code{Any}. The \code{ValueOf} form retrieves the
  8860. underlying value from a tagged value. The \code{ValueOf} form
  8861. includes the type for the underlying value which is used by the type
  8862. checker. Finally, the \code{Exit} form ends the execution of the
  8863. program.
  8864. If the target type of the projection is \code{Boolean} or
  8865. \code{Integer}, then \code{Project} can be translated as follows.
  8866. \begin{center}
  8867. \begin{minipage}{1.0\textwidth}
  8868. \begin{lstlisting}
  8869. (Project |$e$| |$\FType$|)
  8870. |$\Rightarrow$|
  8871. (Let |$\itm{tmp}$| |$e'$|
  8872. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8873. (Int |$\itm{tagof}(\FType)$|)))
  8874. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8875. (Exit)))
  8876. \end{lstlisting}
  8877. \end{minipage}
  8878. \end{center}
  8879. If the target type of the projection is a vector or function type,
  8880. then there is a bit more work to do. For vectors, check that the
  8881. length of the vector type matches the length of the vector (using the
  8882. \code{vector-length} primitive). For functions, check that the number
  8883. of parameters in the function type matches the function's arity (using
  8884. \code{procedure-arity}).
  8885. Regarding \code{inject}, we recommend compiling it to a slightly
  8886. lower-level primitive operation named \code{make-any}. This operation
  8887. takes a tag instead of a type.
  8888. \begin{center}
  8889. \begin{minipage}{1.0\textwidth}
  8890. \begin{lstlisting}
  8891. (Inject |$e$| |$\FType$|)
  8892. |$\Rightarrow$|
  8893. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8894. \end{lstlisting}
  8895. \end{minipage}
  8896. \end{center}
  8897. The type predicates (\code{boolean?}, etc.) can be translated into
  8898. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  8899. translation of \code{Project}.
  8900. The \code{any-vector-ref} and \code{any-vector-set!} operations
  8901. combine the projection action with the vector operation. Also, the
  8902. read and write operations allow arbitrary expressions for the index so
  8903. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  8904. cannot guarantee that the index is within bounds. Thus, we insert code
  8905. to perform bounds checking at runtime. The translation for
  8906. \code{any-vector-ref} is as follows and the other two operations are
  8907. translated in a similar way.
  8908. \begin{lstlisting}
  8909. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  8910. |$\Rightarrow$|
  8911. (Let |$v$| |$e'_1$|
  8912. (Let |$i$| |$e'_2$|
  8913. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  8914. (If (Prim '< (list (Var |$i$|)
  8915. (Prim 'any-vector-length (list (Var |$v$|)))))
  8916. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  8917. (Exit))))
  8918. \end{lstlisting}
  8919. \section{Remove Complex Operands}
  8920. \label{sec:rco-r6}
  8921. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  8922. The subexpression of \code{ValueOf} must be atomic.
  8923. \section{Explicate Control and \LangCAny{}}
  8924. \label{sec:explicate-r6}
  8925. The output of \code{explicate-control} is the \LangCAny{} language whose
  8926. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  8927. form that we added to \LangAny{} remains an expression and the \code{Exit}
  8928. expression becomes a $\Tail$. Also, note that the index argument of
  8929. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  8930. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  8931. \begin{figure}[tp]
  8932. \fbox{
  8933. \begin{minipage}{0.96\textwidth}
  8934. \small
  8935. \[
  8936. \begin{array}{lcl}
  8937. \Exp &::= & \ldots
  8938. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  8939. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  8940. &\mid& \VALUEOF{\Exp}{\FType} \\
  8941. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8942. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  8943. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8944. \mid \GOTO{\itm{label}} } \\
  8945. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8946. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  8947. \mid \LP\key{Exit}\RP \\
  8948. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8949. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8950. \end{array}
  8951. \]
  8952. \end{minipage}
  8953. }
  8954. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  8955. \label{fig:c5-syntax}
  8956. \end{figure}
  8957. \section{Select Instructions}
  8958. \label{sec:select-r6}
  8959. In the \code{select-instructions} pass we translate the primitive
  8960. operations on the \code{Any} type to x86 instructions that involve
  8961. manipulating the 3 tag bits of the tagged value.
  8962. \paragraph{Make-any}
  8963. We recommend compiling the \key{make-any} primitive as follows if the
  8964. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  8965. shifts the destination to the left by the number of bits specified its
  8966. source argument (in this case $3$, the length of the tag) and it
  8967. preserves the sign of the integer. We use the \key{orq} instruction to
  8968. combine the tag and the value to form the tagged value. \\
  8969. \begin{lstlisting}
  8970. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  8971. |$\Rightarrow$|
  8972. movq |$e'$|, |\itm{lhs'}|
  8973. salq $3, |\itm{lhs'}|
  8974. orq $|$\itm{tag}$|, |\itm{lhs'}|
  8975. \end{lstlisting}
  8976. The instruction selection for vectors and procedures is different
  8977. because their is no need to shift them to the left. The rightmost 3
  8978. bits are already zeros as described at the beginning of this
  8979. chapter. So we just combine the value and the tag using \key{orq}. \\
  8980. \begin{lstlisting}
  8981. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  8982. |$\Rightarrow$|
  8983. movq |$e'$|, |\itm{lhs'}|
  8984. orq $|$\itm{tag}$|, |\itm{lhs'}|
  8985. \end{lstlisting}
  8986. \paragraph{Tag-of-any}
  8987. Recall that the \code{tag-of-any} operation extracts the type tag from
  8988. a value of type \code{Any}. The type tag is the bottom three bits, so
  8989. we obtain the tag by taking the bitwise-and of the value with $111$
  8990. ($7$ in decimal).
  8991. \begin{lstlisting}
  8992. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  8993. |$\Rightarrow$|
  8994. movq |$e'$|, |\itm{lhs'}|
  8995. andq $7, |\itm{lhs'}|
  8996. \end{lstlisting}
  8997. \paragraph{ValueOf}
  8998. Like \key{make-any}, the instructions for \key{ValueOf} are different
  8999. depending on whether the type $T$ is a pointer (vector or procedure)
  9000. or not (Integer or Boolean). The following shows the instruction
  9001. selection for Integer and Boolean. We produce an untagged value by
  9002. shifting it to the right by 3 bits.
  9003. \begin{lstlisting}
  9004. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9005. |$\Rightarrow$|
  9006. movq |$e'$|, |\itm{lhs'}|
  9007. sarq $3, |\itm{lhs'}|
  9008. \end{lstlisting}
  9009. %
  9010. In the case for vectors and procedures, there is no need to
  9011. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9012. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9013. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9014. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9015. then apply \code{andq} with the tagged value to get the desired
  9016. result. \\
  9017. \begin{lstlisting}
  9018. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9019. |$\Rightarrow$|
  9020. movq $|$-8$|, |\itm{lhs'}|
  9021. andq |$e'$|, |\itm{lhs'}|
  9022. \end{lstlisting}
  9023. %% \paragraph{Type Predicates} We leave it to the reader to
  9024. %% devise a sequence of instructions to implement the type predicates
  9025. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9026. \paragraph{Any-vector-length}
  9027. \begin{lstlisting}
  9028. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9029. |$\Longrightarrow$|
  9030. movq |$\neg 111$|, %r11
  9031. andq |$a_1'$|, %r11
  9032. movq 0(%r11), %r11
  9033. andq $126, %r11
  9034. sarq $1, %r11
  9035. movq %r11, |$\itm{lhs'}$|
  9036. \end{lstlisting}
  9037. \paragraph{Any-vector-ref}
  9038. The index may be an arbitrary atom so instead of computing the offset
  9039. at compile time, instructions need to be generated to compute the
  9040. offset at runtime as follows. Note the use of the new instruction
  9041. \code{imulq}.
  9042. \begin{center}
  9043. \begin{minipage}{0.96\textwidth}
  9044. \begin{lstlisting}
  9045. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9046. |$\Longrightarrow$|
  9047. movq |$\neg 111$|, %r11
  9048. andq |$a_1'$|, %r11
  9049. movq |$a_2'$|, %rax
  9050. addq $1, %rax
  9051. imulq $8, %rax
  9052. addq %rax, %r11
  9053. movq 0(%r11) |$\itm{lhs'}$|
  9054. \end{lstlisting}
  9055. \end{minipage}
  9056. \end{center}
  9057. \paragraph{Any-vector-set!}
  9058. The code generation for \code{any-vector-set!} is similar to the other
  9059. \code{any-vector} operations.
  9060. \section{Register Allocation for \LangAny{}}
  9061. \label{sec:register-allocation-r6}
  9062. \index{register allocation}
  9063. There is an interesting interaction between tagged values and garbage
  9064. collection that has an impact on register allocation. A variable of
  9065. type \code{Any} might refer to a vector and therefore it might be a
  9066. root that needs to be inspected and copied during garbage
  9067. collection. Thus, we need to treat variables of type \code{Any} in a
  9068. similar way to variables of type \code{Vector} for purposes of
  9069. register allocation. In particular,
  9070. \begin{itemize}
  9071. \item If a variable of type \code{Any} is live during a function call,
  9072. then it must be spilled. This can be accomplished by changing
  9073. \code{build-interference} to mark all variables of type \code{Any}
  9074. that are live after a \code{callq} as interfering with all the
  9075. registers.
  9076. \item If a variable of type \code{Any} is spilled, it must be spilled
  9077. to the root stack instead of the normal procedure call stack.
  9078. \end{itemize}
  9079. Another concern regarding the root stack is that the garbage collector
  9080. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9081. tagged value that points to a tuple, and (3) a tagged value that is
  9082. not a tuple. We enable this differentiation by choosing not to use the
  9083. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9084. reserved for identifying plain old pointers to tuples. That way, if
  9085. one of the first three bits is set, then we have a tagged value and
  9086. inspecting the tag can differentiation between vectors ($010$) and the
  9087. other kinds of values.
  9088. \begin{exercise}\normalfont
  9089. Expand your compiler to handle \LangAny{} as discussed in the last few
  9090. sections. Create 5 new programs that use the \code{Any} type and the
  9091. new operations (\code{inject}, \code{project}, \code{boolean?},
  9092. etc.). Test your compiler on these new programs and all of your
  9093. previously created test programs.
  9094. \end{exercise}
  9095. \begin{exercise}\normalfont
  9096. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9097. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9098. by removing type annotations. Add 5 more tests programs that
  9099. specifically rely on the language being dynamically typed. That is,
  9100. they should not be legal programs in a statically typed language, but
  9101. nevertheless, they should be valid \LangDyn{} programs that run to
  9102. completion without error.
  9103. \end{exercise}
  9104. \begin{figure}[p]
  9105. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9106. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9107. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9108. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9109. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9110. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9111. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9112. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9113. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9114. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9115. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9116. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9117. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9118. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9119. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9120. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9121. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9122. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9123. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9124. \path[->,bend left=15] (Rfun) edge [above] node
  9125. {\ttfamily\footnotesize shrink} (Rfun-2);
  9126. \path[->,bend left=15] (Rfun-2) edge [above] node
  9127. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9128. \path[->,bend left=15] (Rfun-3) edge [above] node
  9129. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9130. \path[->,bend right=15] (Rfun-4) edge [left] node
  9131. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9132. \path[->,bend left=15] (Rfun-5) edge [above] node
  9133. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9134. \path[->,bend left=15] (Rfun-6) edge [left] node
  9135. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9136. \path[->,bend left=15] (Rfun-7) edge [below] node
  9137. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9138. \path[->,bend right=15] (F1-2) edge [above] node
  9139. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9140. \path[->,bend right=15] (F1-3) edge [above] node
  9141. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9142. \path[->,bend right=15] (F1-4) edge [above] node
  9143. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9144. \path[->,bend right=15] (F1-5) edge [right] node
  9145. {\ttfamily\footnotesize explicate-control} (C3-2);
  9146. \path[->,bend left=15] (C3-2) edge [left] node
  9147. {\ttfamily\footnotesize select-instr.} (x86-2);
  9148. \path[->,bend right=15] (x86-2) edge [left] node
  9149. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9150. \path[->,bend right=15] (x86-2-1) edge [below] node
  9151. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9152. \path[->,bend right=15] (x86-2-2) edge [left] node
  9153. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9154. \path[->,bend left=15] (x86-3) edge [above] node
  9155. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9156. \path[->,bend left=15] (x86-4) edge [right] node
  9157. {\ttfamily\footnotesize print-x86} (x86-5);
  9158. \end{tikzpicture}
  9159. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9160. \label{fig:Rdyn-passes}
  9161. \end{figure}
  9162. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9163. for the compilation of \LangDyn{}.
  9164. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9165. \chapter{Loops and Assignment}
  9166. \label{ch:loop}
  9167. % TODO: define R'_8
  9168. % TODO: multi-graph
  9169. In this chapter we study two features that are the hallmarks of
  9170. imperative programming languages: loops and assignments to local
  9171. variables. The following example demonstrates these new features by
  9172. computing the sum of the first five positive integers.
  9173. % similar to loop_test_1.rkt
  9174. \begin{lstlisting}
  9175. (let ([sum 0])
  9176. (let ([i 5])
  9177. (begin
  9178. (while (> i 0)
  9179. (begin
  9180. (set! sum (+ sum i))
  9181. (set! i (- i 1))))
  9182. sum)))
  9183. \end{lstlisting}
  9184. The \code{while} loop consists of a condition and a body.
  9185. %
  9186. The \code{set!} consists of a variable and a right-hand-side expression.
  9187. %
  9188. The primary purpose of both the \code{while} loop and \code{set!} is
  9189. to cause side effects, so it is convenient to also include in a
  9190. language feature for sequencing side effects: the \code{begin}
  9191. expression. It consists of one or more subexpressions that are
  9192. evaluated left-to-right.
  9193. \section{The \LangLoop{} Language}
  9194. \begin{figure}[tp]
  9195. \centering
  9196. \fbox{
  9197. \begin{minipage}{0.96\textwidth}
  9198. \small
  9199. \[
  9200. \begin{array}{lcl}
  9201. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9202. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9203. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9204. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9205. \mid (\key{and}\;\Exp\;\Exp)
  9206. \mid (\key{or}\;\Exp\;\Exp)
  9207. \mid (\key{not}\;\Exp) } \\
  9208. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9209. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9210. (\key{vector-ref}\;\Exp\;\Int)} \\
  9211. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9212. \mid (\Exp \; \Exp\ldots) } \\
  9213. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9214. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9215. &\mid& \CSETBANG{\Var}{\Exp}
  9216. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9217. \mid \CWHILE{\Exp}{\Exp} \\
  9218. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9219. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9220. \end{array}
  9221. \]
  9222. \end{minipage}
  9223. }
  9224. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-concrete-syntax}).}
  9225. \label{fig:r8-concrete-syntax}
  9226. \end{figure}
  9227. \begin{figure}[tp]
  9228. \centering
  9229. \fbox{
  9230. \begin{minipage}{0.96\textwidth}
  9231. \small
  9232. \[
  9233. \begin{array}{lcl}
  9234. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9235. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9236. &\mid& \gray{ \BOOL{\itm{bool}}
  9237. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9238. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9239. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9240. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9241. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9242. \mid \WHILE{\Exp}{\Exp} \\
  9243. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9244. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9245. \end{array}
  9246. \]
  9247. \end{minipage}
  9248. }
  9249. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-syntax}).}
  9250. \label{fig:r8-syntax}
  9251. \end{figure}
  9252. The concrete syntax of \LangLoop{} is defined in
  9253. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  9254. in Figure~\ref{fig:r8-syntax}.
  9255. %
  9256. The definitional interpreter for \LangLoop{} is shown in
  9257. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9258. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9259. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9260. support assignment to variables and to make their lifetimes indefinite
  9261. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9262. box the value that is bound to each variable (in \code{Let}) and
  9263. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9264. the value.
  9265. %
  9266. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9267. variable in the environment to obtain a boxed value and then we change
  9268. it using \code{set-box!} to the result of evaluating the right-hand
  9269. side. The result value of a \code{SetBang} is \code{void}.
  9270. %
  9271. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9272. if the result is true, 2) evaluate the body.
  9273. The result value of a \code{while} loop is also \code{void}.
  9274. %
  9275. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9276. subexpressions \itm{es} for their effects and then evaluates
  9277. and returns the result from \itm{body}.
  9278. \begin{figure}[tbp]
  9279. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9280. (define interp-Rwhile-class
  9281. (class interp-Rany-class
  9282. (super-new)
  9283. (define/override ((interp-exp env) e)
  9284. (define recur (interp-exp env))
  9285. (match e
  9286. [(SetBang x rhs)
  9287. (set-box! (lookup x env) (recur rhs))]
  9288. [(WhileLoop cnd body)
  9289. (define (loop)
  9290. (cond [(recur cnd) (recur body) (loop)]
  9291. [else (void)]))
  9292. (loop)]
  9293. [(Begin es body)
  9294. (for ([e es]) (recur e))
  9295. (recur body)]
  9296. [else ((super interp-exp env) e)]))
  9297. ))
  9298. (define (interp-Rwhile p)
  9299. (send (new interp-Rwhile-class) interp-program p))
  9300. \end{lstlisting}
  9301. \caption{Interpreter for \LangLoop{}.}
  9302. \label{fig:interp-Rwhile}
  9303. \end{figure}
  9304. The type checker for \LangLoop{} is define in
  9305. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9306. variable and the right-hand-side must agree. The result type is
  9307. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9308. \code{Boolean}. The result type is also \code{Void}. For
  9309. \code{Begin}, the result type is the type of its last subexpression.
  9310. \begin{figure}[tbp]
  9311. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9312. (define type-check-Rwhile-class
  9313. (class type-check-Rany-class
  9314. (super-new)
  9315. (inherit check-type-equal?)
  9316. (define/override (type-check-exp env)
  9317. (lambda (e)
  9318. (define recur (type-check-exp env))
  9319. (match e
  9320. [(SetBang x rhs)
  9321. (define-values (rhs^ rhsT) (recur rhs))
  9322. (define varT (dict-ref env x))
  9323. (check-type-equal? rhsT varT e)
  9324. (values (SetBang x rhs^) 'Void)]
  9325. [(WhileLoop cnd body)
  9326. (define-values (cnd^ Tc) (recur cnd))
  9327. (check-type-equal? Tc 'Boolean e)
  9328. (define-values (body^ Tbody) ((type-check-exp env) body))
  9329. (values (WhileLoop cnd^ body^) 'Void)]
  9330. [(Begin es body)
  9331. (define-values (es^ ts)
  9332. (for/lists (l1 l2) ([e es]) (recur e)))
  9333. (define-values (body^ Tbody) (recur body))
  9334. (values (Begin es^ body^) Tbody)]
  9335. [else ((super type-check-exp env) e)])))
  9336. ))
  9337. (define (type-check-Rwhile p)
  9338. (send (new type-check-Rwhile-class) type-check-program p))
  9339. \end{lstlisting}
  9340. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9341. and \code{Begin} in \LangLoop{}.}
  9342. \label{fig:type-check-Rwhile}
  9343. \end{figure}
  9344. At first glance, the translation of these language features to x86
  9345. seems straightforward because the \LangCFun{} intermediate language already
  9346. supports all of the ingredients that we need: assignment, \code{goto},
  9347. conditional branching, and sequencing. However, there are two
  9348. complications that arise which we discuss in the next two
  9349. sections. After that we introduce one new compiler pass and the
  9350. changes necessary to the existing passes.
  9351. \section{Assignment and Lexically Scoped Functions}
  9352. \label{sec:assignment-scoping}
  9353. The addition of assignment raises a problem with our approach to
  9354. implementing lexically-scoped functions. Consider the following
  9355. example in which function \code{f} has a free variable \code{x} that
  9356. is changed after \code{f} is created but before the call to \code{f}.
  9357. % loop_test_11.rkt
  9358. \begin{lstlisting}
  9359. (let ([x 0])
  9360. (let ([y 0])
  9361. (let ([z 20])
  9362. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9363. (begin
  9364. (set! x 10)
  9365. (set! y 12)
  9366. (f y))))))
  9367. \end{lstlisting}
  9368. The correct output for this example is \code{42} because the call to
  9369. \code{f} is required to use the current value of \code{x} (which is
  9370. \code{10}). Unfortunately, the closure conversion pass
  9371. (Section~\ref{sec:closure-conversion}) generates code for the
  9372. \code{lambda} that copies the old value of \code{x} into a
  9373. closure. Thus, if we naively add support for assignment to our current
  9374. compiler, the output of this program would be \code{32}.
  9375. A first attempt at solving this problem would be to save a pointer to
  9376. \code{x} in the closure and change the occurrences of \code{x} inside
  9377. the lambda to dereference the pointer. Of course, this would require
  9378. assigning \code{x} to the stack and not to a register. However, the
  9379. problem goes a bit deeper. Consider the following example in which we
  9380. create a counter abstraction by creating a pair of functions that
  9381. share the free variable \code{x}.
  9382. % similar to loop_test_10.rkt
  9383. \begin{lstlisting}
  9384. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9385. (vector
  9386. (lambda: () : Integer x)
  9387. (lambda: () : Void (set! x (+ 1 x)))))
  9388. (let ([counter (f 0)])
  9389. (let ([get (vector-ref counter 0)])
  9390. (let ([inc (vector-ref counter 1)])
  9391. (begin
  9392. (inc)
  9393. (get)))))
  9394. \end{lstlisting}
  9395. In this example, the lifetime of \code{x} extends beyond the lifetime
  9396. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9397. stack frame for the call to \code{f}, it would be gone by the time we
  9398. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9399. \code{x}. This example demonstrates that when a variable occurs free
  9400. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9401. value of the variable needs to live on the heap. The verb ``box'' is
  9402. often used for allocating a single value on the heap, producing a
  9403. pointer, and ``unbox'' for dereferencing the pointer.
  9404. We recommend solving these problems by ``boxing'' the local variables
  9405. that are in the intersection of 1) variables that appear on the
  9406. left-hand-side of a \code{set!} and 2) variables that occur free
  9407. inside a \code{lambda}. We shall introduce a new pass named
  9408. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9409. perform this translation. But before diving into the compiler passes,
  9410. we one more problem to discuss.
  9411. \section{Cyclic Control Flow and Dataflow Analysis}
  9412. \label{sec:dataflow-analysis}
  9413. Up until this point the control-flow graphs generated in
  9414. \code{explicate-control} were guaranteed to be acyclic. However, each
  9415. \code{while} loop introduces a cycle in the control-flow graph.
  9416. But does that matter?
  9417. %
  9418. Indeed it does. Recall that for register allocation, the compiler
  9419. performs liveness analysis to determine which variables can share the
  9420. same register. In Section~\ref{sec:liveness-analysis-r2} we analyze
  9421. the control-flow graph in reverse topological order, but topological
  9422. order is only well-defined for acyclic graphs.
  9423. Let us return to the example of computing the sum of the first five
  9424. positive integers. Here is the program after instruction selection but
  9425. before register allocation.
  9426. \begin{center}
  9427. \begin{minipage}{0.45\textwidth}
  9428. \begin{lstlisting}
  9429. (define (main) : Integer
  9430. mainstart:
  9431. movq $0, sum1
  9432. movq $5, i2
  9433. jmp block5
  9434. block5:
  9435. movq i2, tmp3
  9436. cmpq tmp3, $0
  9437. jl block7
  9438. jmp block8
  9439. \end{lstlisting}
  9440. \end{minipage}
  9441. \begin{minipage}{0.45\textwidth}
  9442. \begin{lstlisting}
  9443. block7:
  9444. addq i2, sum1
  9445. movq $1, tmp4
  9446. negq tmp4
  9447. addq tmp4, i2
  9448. jmp block5
  9449. block8:
  9450. movq $27, %rax
  9451. addq sum1, %rax
  9452. jmp mainconclusion
  9453. )
  9454. \end{lstlisting}
  9455. \end{minipage}
  9456. \end{center}
  9457. Recall that liveness analysis works backwards, starting at the end
  9458. of each function. For this example we could start with \code{block8}
  9459. because we know what is live at the beginning of the conclusion,
  9460. just \code{rax} and \code{rsp}. So the live-before set
  9461. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9462. %
  9463. Next we might try to analyze \code{block5} or \code{block7}, but
  9464. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9465. we are stuck.
  9466. The way out of this impasse comes from the realization that one can
  9467. perform liveness analysis starting with an empty live-after set to
  9468. compute an under-approximation of the live-before set. By
  9469. \emph{under-approximation}, we mean that the set only contains
  9470. variables that are really live, but it may be missing some. Next, the
  9471. under-approximations for each block can be improved by 1) updating the
  9472. live-after set for each block using the approximate live-before sets
  9473. from the other blocks and 2) perform liveness analysis again on each
  9474. block. In fact, by iterating this process, the under-approximations
  9475. eventually become the correct solutions!
  9476. %
  9477. This approach of iteratively analyzing a control-flow graph is
  9478. applicable to many static analysis problems and goes by the name
  9479. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9480. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9481. Washington.
  9482. Let us apply this approach to the above example. We use the empty set
  9483. for the initial live-before set for each block. Let $m_0$ be the
  9484. following mapping from label names to sets of locations (variables and
  9485. registers).
  9486. \begin{center}
  9487. \begin{lstlisting}
  9488. mainstart: {}
  9489. block5: {}
  9490. block7: {}
  9491. block8: {}
  9492. \end{lstlisting}
  9493. \end{center}
  9494. Using the above live-before approximations, we determine the
  9495. live-after for each block and then apply liveness analysis to each
  9496. block. This produces our next approximation $m_1$ of the live-before
  9497. sets.
  9498. \begin{center}
  9499. \begin{lstlisting}
  9500. mainstart: {}
  9501. block5: {i2}
  9502. block7: {i2, sum1}
  9503. block8: {rsp, sum1}
  9504. \end{lstlisting}
  9505. \end{center}
  9506. For the second round, the live-after for \code{mainstart} is the
  9507. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9508. liveness analysis for \code{mainstart} computes the empty set. The
  9509. live-after for \code{block5} is the union of the live-before sets for
  9510. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9511. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9512. sum1\}}. The live-after for \code{block7} is the live-before for
  9513. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9514. So the liveness analysis for \code{block7} remains \code{\{i2,
  9515. sum1\}}. Together these yield the following approximation $m_2$ of
  9516. the live-before sets.
  9517. \begin{center}
  9518. \begin{lstlisting}
  9519. mainstart: {}
  9520. block5: {i2, rsp, sum1}
  9521. block7: {i2, sum1}
  9522. block8: {rsp, sum1}
  9523. \end{lstlisting}
  9524. \end{center}
  9525. In the preceding iteration, only \code{block5} changed, so we can
  9526. limit our attention to \code{mainstart} and \code{block7}, the two
  9527. blocks that jump to \code{block5}. As a result, the live-before sets
  9528. for \code{mainstart} and \code{block7} are updated to include
  9529. \code{rsp}, yielding the following approximation $m_3$.
  9530. \begin{center}
  9531. \begin{lstlisting}
  9532. mainstart: {rsp}
  9533. block5: {i2, rsp, sum1}
  9534. block7: {i2, rsp, sum1}
  9535. block8: {rsp, sum1}
  9536. \end{lstlisting}
  9537. \end{center}
  9538. Because \code{block7} changed, we analyze \code{block5} once more, but
  9539. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9540. our approximations have converged, so $m_3$ is the solution.
  9541. This iteration process is guaranteed to converge to a solution by the
  9542. Kleene Fixed-Point Theorem, a general theorem about functions on
  9543. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9544. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9545. elements, a least element $\bot$ (pronounced bottom), and a join
  9546. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9547. ordering}\index{join}\footnote{Technically speaking, we will be
  9548. working with join semi-lattices.} When two elements are ordered $m_i
  9549. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9550. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9551. approximation than $m_i$. The bottom element $\bot$ represents the
  9552. complete lack of information, i.e., the worst approximation. The join
  9553. operator takes two lattice elements and combines their information,
  9554. i.e., it produces the least upper bound of the two.\index{least upper
  9555. bound}
  9556. A dataflow analysis typically involves two lattices: one lattice to
  9557. represent abstract states and another lattice that aggregates the
  9558. abstract states of all the blocks in the control-flow graph. For
  9559. liveness analysis, an abstract state is a set of locations. We form
  9560. the lattice $L$ by taking its elements to be sets of locations, the
  9561. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9562. set, and the join operator to be set union.
  9563. %
  9564. We form a second lattice $M$ by taking its elements to be mappings
  9565. from the block labels to sets of locations (elements of $L$). We
  9566. order the mappings point-wise, using the ordering of $L$. So given any
  9567. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9568. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9569. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9570. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9571. We can think of one iteration of liveness analysis as being a function
  9572. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9573. mapping.
  9574. \[
  9575. f(m_i) = m_{i+1}
  9576. \]
  9577. Next let us think for a moment about what a final solution $m_s$
  9578. should look like. If we perform liveness analysis using the solution
  9579. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9580. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9581. \[
  9582. f(m_s) = m_s
  9583. \]
  9584. Furthermore, the solution should only include locations that are
  9585. forced to be there by performing liveness analysis on the program, so
  9586. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9587. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9588. monotone (better inputs produce better outputs), then the least fixed
  9589. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9590. chain} obtained by starting at $\bot$ and iterating $f$ as
  9591. follows.\index{Kleene Fixed-Point Theorem}
  9592. \[
  9593. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9594. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9595. \]
  9596. When a lattice contains only finitely-long ascending chains, then
  9597. every Kleene chain tops out at some fixed point after a number of
  9598. iterations of $f$. So that fixed point is also a least upper
  9599. bound of the chain.
  9600. \[
  9601. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9602. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9603. \]
  9604. The liveness analysis is indeed a monotone function and the lattice
  9605. $M$ only has finitely-long ascending chains because there are only a
  9606. finite number of variables and blocks in the program. Thus we are
  9607. guaranteed that iteratively applying liveness analysis to all blocks
  9608. in the program will eventually produce the least fixed point solution.
  9609. Next let us consider dataflow analysis in general and discuss the
  9610. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9611. %
  9612. The algorithm has four parameters: the control-flow graph \code{G}, a
  9613. function \code{transfer} that applies the analysis to one block, the
  9614. \code{bottom} and \code{join} operator for the lattice of abstract
  9615. states. The algorithm begins by creating the bottom mapping,
  9616. represented by a hash table. It then pushes all of the nodes in the
  9617. control-flow graph onto the work list (a queue). The algorithm repeats
  9618. the \code{while} loop as long as there are items in the work list. In
  9619. each iteration, a node is popped from the work list and processed. The
  9620. \code{input} for the node is computed by taking the join of the
  9621. abstract states of all the predecessor nodes. The \code{transfer}
  9622. function is then applied to obtain the \code{output} abstract
  9623. state. If the output differs from the previous state for this block,
  9624. the mapping for this block is updated and its successor nodes are
  9625. pushed onto the work list.
  9626. \begin{figure}[tb]
  9627. \begin{lstlisting}
  9628. (define (analyze-dataflow G transfer bottom join)
  9629. (define mapping (make-hash))
  9630. (for ([v (in-vertices G)])
  9631. (dict-set! mapping v bottom))
  9632. (define worklist (make-queue))
  9633. (for ([v (in-vertices G)])
  9634. (enqueue! worklist v))
  9635. (define trans-G (transpose G))
  9636. (while (not (queue-empty? worklist))
  9637. (define node (dequeue! worklist))
  9638. (define input (for/fold ([state bottom])
  9639. ([pred (in-neighbors trans-G node)])
  9640. (join state (dict-ref mapping pred))))
  9641. (define output (transfer node input))
  9642. (cond [(not (equal? output (dict-ref mapping node)))
  9643. (dict-set! mapping node output)
  9644. (for ([v (in-neighbors G node)])
  9645. (enqueue! worklist v))]))
  9646. mapping)
  9647. \end{lstlisting}
  9648. \caption{Generic work list algorithm for dataflow analysis}
  9649. \label{fig:generic-dataflow}
  9650. \end{figure}
  9651. Having discussed the two complications that arise from adding support
  9652. for assignment and loops, we turn to discussing the one new compiler
  9653. pass and the significant changes to existing passes.
  9654. \section{Convert Assignments}
  9655. \label{sec:convert-assignments}
  9656. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9657. the combination of assignments and lexically-scoped functions requires
  9658. that we box those variables that are both assigned-to and that appear
  9659. free inside a \code{lambda}. The purpose of the
  9660. \code{convert-assignments} pass is to carry out that transformation.
  9661. We recommend placing this pass after \code{uniquify} but before
  9662. \code{reveal-functions}.
  9663. Consider again the first example from
  9664. Section~\ref{sec:assignment-scoping}:
  9665. \begin{lstlisting}
  9666. (let ([x 0])
  9667. (let ([y 0])
  9668. (let ([z 20])
  9669. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9670. (begin
  9671. (set! x 10)
  9672. (set! y 12)
  9673. (f y))))))
  9674. \end{lstlisting}
  9675. The variables \code{x} and \code{y} are assigned-to. The variables
  9676. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9677. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9678. The boxing of \code{x} consists of three transformations: initialize
  9679. \code{x} with a vector, replace reads from \code{x} with
  9680. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9681. \code{vector-set!}. The output of \code{convert-assignments} for this
  9682. example is as follows.
  9683. \begin{lstlisting}
  9684. (define (main) : Integer
  9685. (let ([x0 (vector 0)])
  9686. (let ([y1 0])
  9687. (let ([z2 20])
  9688. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9689. (+ a3 (+ (vector-ref x0 0) z2)))])
  9690. (begin
  9691. (vector-set! x0 0 10)
  9692. (set! y1 12)
  9693. (f4 y1)))))))
  9694. \end{lstlisting}
  9695. \paragraph{Assigned \& Free}
  9696. We recommend defining an auxiliary function named
  9697. \code{assigned\&free} that takes an expression and simultaneously
  9698. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9699. that occur free within lambda's, and 3) a new version of the
  9700. expression that records which bound variables occurred in the
  9701. intersection of $A$ and $F$. You can use the struct
  9702. \code{AssignedFree} to do this. Consider the case for
  9703. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9704. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9705. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9706. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9707. \begin{lstlisting}
  9708. (Let |$x$| |$rhs$| |$body$|)
  9709. |$\Rightarrow$|
  9710. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  9711. \end{lstlisting}
  9712. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  9713. The set of assigned variables for this \code{Let} is
  9714. $A_r \cup (A_b - \{x\})$
  9715. and the set of variables free in lambda's is
  9716. $F_r \cup (F_b - \{x\})$.
  9717. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  9718. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  9719. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  9720. and $F_r$.
  9721. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  9722. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  9723. recursively processing \itm{body}. Wrap each of parameter that occurs
  9724. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  9725. Let $P$ be the set of parameter names in \itm{params}. The result is
  9726. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  9727. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  9728. variables of an expression (see Chapter~\ref{ch:lambdas}).
  9729. \paragraph{Convert Assignments}
  9730. Next we discuss the \code{convert-assignment} pass with its auxiliary
  9731. functions for expressions and definitions. The function for
  9732. expressions, \code{cnvt-assign-exp}, should take an expression and a
  9733. set of assigned-and-free variables (obtained from the result of
  9734. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  9735. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  9736. \code{vector-ref}.
  9737. \begin{lstlisting}
  9738. (Var |$x$|)
  9739. |$\Rightarrow$|
  9740. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  9741. \end{lstlisting}
  9742. %
  9743. In the case for $\LET{\LP\code{AssignedFree}\,
  9744. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  9745. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  9746. \itm{body'} but with $x$ added to the set of assigned-and-free
  9747. variables. Translate the let-expression as follows to bind $x$ to a
  9748. boxed value.
  9749. \begin{lstlisting}
  9750. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  9751. |$\Rightarrow$|
  9752. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  9753. \end{lstlisting}
  9754. %
  9755. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  9756. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  9757. variables, translate the \code{set!} into a \code{vector-set!}
  9758. as follows.
  9759. \begin{lstlisting}
  9760. (SetBang |$x$| |$\itm{rhs}$|)
  9761. |$\Rightarrow$|
  9762. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  9763. \end{lstlisting}
  9764. %
  9765. The case for \code{Lambda} is non-trivial, but it is similar to the
  9766. case for function definitions, which we discuss next.
  9767. The auxiliary function for definitions, \code{cnvt-assign-def},
  9768. applies assignment conversion to function definitions.
  9769. We translate a function definition as follows.
  9770. \begin{lstlisting}
  9771. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  9772. |$\Rightarrow$|
  9773. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  9774. \end{lstlisting}
  9775. So it remains to explain \itm{params'} and $\itm{body}_4$.
  9776. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  9777. \code{assigned\&free} on $\itm{body_1}$.
  9778. Let $P$ be the parameter names in \itm{params}.
  9779. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  9780. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  9781. as the set of assigned-and-free variables.
  9782. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  9783. in a sequence of let-expressions that box the parameters
  9784. that are in $A_b \cap F_b$.
  9785. %
  9786. Regarding \itm{params'}, change the names of the parameters that are
  9787. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  9788. variables can retain the original names). Recall the second example in
  9789. Section~\ref{sec:assignment-scoping} involving a counter
  9790. abstraction. The following is the output of assignment version for
  9791. function \code{f}.
  9792. \begin{lstlisting}
  9793. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  9794. (vector
  9795. (lambda: () : Integer x1)
  9796. (lambda: () : Void (set! x1 (+ 1 x1)))))
  9797. |$\Rightarrow$|
  9798. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  9799. (let ([x1 (vector param_x1)])
  9800. (vector (lambda: () : Integer (vector-ref x1 0))
  9801. (lambda: () : Void
  9802. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  9803. \end{lstlisting}
  9804. \section{Remove Complex Operands}
  9805. \label{sec:rco-loop}
  9806. The three new language forms, \code{while}, \code{set!}, and
  9807. \code{begin} are all complex expressions and their subexpressions are
  9808. allowed to be complex. Figure~\ref{fig:r4-anf-syntax} defines the
  9809. output language \LangFunANF{} of this pass.
  9810. \begin{figure}[tp]
  9811. \centering
  9812. \fbox{
  9813. \begin{minipage}{0.96\textwidth}
  9814. \small
  9815. \[
  9816. \begin{array}{rcl}
  9817. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  9818. \mid \VOID{} } \\
  9819. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9820. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  9821. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9822. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9823. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9824. \end{array}
  9825. \]
  9826. \end{minipage}
  9827. }
  9828. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  9829. \label{fig:r8-anf-syntax}
  9830. \end{figure}
  9831. As usual, when a complex expression appears in a grammar position that
  9832. needs to be atomic, such as the argument of a primitive operator, we
  9833. must introduce a temporary variable and bind it to the complex
  9834. expression. This approach applies, unchanged, to handle the new
  9835. language forms. For example, in the following code there are two
  9836. \code{begin} expressions appearing as arguments to \code{+}. The
  9837. output of \code{rco-exp} is shown below, in which the \code{begin}
  9838. expressions have been bound to temporary variables. Recall that
  9839. \code{let} expressions in \LangLoopANF{} are allowed to have
  9840. arbitrary expressions in their right-hand-side expression, so it is
  9841. fine to place \code{begin} there.
  9842. \begin{lstlisting}
  9843. (let ([x0 10])
  9844. (let ([y1 0])
  9845. (+ (+ (begin (set! y1 (read)) x0)
  9846. (begin (set! x0 (read)) y1))
  9847. x0)))
  9848. |$\Rightarrow$|
  9849. (let ([x0 10])
  9850. (let ([y1 0])
  9851. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9852. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9853. (let ([tmp4 (+ tmp2 tmp3)])
  9854. (+ tmp4 x0))))))
  9855. \end{lstlisting}
  9856. \section{Explicate Control and \LangCLoop{}}
  9857. \label{sec:explicate-loop}
  9858. Recall that in the \code{explicate-control} pass we define one helper
  9859. function for each kind of position in the program. For the \LangVar{}
  9860. language of integers and variables we needed kinds of positions:
  9861. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9862. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9863. yet another kind of position: effect position. Except for the last
  9864. subexpression, the subexpressions inside a \code{begin} are evaluated
  9865. only for their effect. Their result values are discarded. We can
  9866. generate better code by taking this fact into account.
  9867. The output language of \code{explicate-control} is \LangCLoop{}
  9868. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9869. \LangCLam{}. The only syntactic difference is that \code{Call},
  9870. \code{vector-set!}, and \code{read} may also appear as statements.
  9871. The most significant difference between \LangCLam{} and \LangCLoop{}
  9872. is that the control-flow graphs of the later may contain cycles.
  9873. \begin{figure}[tp]
  9874. \fbox{
  9875. \begin{minipage}{0.96\textwidth}
  9876. \small
  9877. \[
  9878. \begin{array}{lcl}
  9879. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9880. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  9881. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  9882. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9883. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9884. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9885. \end{array}
  9886. \]
  9887. \end{minipage}
  9888. }
  9889. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9890. \label{fig:c7-syntax}
  9891. \end{figure}
  9892. The new auxiliary function \code{explicate-effect} takes an expression
  9893. (in an effect position) and a promise of a continuation block. The
  9894. function returns a promise for a $\Tail$ that includes the generated
  9895. code for the input expression followed by the continuation block. If
  9896. the expression is obviously pure, that is, never causes side effects,
  9897. then the expression can be removed, so the result is just the
  9898. continuation block.
  9899. %
  9900. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9901. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9902. the loop. Recursively process the \itm{body} (in effect position)
  9903. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9904. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9905. \itm{body'} as the then-branch and the continuation block as the
  9906. else-branch. The result should be added to the control-flow graph with
  9907. the label \itm{loop}. The result for the whole \code{while} loop is a
  9908. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9909. added to the control-flow graph if the loop is indeed used, which can
  9910. be accomplished using \code{delay}.
  9911. The auxiliary functions for tail, assignment, and predicate positions
  9912. need to be updated. The three new language forms, \code{while},
  9913. \code{set!}, and \code{begin}, can appear in assignment and tail
  9914. positions. Only \code{begin} may appear in predicate positions; the
  9915. other two have result type \code{Void}.
  9916. \section{Select Instructions}
  9917. \label{sec:select-instructions-loop}
  9918. Only three small additions are needed in the
  9919. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  9920. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9921. stand-alone statements instead of only appearing on the right-hand
  9922. side of an assignment statement. The code generation is nearly
  9923. identical; just leave off the instruction for moving the result into
  9924. the left-hand side.
  9925. \section{Register Allocation}
  9926. \label{sec:register-allocation-loop}
  9927. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9928. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9929. which complicates the liveness analysis needed for register
  9930. allocation.
  9931. \subsection{Liveness Analysis}
  9932. \label{sec:liveness-analysis-r8}
  9933. We recommend using the generic \code{analyze-dataflow} function that
  9934. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9935. perform liveness analysis, replacing the code in
  9936. \code{uncover-live-CFG} that processed the basic blocks in topological
  9937. order (Section~\ref{sec:liveness-analysis-r2}).
  9938. The \code{analyze-dataflow} function has four parameters.
  9939. \begin{enumerate}
  9940. \item The first parameter \code{G} should be a directed graph from the
  9941. \code{racket/graph} package (see the sidebar in
  9942. Section~\ref{sec:build-interference}) that represents the
  9943. control-flow graph.
  9944. \item The second parameter \code{transfer} is a function that applies
  9945. liveness analysis to a basic block. It takes two parameters: the
  9946. label for the block to analyze and the live-after set for that
  9947. block. The transfer function should return the live-before set for
  9948. the block. Also, as a side-effect, it should update the block's
  9949. $\itm{info}$ with the liveness information for each instruction. To
  9950. implement the \code{transfer} function, you should be able to reuse
  9951. the code you already have for analyzing basic blocks.
  9952. \item The third and fourth parameters of \code{analyze-dataflow} are
  9953. \code{bottom} and \code{join} for the lattice of abstract states,
  9954. i.e. sets of locations. The bottom of the lattice is the empty set
  9955. \code{(set)} and the join operator is \code{set-union}.
  9956. \end{enumerate}
  9957. \begin{figure}[p]
  9958. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9959. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9960. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9961. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9962. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9963. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9964. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9965. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9966. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  9967. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  9968. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  9969. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9970. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9971. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9972. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9973. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9974. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9975. %% \path[->,bend left=15] (Rfun) edge [above] node
  9976. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9977. \path[->,bend left=15] (Rfun) edge [above] node
  9978. {\ttfamily\footnotesize shrink} (Rfun-2);
  9979. \path[->,bend left=15] (Rfun-2) edge [above] node
  9980. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9981. \path[->,bend left=15] (Rfun-3) edge [above] node
  9982. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9983. \path[->,bend left=15] (Rfun-4) edge [right] node
  9984. {\ttfamily\footnotesize convert-assignments} (F1-1);
  9985. \path[->,bend left=15] (F1-1) edge [below] node
  9986. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9987. \path[->,bend right=15] (F1-2) edge [above] node
  9988. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9989. \path[->,bend right=15] (F1-3) edge [above] node
  9990. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9991. \path[->,bend right=15] (F1-4) edge [above] node
  9992. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9993. \path[->,bend right=15] (F1-5) edge [right] node
  9994. {\ttfamily\footnotesize explicate-control} (C3-2);
  9995. \path[->,bend left=15] (C3-2) edge [left] node
  9996. {\ttfamily\footnotesize select-instr.} (x86-2);
  9997. \path[->,bend right=15] (x86-2) edge [left] node
  9998. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9999. \path[->,bend right=15] (x86-2-1) edge [below] node
  10000. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10001. \path[->,bend right=15] (x86-2-2) edge [left] node
  10002. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10003. \path[->,bend left=15] (x86-3) edge [above] node
  10004. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10005. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10006. \end{tikzpicture}
  10007. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10008. \label{fig:Rwhile-passes}
  10009. \end{figure}
  10010. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10011. for the compilation of \LangLoop{}.
  10012. % TODO: challenge assignment
  10013. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10014. \chapter{Gradual Typing}
  10015. \label{ch:gradual-typing}
  10016. \index{gradual typing}
  10017. This chapter studies a language, \LangGrad{}, in which the programmer
  10018. can choose between static and dynamic type checking in different parts
  10019. of a program, thereby mixing the statically typed \LangLoop{} language
  10020. with the dynamically typed \LangDyn{}. There are several approaches to
  10021. mixing static and dynamic typing, including multi-language
  10022. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10023. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10024. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10025. programmer controls the amount of static versus dynamic checking by
  10026. adding or removing type annotations on parameters and
  10027. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10028. %
  10029. The concrete syntax of \LangGrad{} is defined in
  10030. Figure~\ref{fig:r9-concrete-syntax} and its abstract syntax is defined
  10031. in Figure~\ref{fig:r9-syntax}. The main syntactic difference between
  10032. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10033. non-terminals that make type annotations optional. The return types
  10034. are not optional in the abstract syntax; the parser fills in
  10035. \code{Any} when the return type is not specified in the concrete
  10036. syntax.
  10037. \begin{figure}[tp]
  10038. \centering
  10039. \fbox{
  10040. \begin{minipage}{0.96\textwidth}
  10041. \small
  10042. \[
  10043. \begin{array}{lcl}
  10044. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10045. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10046. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10047. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10048. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10049. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10050. \mid (\key{and}\;\Exp\;\Exp)
  10051. \mid (\key{or}\;\Exp\;\Exp)
  10052. \mid (\key{not}\;\Exp) } \\
  10053. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10054. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10055. (\key{vector-ref}\;\Exp\;\Int)} \\
  10056. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10057. \mid (\Exp \; \Exp\ldots) } \\
  10058. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10059. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10060. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10061. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10062. \mid \CWHILE{\Exp}{\Exp} } \\
  10063. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10064. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10065. \end{array}
  10066. \]
  10067. \end{minipage}
  10068. }
  10069. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-concrete-syntax}).}
  10070. \label{fig:r9-concrete-syntax}
  10071. \end{figure}
  10072. \begin{figure}[tp]
  10073. \centering
  10074. \fbox{
  10075. \begin{minipage}{0.96\textwidth}
  10076. \small
  10077. \[
  10078. \begin{array}{lcl}
  10079. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10080. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10081. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10082. &\mid& \gray{ \BOOL{\itm{bool}}
  10083. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10084. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10085. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10086. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10087. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10088. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10089. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10090. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10091. \end{array}
  10092. \]
  10093. \end{minipage}
  10094. }
  10095. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10096. \label{fig:r9-syntax}
  10097. \end{figure}
  10098. Both the type checker and the interpreter for \LangGrad{} require some
  10099. interesting changes to enable gradual typing, which we discuss in the
  10100. next two sections in the context of the \code{map-vec} example from
  10101. Chapter~\ref{ch:functions}. In Figure~\ref{fig:gradual-map-vec} we
  10102. revised the \code{map-vec} example, omitting the type annotations from
  10103. the \code{add1} function.
  10104. \begin{figure}[btp]
  10105. % gradual_test_9.rkt
  10106. \begin{lstlisting}
  10107. (define (map-vec [f : (Integer -> Integer)]
  10108. [v : (Vector Integer Integer)])
  10109. : (Vector Integer Integer)
  10110. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10111. (define (add1 x) (+ x 1))
  10112. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10113. \end{lstlisting}
  10114. \caption{A partially-typed version of the \code{map-vec} example.}
  10115. \label{fig:gradual-map-vec}
  10116. \end{figure}
  10117. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10118. \label{sec:gradual-type-check}
  10119. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10120. parameter and return types. For example, the \code{x} parameter of
  10121. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10122. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10123. consider the \code{+} operator inside \code{add1}. It expects both
  10124. arguments to have type \code{Integer}, but its first argument \code{x}
  10125. has type \code{Any}. In a gradually typed language, such differences
  10126. are allowed so long as the types are \emph{consistent}, that is, they
  10127. are equal except in places where there is an \code{Any} type. The type
  10128. \code{Any} is consistent with every other type.
  10129. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10130. \begin{figure}[tbp]
  10131. \begin{lstlisting}
  10132. (define/public (consistent? t1 t2)
  10133. (match* (t1 t2)
  10134. [('Integer 'Integer) #t]
  10135. [('Boolean 'Boolean) #t]
  10136. [('Void 'Void) #t]
  10137. [('Any t2) #t]
  10138. [(t1 'Any) #t]
  10139. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10140. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10141. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10142. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10143. (consistent? rt1 rt2))]
  10144. [(other wise) #f]))
  10145. \end{lstlisting}
  10146. \caption{The consistency predicate on types, a method in
  10147. \code{type-check-gradual-class}.}
  10148. \label{fig:consistent}
  10149. \end{figure}
  10150. Returning to the \code{map-vec} example of
  10151. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10152. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10153. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10154. because the two types are consistent. In particular, \code{->} is
  10155. equal to \code{->} and because \code{Any} is consistent with
  10156. \code{Integer}.
  10157. Next consider a program with an error, such as applying the
  10158. \code{map-vec} to a function that sometimes returns a Boolean, as
  10159. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10160. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10161. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10162. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10163. Integer)}. One might say that a gradual type checker is optimistic
  10164. in that it accepts programs that might execute without a runtime type
  10165. error.
  10166. %
  10167. Unfortunately, running this program with input \code{1} triggers an
  10168. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10169. performs checking at runtime to ensure the integrity of the static
  10170. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10171. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10172. new \code{Cast} form that is inserted by the type checker. Thus, the
  10173. output of the type checker is a program in the \LangCast{} language, which
  10174. adds \code{Cast} to \LangLoop{}, as shown in
  10175. Figure~\ref{fig:r9-prime-syntax}.
  10176. \begin{figure}[tp]
  10177. \centering
  10178. \fbox{
  10179. \begin{minipage}{0.96\textwidth}
  10180. \small
  10181. \[
  10182. \begin{array}{lcl}
  10183. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10184. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10185. \end{array}
  10186. \]
  10187. \end{minipage}
  10188. }
  10189. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10190. \label{fig:r9-prime-syntax}
  10191. \end{figure}
  10192. \begin{figure}[tbp]
  10193. \begin{lstlisting}
  10194. (define (map-vec [f : (Integer -> Integer)]
  10195. [v : (Vector Integer Integer)])
  10196. : (Vector Integer Integer)
  10197. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10198. (define (add1 x) (+ x 1))
  10199. (define (true) #t)
  10200. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10201. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10202. \end{lstlisting}
  10203. \caption{A variant of the \code{map-vec} example with an error.}
  10204. \label{fig:map-vec-maybe-add1}
  10205. \end{figure}
  10206. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10207. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10208. inserted every time the type checker sees two types that are
  10209. consistent but not equal. In the \code{add1} function, \code{x} is
  10210. cast to \code{Integer} and the result of the \code{+} is cast to
  10211. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10212. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10213. \begin{figure}[btp]
  10214. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10215. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10216. : (Vector Integer Integer)
  10217. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10218. (define (add1 [x : Any]) : Any
  10219. (cast (+ (cast x Any Integer) 1) Integer Any))
  10220. (define (true) : Any (cast #t Boolean Any))
  10221. (define (maybe-add1 [x : Any]) : Any
  10222. (if (eq? 0 (read)) (add1 x) (true)))
  10223. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10224. (vector 0 41)) 0)
  10225. \end{lstlisting}
  10226. \caption{Output of type checking \code{map-vec}
  10227. and \code{maybe-add1}.}
  10228. \label{fig:map-vec-cast}
  10229. \end{figure}
  10230. The type checker for \LangGrad{} is defined in
  10231. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10232. and \ref{fig:type-check-Rgradual-3}.
  10233. \begin{figure}[tbp]
  10234. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10235. (define type-check-gradual-class
  10236. (class type-check-Rwhile-class
  10237. (super-new)
  10238. (inherit operator-types type-predicates)
  10239. (define/override (type-check-exp env)
  10240. (lambda (e)
  10241. (define recur (type-check-exp env))
  10242. (match e
  10243. [(Prim 'vector-length (list e1))
  10244. (define-values (e1^ t) (recur e1))
  10245. (match t
  10246. [`(Vector ,ts ...)
  10247. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10248. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10249. [(Prim 'vector-ref (list e1 e2))
  10250. (define-values (e1^ t1) (recur e1))
  10251. (define-values (e2^ t2) (recur e2))
  10252. (check-consistent? t2 'Integer e)
  10253. (match t1
  10254. [`(Vector ,ts ...)
  10255. (match e2^
  10256. [(Int i)
  10257. (unless (and (0 . <= . i) (i . < . (length ts)))
  10258. (error 'type-check "invalid index ~a in ~a" i e))
  10259. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10260. [else (define e1^^ (make-cast e1^ t1 'Any))
  10261. (define e2^^ (make-cast e2^ t2 'Integer))
  10262. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10263. ['Any
  10264. (define e2^^ (make-cast e2^ t2 'Integer))
  10265. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10266. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10267. [(Prim 'vector-set! (list e1 e2 e3) )
  10268. (define-values (e1^ t1) (recur e1))
  10269. (define-values (e2^ t2) (recur e2))
  10270. (define-values (e3^ t3) (recur e3))
  10271. (check-consistent? t2 'Integer e)
  10272. (match t1
  10273. [`(Vector ,ts ...)
  10274. (match e2^
  10275. [(Int i)
  10276. (unless (and (0 . <= . i) (i . < . (length ts)))
  10277. (error 'type-check "invalid index ~a in ~a" i e))
  10278. (check-consistent? (list-ref ts i) t3 e)
  10279. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10280. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10281. [else
  10282. (define e1^^ (make-cast e1^ t1 'Any))
  10283. (define e2^^ (make-cast e2^ t2 'Integer))
  10284. (define e3^^ (make-cast e3^ t3 'Any))
  10285. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10286. ['Any
  10287. (define e2^^ (make-cast e2^ t2 'Integer))
  10288. (define e3^^ (make-cast e3^ t3 'Any))
  10289. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10290. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10291. \end{lstlisting}
  10292. \caption{Type checker for the \LangGrad{} language, part 1.}
  10293. \label{fig:type-check-Rgradual-1}
  10294. \end{figure}
  10295. \begin{figure}[tbp]
  10296. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10297. [(Prim 'eq? (list e1 e2))
  10298. (define-values (e1^ t1) (recur e1))
  10299. (define-values (e2^ t2) (recur e2))
  10300. (check-consistent? t1 t2 e)
  10301. (define T (meet t1 t2))
  10302. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10303. 'Boolean)]
  10304. [(Prim 'not (list e1))
  10305. (define-values (e1^ t1) (recur e1))
  10306. (match t1
  10307. ['Any
  10308. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10309. (Bool #t) (Bool #f)))]
  10310. [else
  10311. (define-values (t-ret new-es^)
  10312. (type-check-op 'not (list t1) (list e1^) e))
  10313. (values (Prim 'not new-es^) t-ret)])]
  10314. [(Prim 'and (list e1 e2))
  10315. (recur (If e1 e2 (Bool #f)))]
  10316. [(Prim 'or (list e1 e2))
  10317. (define tmp (gensym 'tmp))
  10318. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10319. [(Prim op es)
  10320. #:when (not (set-member? explicit-prim-ops op))
  10321. (define-values (new-es ts)
  10322. (for/lists (exprs types) ([e es])
  10323. (recur e)))
  10324. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10325. (values (Prim op new-es^) t-ret)]
  10326. [(If e1 e2 e3)
  10327. (define-values (e1^ T1) (recur e1))
  10328. (define-values (e2^ T2) (recur e2))
  10329. (define-values (e3^ T3) (recur e3))
  10330. (check-consistent? T2 T3 e)
  10331. (match T1
  10332. ['Boolean
  10333. (define Tif (join T2 T3))
  10334. (values (If e1^ (make-cast e2^ T2 Tif)
  10335. (make-cast e3^ T3 Tif)) Tif)]
  10336. ['Any
  10337. (define Tif (meet T2 T3))
  10338. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10339. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10340. Tif)]
  10341. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10342. [(HasType e1 T)
  10343. (define-values (e1^ T1) (recur e1))
  10344. (check-consistent? T1 T)
  10345. (values (make-cast e1^ T1 T) T)]
  10346. [(SetBang x e1)
  10347. (define-values (e1^ T1) (recur e1))
  10348. (define varT (dict-ref env x))
  10349. (check-consistent? T1 varT e)
  10350. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10351. [(WhileLoop e1 e2)
  10352. (define-values (e1^ T1) (recur e1))
  10353. (check-consistent? T1 'Boolean e)
  10354. (define-values (e2^ T2) ((type-check-exp env) e2))
  10355. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10356. \end{lstlisting}
  10357. \caption{Type checker for the \LangGrad{} language, part 2.}
  10358. \label{fig:type-check-Rgradual-2}
  10359. \end{figure}
  10360. \begin{figure}[tbp]
  10361. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10362. [(Apply e1 e2s)
  10363. (define-values (e1^ T1) (recur e1))
  10364. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10365. (match T1
  10366. [`(,T1ps ... -> ,T1rt)
  10367. (for ([T2 T2s] [Tp T1ps])
  10368. (check-consistent? T2 Tp e))
  10369. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10370. (make-cast e2 src tgt)))
  10371. (values (Apply e1^ e2s^^) T1rt)]
  10372. [`Any
  10373. (define e1^^ (make-cast e1^ 'Any
  10374. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10375. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10376. (make-cast e2 src 'Any)))
  10377. (values (Apply e1^^ e2s^^) 'Any)]
  10378. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10379. [(Lambda params Tr e1)
  10380. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10381. (match p
  10382. [`[,x : ,T] (values x T)]
  10383. [(? symbol? x) (values x 'Any)])))
  10384. (define-values (e1^ T1)
  10385. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10386. (check-consistent? Tr T1 e)
  10387. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10388. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10389. [else ((super type-check-exp env) e)]
  10390. )))
  10391. \end{lstlisting}
  10392. \caption{Type checker for the \LangGrad{} language, part 3.}
  10393. \label{fig:type-check-Rgradual-3}
  10394. \end{figure}
  10395. \begin{figure}[tbp]
  10396. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10397. (define/public (join t1 t2)
  10398. (match* (t1 t2)
  10399. [('Integer 'Integer) 'Integer]
  10400. [('Boolean 'Boolean) 'Boolean]
  10401. [('Void 'Void) 'Void]
  10402. [('Any t2) t2]
  10403. [(t1 'Any) t1]
  10404. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10405. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10406. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10407. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10408. -> ,(join rt1 rt2))]))
  10409. (define/public (meet t1 t2)
  10410. (match* (t1 t2)
  10411. [('Integer 'Integer) 'Integer]
  10412. [('Boolean 'Boolean) 'Boolean]
  10413. [('Void 'Void) 'Void]
  10414. [('Any t2) 'Any]
  10415. [(t1 'Any) 'Any]
  10416. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10417. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10418. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10419. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10420. -> ,(meet rt1 rt2))]))
  10421. (define/public (make-cast e src tgt)
  10422. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10423. (define/public (check-consistent? t1 t2 e)
  10424. (unless (consistent? t1 t2)
  10425. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10426. (define/override (type-check-op op arg-types args e)
  10427. (match (dict-ref (operator-types) op)
  10428. [`(,param-types . ,return-type)
  10429. (for ([at arg-types] [pt param-types])
  10430. (check-consistent? at pt e))
  10431. (values return-type
  10432. (for/list ([e args] [s arg-types] [t param-types])
  10433. (make-cast e s t)))]
  10434. [else (error 'type-check-op "unrecognized ~a" op)]))
  10435. (define explicit-prim-ops
  10436. (set-union
  10437. (type-predicates)
  10438. (set 'procedure-arity 'eq?
  10439. 'vector 'vector-length 'vector-ref 'vector-set!
  10440. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  10441. (define/override (fun-def-type d)
  10442. (match d
  10443. [(Def f params rt info body)
  10444. (define ps
  10445. (for/list ([p params])
  10446. (match p
  10447. [`[,x : ,T] T]
  10448. [(? symbol?) 'Any]
  10449. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  10450. `(,@ps -> ,rt)]
  10451. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  10452. \end{lstlisting}
  10453. \caption{Auxiliary functions for type checking \LangGrad{}.}
  10454. \label{fig:type-check-Rgradual-aux}
  10455. \end{figure}
  10456. \clearpage
  10457. \section{Interpreting \LangCast{}}
  10458. \label{sec:interp-casts}
  10459. The runtime behavior of first-order casts is straightforward, that is,
  10460. casts involving simple types such as \code{Integer} and
  10461. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  10462. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  10463. puts the integer into a tagged value
  10464. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  10465. \code{Integer} is accomplished with the \code{Project} operator, that
  10466. is, by checking the value's tag and either retrieving the underlying
  10467. integer or signaling an error if it the tag is not the one for
  10468. integers (Figure~\ref{fig:apply-project}).
  10469. %
  10470. Things get more interesting for higher-order casts, that is, casts
  10471. involving function or vector types.
  10472. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  10473. Any)} to \code{(Integer -> Integer)}. When a function flows through
  10474. this cast at runtime, we can't know in general whether the function
  10475. will always return an integer.\footnote{Predicting the return value of
  10476. a function is equivalent to the halting problem, which is
  10477. undecidable.} The \LangCast{} interpreter therefore delays the checking
  10478. of the cast until the function is applied. This is accomplished by
  10479. wrapping \code{maybe-add1} in a new function that casts its parameter
  10480. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  10481. casts the return value from \code{Any} to \code{Integer}.
  10482. Turning our attention to casts involving vector types, we consider the
  10483. example in Figure~\ref{fig:map-vec-bang} that defines a
  10484. partially-typed version of \code{map-vec} whose parameter \code{v} has
  10485. type \code{(Vector Any Any)} and that updates \code{v} in place
  10486. instead of returning a new vector. So we name this function
  10487. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  10488. the type checker inserts a cast from \code{(Vector Integer Integer)}
  10489. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  10490. cast between vector types would be a build a new vector whose elements
  10491. are the result of casting each of the original elements to the
  10492. appropriate target type. However, this approach is only valid for
  10493. immutable vectors; and our vectors are mutable. In the example of
  10494. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  10495. the updates inside of \code{map-vec!} would happen to the new vector
  10496. and not the original one.
  10497. \begin{figure}[tbp]
  10498. % gradual_test_11.rkt
  10499. \begin{lstlisting}
  10500. (define (map-vec! [f : (Any -> Any)]
  10501. [v : (Vector Any Any)]) : Void
  10502. (begin
  10503. (vector-set! v 0 (f (vector-ref v 0)))
  10504. (vector-set! v 1 (f (vector-ref v 1)))))
  10505. (define (add1 x) (+ x 1))
  10506. (let ([v (vector 0 41)])
  10507. (begin (map-vec! add1 v) (vector-ref v 1)))
  10508. \end{lstlisting}
  10509. \caption{An example involving casts on vectors.}
  10510. \label{fig:map-vec-bang}
  10511. \end{figure}
  10512. Instead the interpreter needs to create a new kind of value, a
  10513. \emph{vector proxy}, that intercepts every vector operation. On a
  10514. read, the proxy reads from the underlying vector and then applies a
  10515. cast to the resulting value. On a write, the proxy casts the argument
  10516. value and then performs the write to the underlying vector. For the
  10517. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  10518. \code{0} from \code{Integer} to \code{Any}. For the first
  10519. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  10520. to \code{Integer}.
  10521. The final category of cast that we need to consider are casts between
  10522. the \code{Any} type and either a function or a vector
  10523. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  10524. in which parameter \code{v} does not have a type annotation, so it is
  10525. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  10526. type \code{(Vector Integer Integer)} so the type checker inserts a
  10527. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  10528. thought is to use \code{Inject}, but that doesn't work because
  10529. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  10530. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  10531. to \code{Any}.
  10532. \begin{figure}[tbp]
  10533. \begin{lstlisting}
  10534. (define (map-vec! [f : (Any -> Any)] v) : Void
  10535. (begin
  10536. (vector-set! v 0 (f (vector-ref v 0)))
  10537. (vector-set! v 1 (f (vector-ref v 1)))))
  10538. (define (add1 x) (+ x 1))
  10539. (let ([v (vector 0 41)])
  10540. (begin (map-vec! add1 v) (vector-ref v 1)))
  10541. \end{lstlisting}
  10542. \caption{Casting a vector to \code{Any}.}
  10543. \label{fig:map-vec-any}
  10544. \end{figure}
  10545. The \LangCast{} interpreter uses an auxiliary function named
  10546. \code{apply-cast} to cast a value from a source type to a target type,
  10547. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  10548. of the kinds of casts that we've discussed in this section.
  10549. \begin{figure}[tbp]
  10550. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10551. (define/public (apply-cast v s t)
  10552. (match* (s t)
  10553. [(t1 t2) #:when (equal? t1 t2) v]
  10554. [('Any t2)
  10555. (match t2
  10556. [`(,ts ... -> ,rt)
  10557. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10558. (define v^ (apply-project v any->any))
  10559. (apply-cast v^ any->any `(,@ts -> ,rt))]
  10560. [`(Vector ,ts ...)
  10561. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10562. (define v^ (apply-project v vec-any))
  10563. (apply-cast v^ vec-any `(Vector ,@ts))]
  10564. [else (apply-project v t2)])]
  10565. [(t1 'Any)
  10566. (match t1
  10567. [`(,ts ... -> ,rt)
  10568. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10569. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  10570. (apply-inject v^ (any-tag any->any))]
  10571. [`(Vector ,ts ...)
  10572. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10573. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  10574. (apply-inject v^ (any-tag vec-any))]
  10575. [else (apply-inject v (any-tag t1))])]
  10576. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10577. (define x (gensym 'x))
  10578. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  10579. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  10580. (define cast-writes
  10581. (for/list ([t1 ts1] [t2 ts2])
  10582. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  10583. `(vector-proxy ,(vector v (apply vector cast-reads)
  10584. (apply vector cast-writes)))]
  10585. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10586. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  10587. `(function ,xs ,(Cast
  10588. (Apply (Value v)
  10589. (for/list ([x xs][t1 ts1][t2 ts2])
  10590. (Cast (Var x) t2 t1)))
  10591. rt1 rt2) ())]
  10592. ))
  10593. \end{lstlisting}
  10594. \caption{The \code{apply-cast} auxiliary method.}
  10595. \label{fig:apply-cast}
  10596. \end{figure}
  10597. The interpreter for \LangCast{} is defined in
  10598. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  10599. dispatching to \code{apply-cast}. To handle the addition of vector
  10600. proxies, we update the vector primitives in \code{interp-op} using the
  10601. functions in Figure~\ref{fig:guarded-vector}.
  10602. \begin{figure}[tbp]
  10603. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10604. (define interp-Rcast-class
  10605. (class interp-Rwhile-class
  10606. (super-new)
  10607. (inherit apply-fun apply-inject apply-project)
  10608. (define/override (interp-op op)
  10609. (match op
  10610. ['vector-length guarded-vector-length]
  10611. ['vector-ref guarded-vector-ref]
  10612. ['vector-set! guarded-vector-set!]
  10613. ['any-vector-ref (lambda (v i)
  10614. (match v [`(tagged ,v^ ,tg)
  10615. (guarded-vector-ref v^ i)]))]
  10616. ['any-vector-set! (lambda (v i a)
  10617. (match v [`(tagged ,v^ ,tg)
  10618. (guarded-vector-set! v^ i a)]))]
  10619. ['any-vector-length (lambda (v)
  10620. (match v [`(tagged ,v^ ,tg)
  10621. (guarded-vector-length v^)]))]
  10622. [else (super interp-op op)]
  10623. ))
  10624. (define/override ((interp-exp env) e)
  10625. (define (recur e) ((interp-exp env) e))
  10626. (match e
  10627. [(Value v) v]
  10628. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  10629. [else ((super interp-exp env) e)]))
  10630. ))
  10631. (define (interp-Rcast p)
  10632. (send (new interp-Rcast-class) interp-program p))
  10633. \end{lstlisting}
  10634. \caption{The interpreter for \LangCast{}.}
  10635. \label{fig:interp-Rcast}
  10636. \end{figure}
  10637. \begin{figure}[tbp]
  10638. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10639. (define (guarded-vector-ref vec i)
  10640. (match vec
  10641. [`(vector-proxy ,proxy)
  10642. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  10643. (define rd (vector-ref (vector-ref proxy 1) i))
  10644. (apply-fun rd (list val) 'guarded-vector-ref)]
  10645. [else (vector-ref vec i)]))
  10646. (define (guarded-vector-set! vec i arg)
  10647. (match vec
  10648. [`(vector-proxy ,proxy)
  10649. (define wr (vector-ref (vector-ref proxy 2) i))
  10650. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  10651. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  10652. [else (vector-set! vec i arg)]))
  10653. (define (guarded-vector-length vec)
  10654. (match vec
  10655. [`(vector-proxy ,proxy)
  10656. (guarded-vector-length (vector-ref proxy 0))]
  10657. [else (vector-length vec)]))
  10658. \end{lstlisting}
  10659. \caption{The guarded-vector auxiliary functions.}
  10660. \label{fig:guarded-vector}
  10661. \end{figure}
  10662. \section{Lower Casts}
  10663. \label{sec:lower-casts}
  10664. The next step in the journey towards x86 is the \code{lower-casts}
  10665. pass that translates the casts in \LangCast{} to the lower-level
  10666. \code{Inject} and \code{Project} operators and a new operator for
  10667. creating vector proxies, extending the \LangLoop{} language to create
  10668. \LangProxy{}. We recommend creating an auxiliary function named
  10669. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  10670. and a target type, and translates it to expression in \LangProxy{} that has
  10671. the same behavior as casting the expression from the source to the
  10672. target type in the interpreter.
  10673. The \code{lower-cast} function can follow a code structure similar to
  10674. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  10675. the interpreter for \LangCast{} because it must handle the same cases as
  10676. \code{apply-cast} and it needs to mimic the behavior of
  10677. \code{apply-cast}. The most interesting cases are those concerning the
  10678. casts between two vector types and between two function types.
  10679. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  10680. type to another vector type is accomplished by creating a proxy that
  10681. intercepts the operations on the underlying vector. Here we make the
  10682. creation of the proxy explicit with the \code{vector-proxy} primitive
  10683. operation. It takes three arguments, the first is an expression for
  10684. the vector, the second is a vector of functions for casting an element
  10685. that is being read from the vector, and the third is a vector of
  10686. functions for casting an element that is being written to the vector.
  10687. You can create the functions using \code{Lambda}. Also, as we shall
  10688. see in the next section, we need to differentiate these vectors from
  10689. the user-created ones, so we recommend using a new primitive operator
  10690. named \code{raw-vector} instead of \code{vector} to create these
  10691. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  10692. the output of \code{lower-casts} on the example in
  10693. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  10694. integers to a vector of \code{Any}.
  10695. \begin{figure}[tbp]
  10696. \begin{lstlisting}
  10697. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  10698. (begin
  10699. (vector-set! v 0 (f (vector-ref v 0)))
  10700. (vector-set! v 1 (f (vector-ref v 1)))))
  10701. (define (add1 [x : Any]) : Any
  10702. (inject (+ (project x Integer) 1) Integer))
  10703. (let ([v (vector 0 41)])
  10704. (begin
  10705. (map-vec! add1 (vector-proxy v
  10706. (raw-vector (lambda: ([x9 : Integer]) : Any
  10707. (inject x9 Integer))
  10708. (lambda: ([x9 : Integer]) : Any
  10709. (inject x9 Integer)))
  10710. (raw-vector (lambda: ([x9 : Any]) : Integer
  10711. (project x9 Integer))
  10712. (lambda: ([x9 : Any]) : Integer
  10713. (project x9 Integer)))))
  10714. (vector-ref v 1)))
  10715. \end{lstlisting}
  10716. \caption{Output of \code{lower-casts} on the example in
  10717. Figure~\ref{fig:map-vec-bang}.}
  10718. \label{fig:map-vec-bang-lower-cast}
  10719. \end{figure}
  10720. A cast from one function type to another function type is accomplished
  10721. by generating a \code{Lambda} whose parameter and return types match
  10722. the target function type. The body of the \code{Lambda} should cast
  10723. the parameters from the target type to the source type (yes,
  10724. backwards! functions are contravariant\index{contravariant} in the
  10725. parameters), then call the underlying function, and finally cast the
  10726. result from the source return type to the target return type.
  10727. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  10728. \code{lower-casts} pass on the \code{map-vec} example in
  10729. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  10730. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  10731. \begin{figure}[tbp]
  10732. \begin{lstlisting}
  10733. (define (map-vec [f : (Integer -> Integer)]
  10734. [v : (Vector Integer Integer)])
  10735. : (Vector Integer Integer)
  10736. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10737. (define (add1 [x : Any]) : Any
  10738. (inject (+ (project x Integer) 1) Integer))
  10739. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  10740. (project (add1 (inject x9 Integer)) Integer))
  10741. (vector 0 41)) 1)
  10742. \end{lstlisting}
  10743. \caption{Output of \code{lower-casts} on the example in
  10744. Figure~\ref{fig:gradual-map-vec}.}
  10745. \label{fig:map-vec-lower-cast}
  10746. \end{figure}
  10747. \section{Differentiate Proxies}
  10748. \label{sec:differentiate-proxies}
  10749. So far the job of differentiating vectors and vector proxies has been
  10750. the job of the interpreter. For example, the interpreter for \LangCast{}
  10751. implements \code{vector-ref} using the \code{guarded-vector-ref}
  10752. function in Figure~\ref{fig:guarded-vector}. In the
  10753. \code{differentiate-proxies} pass we shift this responsibility to the
  10754. generated code.
  10755. We begin by designing the output language $R^p_8$. In
  10756. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  10757. proxies. In $R^p_8$ we return the \code{Vector} type to
  10758. its original meaning, as the type of real vectors, and we introduce a
  10759. new type, \code{PVector}, whose values can be either real vectors or
  10760. vector proxies. This new type comes with a suite of new primitive
  10761. operations for creating and using values of type \code{PVector}. We
  10762. don't need to introduce a new type to represent vector proxies. A
  10763. proxy is represented by a vector containing three things: 1) the
  10764. underlying vector, 2) a vector of functions for casting elements that
  10765. are read from the vector, and 3) a vector of functions for casting
  10766. values to be written to the vector. So we define the following
  10767. abbreviation for the type of a vector proxy:
  10768. \[
  10769. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  10770. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  10771. \to (\key{PVector}~ T' \ldots)
  10772. \]
  10773. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  10774. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  10775. %
  10776. Next we describe each of the new primitive operations.
  10777. \begin{description}
  10778. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  10779. (\key{PVector} $T \ldots$)]\ \\
  10780. %
  10781. This operation brands a vector as a value of the \code{PVector} type.
  10782. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  10783. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  10784. %
  10785. This operation brands a vector proxy as value of the \code{PVector} type.
  10786. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  10787. \code{Boolean}] \ \\
  10788. %
  10789. returns true if the value is a vector proxy and false if it is a
  10790. real vector.
  10791. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  10792. (\key{Vector} $T \ldots$)]\ \\
  10793. %
  10794. Assuming that the input is a vector (and not a proxy), this
  10795. operation returns the vector.
  10796. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  10797. $\to$ \code{Boolean}]\ \\
  10798. %
  10799. Given a vector proxy, this operation returns the length of the
  10800. underlying vector.
  10801. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  10802. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  10803. %
  10804. Given a vector proxy, this operation returns the $i$th element of
  10805. the underlying vector.
  10806. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  10807. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  10808. proxy, this operation writes a value to the $i$th element of the
  10809. underlying vector.
  10810. \end{description}
  10811. Now to discuss the translation that differentiates vectors from
  10812. proxies. First, every type annotation in the program must be
  10813. translated (recursively) to replace \code{Vector} with \code{PVector}.
  10814. Next, we must insert uses of \code{PVector} operations in the
  10815. appropriate places. For example, we wrap every vector creation with an
  10816. \code{inject-vector}.
  10817. \begin{lstlisting}
  10818. (vector |$e_1 \ldots e_n$|)
  10819. |$\Rightarrow$|
  10820. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  10821. \end{lstlisting}
  10822. The \code{raw-vector} operator that we introduced in the previous
  10823. section does not get injected.
  10824. \begin{lstlisting}
  10825. (raw-vector |$e_1 \ldots e_n$|)
  10826. |$\Rightarrow$|
  10827. (vector |$e'_1 \ldots e'_n$|)
  10828. \end{lstlisting}
  10829. The \code{vector-proxy} primitive translates as follows.
  10830. \begin{lstlisting}
  10831. (vector-proxy |$e_1~e_2~e_3$|)
  10832. |$\Rightarrow$|
  10833. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  10834. \end{lstlisting}
  10835. We translate the vector operations into conditional expressions that
  10836. check whether the value is a proxy and then dispatch to either the
  10837. appropriate proxy vector operation or the regular vector operation.
  10838. For example, the following is the translation for \code{vector-ref}.
  10839. \begin{lstlisting}
  10840. (vector-ref |$e_1$| |$i$|)
  10841. |$\Rightarrow$|
  10842. (let ([|$v~e_1$|])
  10843. (if (proxy? |$v$|)
  10844. (proxy-vector-ref |$v$| |$i$|)
  10845. (vector-ref (project-vector |$v$|) |$i$|)
  10846. \end{lstlisting}
  10847. Note in the case of a real vector, we must apply \code{project-vector}
  10848. before the \code{vector-ref}.
  10849. \section{Reveal Casts}
  10850. \label{sec:reveal-casts-gradual}
  10851. Recall that the \code{reveal-casts} pass
  10852. (Section~\ref{sec:reveal-casts-r6}) is responsible for lowering
  10853. \code{Inject} and \code{Project} into lower-level operations. In
  10854. particular, \code{Project} turns into a conditional expression that
  10855. inspects the tag and retrieves the underlying value. Here we need to
  10856. augment the translation of \code{Project} to handle the situation when
  10857. the target type is \code{PVector}. Instead of using
  10858. \code{vector-length} we need to use \code{proxy-vector-length}.
  10859. \begin{lstlisting}
  10860. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  10861. |$\Rightarrow$|
  10862. (let |$\itm{tmp}$| |$e'$|
  10863. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  10864. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  10865. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  10866. (exit)))
  10867. \end{lstlisting}
  10868. \section{Closure Conversion}
  10869. \label{sec:closure-conversion-gradual}
  10870. The closure conversion pass only requires one minor adjustment. The
  10871. auxiliary function that translates type annotations needs to be
  10872. updated to handle the \code{PVector} type.
  10873. \section{Explicate Control}
  10874. \label{sec:explicate-control-gradual}
  10875. Update the \code{explicate-control} pass to handle the new primitive
  10876. operations on the \code{PVector} type.
  10877. \section{Select Instructions}
  10878. \label{sec:select-instructions-gradual}
  10879. Recall that the \code{select-instructions} pass is responsible for
  10880. lowering the primitive operations into x86 instructions. So we need
  10881. to translate the new \code{PVector} operations to x86. To do so, the
  10882. first question we need to answer is how will we differentiate the two
  10883. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  10884. We need just one bit to accomplish this, so we use the $57$th bit of
  10885. the 64-bit tag at the front of every vector (see
  10886. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  10887. for \code{inject-vector} we leave it that way.
  10888. \begin{lstlisting}
  10889. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  10890. |$\Rightarrow$|
  10891. movq |$e'_1$|, |$\itm{lhs'}$|
  10892. \end{lstlisting}
  10893. On the other hand, \code{inject-proxy} sets the $57$th bit to $1$.
  10894. \begin{lstlisting}
  10895. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  10896. |$\Rightarrow$|
  10897. movq |$e'_1$|, %r11
  10898. movq |$(1 << 57)$|, %rax
  10899. orq 0(%r11), %rax
  10900. movq %rax, 0(%r11)
  10901. movq %r11, |$\itm{lhs'}$|
  10902. \end{lstlisting}
  10903. The \code{proxy?} operation consumes the information so carefully
  10904. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  10905. isolates the $57$th bit to tell whether the value is a real vector or
  10906. a proxy.
  10907. \begin{lstlisting}
  10908. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  10909. |$\Rightarrow$|
  10910. movq |$e_1'$|, %r11
  10911. movq 0(%r11), %rax
  10912. sarq $57, %rax
  10913. andq $1, %rax
  10914. movq %rax, |$\itm{lhs'}$|
  10915. \end{lstlisting}
  10916. The \code{project-vector} operation is straightforward to translate,
  10917. so we leave it up to the reader.
  10918. Regarding the \code{proxy-vector} operations, the runtime provides
  10919. procedures that implement them (they are recursive functions!) so
  10920. here we simply need to translate these vector operations into the
  10921. appropriate function call. For example, here is the translation for
  10922. \code{proxy-vector-ref}.
  10923. \begin{lstlisting}
  10924. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  10925. |$\Rightarrow$|
  10926. movq |$e_1'$|, %rdi
  10927. movq |$e_2'$|, %rsi
  10928. callq proxy_vector_ref
  10929. movq %rax, |$\itm{lhs'}$|
  10930. \end{lstlisting}
  10931. We have another batch of vector operations to deal with, those for the
  10932. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  10933. \code{any-vector-ref} when there is a \code{vector-ref} on something
  10934. of type \code{Any}, and similarly for \code{any-vector-set!} and
  10935. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  10936. Section~\ref{sec:select-r6} we selected instructions for these
  10937. operations based on the idea that the underlying value was a real
  10938. vector. But in the current setting, the underlying value is of type
  10939. \code{PVector}. So \code{any-vector-ref} can be translates to
  10940. pseudo-x86 as follows. We begin by projecting the underlying value out
  10941. of the tagged value and then call the \code{proxy\_vector\_ref}
  10942. procedure in the runtime.
  10943. \begin{lstlisting}
  10944. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  10945. movq |$\neg 111$|, %rdi
  10946. andq |$e_1'$|, %rdi
  10947. movq |$e_2'$|, %rsi
  10948. callq proxy_vector_ref
  10949. movq %rax, |$\itm{lhs'}$|
  10950. \end{lstlisting}
  10951. The \code{any-vector-set!} and \code{any-vector-length} operators can
  10952. be translated in a similar way.
  10953. \begin{exercise}\normalfont
  10954. Implement a compiler for the gradually-typed \LangGrad{} language by
  10955. extending and adapting your compiler for \LangLoop{}. Create 10 new
  10956. partially-typed test programs. In addition to testing with these
  10957. new programs, also test your compiler on all the tests for \LangLoop{}
  10958. and tests for \LangDyn{}. Sometimes you may get a type checking error
  10959. on the \LangDyn{} programs but you can adapt them by inserting
  10960. a cast to the \code{Any} type around each subexpression
  10961. causing a type error. While \LangDyn{} doesn't have explicit casts,
  10962. you can induce one by wrapping the subexpression \code{e}
  10963. with a call to an un-annotated identity function, like this:
  10964. \code{((lambda (x) x) e)}.
  10965. \end{exercise}
  10966. \begin{figure}[p]
  10967. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10968. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  10969. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  10970. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  10971. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  10972. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  10973. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  10974. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  10975. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  10976. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  10977. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  10978. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  10979. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  10980. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  10981. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  10982. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10983. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10984. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10985. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10986. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10987. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10988. \path[->,bend right=15] (Rgradual) edge [above] node
  10989. {\ttfamily\footnotesize type-check} (Rgradualp);
  10990. \path[->,bend right=15] (Rgradualp) edge [above] node
  10991. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  10992. \path[->,bend right=15] (Rwhilepp) edge [right] node
  10993. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  10994. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  10995. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  10996. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  10997. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  10998. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  10999. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11000. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11001. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11002. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11003. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11004. \path[->,bend left=15] (F1-1) edge [below] node
  11005. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11006. \path[->,bend right=15] (F1-2) edge [above] node
  11007. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11008. \path[->,bend right=15] (F1-3) edge [above] node
  11009. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11010. \path[->,bend right=15] (F1-4) edge [above] node
  11011. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11012. \path[->,bend right=15] (F1-5) edge [right] node
  11013. {\ttfamily\footnotesize explicate-control} (C3-2);
  11014. \path[->,bend left=15] (C3-2) edge [left] node
  11015. {\ttfamily\footnotesize select-instr.} (x86-2);
  11016. \path[->,bend right=15] (x86-2) edge [left] node
  11017. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11018. \path[->,bend right=15] (x86-2-1) edge [below] node
  11019. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11020. \path[->,bend right=15] (x86-2-2) edge [left] node
  11021. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11022. \path[->,bend left=15] (x86-3) edge [above] node
  11023. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11024. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11025. \end{tikzpicture}
  11026. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11027. \label{fig:Rgradual-passes}
  11028. \end{figure}
  11029. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11030. for the compilation of \LangGrad{}.
  11031. \section{Further Reading}
  11032. This chapter just scratches the surface of gradual typing. The basic
  11033. approach described here is missing two key ingredients that one would
  11034. want in a implementation of gradual typing: blame
  11035. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11036. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11037. problem addressed by blame tracking is that when a cast on a
  11038. higher-order value fails, it often does so at a point in the program
  11039. that is far removed from the original cast. Blame tracking is a
  11040. technique for propagating extra information through casts and proxies
  11041. so that when a cast fails, the error message can point back to the
  11042. original location of the cast in the source program.
  11043. The problem addressed by space-efficient casts also relates to
  11044. higher-order casts. It turns out that in partially typed programs, a
  11045. function or vector can flow through very-many casts at runtime. With
  11046. the approach described in this chapter, each cast adds another
  11047. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11048. considerable space, but it also makes the function calls and vector
  11049. operations slow. For example, a partially-typed version of quicksort
  11050. could, in the worst case, build a chain of proxies of length $O(n)$
  11051. around the vector, changing the overall time complexity of the
  11052. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11053. solution to this problem by representing casts using the coercion
  11054. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11055. long chains of proxies by compressing them into a concise normal
  11056. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11057. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11058. the Grift compiler.
  11059. \begin{center}
  11060. \url{https://github.com/Gradual-Typing/Grift}
  11061. \end{center}
  11062. There are also interesting interactions between gradual typing and
  11063. other language features, such as parametetric polymorphism,
  11064. information-flow types, and type inference, to name a few. We
  11065. recommend the reader to the online gradual typing bibliography:
  11066. \begin{center}
  11067. \url{http://samth.github.io/gradual-typing-bib/}
  11068. \end{center}
  11069. % TODO: challenge problem:
  11070. % type analysis and type specialization?
  11071. % coercions?
  11072. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11073. \chapter{Parametric Polymorphism}
  11074. \label{ch:parametric-polymorphism}
  11075. \index{parametric polymorphism}
  11076. \index{generics}
  11077. This chapter studies the compilation of parametric
  11078. polymorphism\index{parametric polymorphism}
  11079. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11080. Racket. Parametric polymorphism enables improved code reuse by
  11081. parameterizing functions and data structures with respect to the types
  11082. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11083. revisits the \code{map-vec} example but this time gives it a more
  11084. fitting type. This \code{map-vec} function is parameterized with
  11085. respect to the element type of the vector. The type of \code{map-vec}
  11086. is the following polymorphic type as specified by the \code{All} and
  11087. the type parameter \code{a}.
  11088. \begin{lstlisting}
  11089. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11090. \end{lstlisting}
  11091. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11092. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11093. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11094. \code{a}, but we could have just as well applied \code{map-vec} to a
  11095. vector of Booleans (and a function on Booleans).
  11096. \begin{figure}[tbp]
  11097. % poly_test_2.rkt
  11098. \begin{lstlisting}
  11099. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11100. (define (map-vec f v)
  11101. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11102. (define (add1 [x : Integer]) : Integer (+ x 1))
  11103. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11104. \end{lstlisting}
  11105. \caption{The \code{map-vec} example using parametric polymorphism.}
  11106. \label{fig:map-vec-poly}
  11107. \end{figure}
  11108. Figure~\ref{fig:r10-concrete-syntax} defines the concrete syntax of
  11109. \LangPoly{} and Figure~\ref{fig:r10-syntax} defines the abstract
  11110. syntax. We add a second form for function definitions in which a type
  11111. declaration comes before the \code{define}. In the abstract syntax,
  11112. the return type in the \code{Def} is \code{Any}, but that should be
  11113. ignored in favor of the return type in the type declaration. (The
  11114. \code{Any} comes from using the same parser as in
  11115. Chapter~\ref{ch:type-dynamic}.) The presence of a type declaration
  11116. enables the use of an \code{All} type for a function, thereby making
  11117. it polymorphic. The grammar for types is extended to include
  11118. polymorphic types and type variables.
  11119. \begin{figure}[tp]
  11120. \centering
  11121. \fbox{
  11122. \begin{minipage}{0.96\textwidth}
  11123. \small
  11124. \[
  11125. \begin{array}{lcl}
  11126. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11127. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11128. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11129. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11130. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11131. \end{array}
  11132. \]
  11133. \end{minipage}
  11134. }
  11135. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11136. (Figure~\ref{fig:r8-concrete-syntax}).}
  11137. \label{fig:r10-concrete-syntax}
  11138. \end{figure}
  11139. \begin{figure}[tp]
  11140. \centering
  11141. \fbox{
  11142. \begin{minipage}{0.96\textwidth}
  11143. \small
  11144. \[
  11145. \begin{array}{lcl}
  11146. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11147. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11148. &\mid& \DECL{\Var}{\Type} \\
  11149. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11150. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11151. \end{array}
  11152. \]
  11153. \end{minipage}
  11154. }
  11155. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11156. (Figure~\ref{fig:r8-syntax}).}
  11157. \label{fig:r10-syntax}
  11158. \end{figure}
  11159. By including polymorphic types in the $\Type$ non-terminal we choose
  11160. to make them first-class which has interesting repercussions on the
  11161. compiler. Many languages with polymorphism, such as
  11162. C++~\citep{stroustrup88:_param_types} and Standard
  11163. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11164. it is useful to see an example of first-class polymorphism. In
  11165. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11166. whose parameter is a polymorphic function. The occurrence of a
  11167. polymorphic type underneath a function type is enabled by the normal
  11168. recursive structure of the grammar for $\Type$ and the categorization
  11169. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11170. applies the polymorphic function to a Boolean and to an integer.
  11171. \begin{figure}[tbp]
  11172. \begin{lstlisting}
  11173. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11174. (define (apply-twice f)
  11175. (if (f #t) (f 42) (f 777)))
  11176. (: id (All (a) (a -> a)))
  11177. (define (id x) x)
  11178. (apply-twice id)
  11179. \end{lstlisting}
  11180. \caption{An example illustrating first-class polymorphism.}
  11181. \label{fig:apply-twice}
  11182. \end{figure}
  11183. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11184. three new responsibilities (compared to \LangLoop{}). The type checking of
  11185. function application is extended to handle the case where the operator
  11186. expression is a polymorphic function. In that case the type arguments
  11187. are deduced by matching the type of the parameters with the types of
  11188. the arguments.
  11189. %
  11190. The \code{match-types} auxiliary function carries out this deduction
  11191. by recursively descending through a parameter type \code{pt} and the
  11192. corresponding argument type \code{at}, making sure that they are equal
  11193. except when there is a type parameter on the left (in the parameter
  11194. type). If it's the first time that the type parameter has been
  11195. encountered, then the algorithm deduces an association of the type
  11196. parameter to the corresponding type on the right (in the argument
  11197. type). If it's not the first time that the type parameter has been
  11198. encountered, the algorithm looks up its deduced type and makes sure
  11199. that it is equal to the type on the right.
  11200. %
  11201. Once the type arguments are deduced, the operator expression is
  11202. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11203. type of the operator, but more importantly, records the deduced type
  11204. arguments. The return type of the application is the return type of
  11205. the polymorphic function, but with the type parameters replaced by the
  11206. deduced type arguments, using the \code{subst-type} function.
  11207. The second responsibility of the type checker is extending the
  11208. function \code{type-equal?} to handle the \code{All} type. This is
  11209. not quite a simple as equal on other types, such as function and
  11210. vector types, because two polymorphic types can be syntactically
  11211. different even though they are equivalent types. For example,
  11212. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11213. Two polymorphic types should be considered equal if they differ only
  11214. in the choice of the names of the type parameters. The
  11215. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11216. renames the type parameters of the first type to match the type
  11217. parameters of the second type.
  11218. The third responsibility of the type checker is making sure that only
  11219. defined type variables appear in type annotations. The
  11220. \code{check-well-formed} function defined in
  11221. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11222. sure that each type variable has been defined.
  11223. The output language of the type checker is \LangInst{}, defined in
  11224. Figure~\ref{fig:r10-prime-syntax}. The type checker combines the type
  11225. declaration and polymorphic function into a single definition, using
  11226. the \code{Poly} form, to make polymorphic functions more convenient to
  11227. process in next pass of the compiler.
  11228. \begin{figure}[tp]
  11229. \centering
  11230. \fbox{
  11231. \begin{minipage}{0.96\textwidth}
  11232. \small
  11233. \[
  11234. \begin{array}{lcl}
  11235. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11236. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11237. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11238. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11239. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11240. \end{array}
  11241. \]
  11242. \end{minipage}
  11243. }
  11244. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11245. (Figure~\ref{fig:r8-syntax}).}
  11246. \label{fig:r10-prime-syntax}
  11247. \end{figure}
  11248. The output of the type checker on the polymorphic \code{map-vec}
  11249. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11250. \begin{figure}[tbp]
  11251. % poly_test_2.rkt
  11252. \begin{lstlisting}
  11253. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11254. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11255. (define (add1 [x : Integer]) : Integer (+ x 1))
  11256. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11257. (Integer))
  11258. add1 (vector 0 41)) 1)
  11259. \end{lstlisting}
  11260. \caption{Output of the type checker on the \code{map-vec} example.}
  11261. \label{fig:map-vec-type-check}
  11262. \end{figure}
  11263. \begin{figure}[tbp]
  11264. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11265. (define type-check-poly-class
  11266. (class type-check-Rwhile-class
  11267. (super-new)
  11268. (inherit check-type-equal?)
  11269. (define/override (type-check-apply env e1 es)
  11270. (define-values (e^ ty) ((type-check-exp env) e1))
  11271. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11272. ((type-check-exp env) e)))
  11273. (match ty
  11274. [`(,ty^* ... -> ,rt)
  11275. (for ([arg-ty ty*] [param-ty ty^*])
  11276. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11277. (values e^ es^ rt)]
  11278. [`(All ,xs (,tys ... -> ,rt))
  11279. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11280. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11281. (match-types env^^ param-ty arg-ty)))
  11282. (define targs
  11283. (for/list ([x xs])
  11284. (match (dict-ref env^^ x (lambda () #f))
  11285. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11286. x (Apply e1 es))]
  11287. [ty ty])))
  11288. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11289. [else (error 'type-check "expected a function, not ~a" ty)]))
  11290. (define/override ((type-check-exp env) e)
  11291. (match e
  11292. [(Lambda `([,xs : ,Ts] ...) rT body)
  11293. (for ([T Ts]) ((check-well-formed env) T))
  11294. ((check-well-formed env) rT)
  11295. ((super type-check-exp env) e)]
  11296. [(HasType e1 ty)
  11297. ((check-well-formed env) ty)
  11298. ((super type-check-exp env) e)]
  11299. [else ((super type-check-exp env) e)]))
  11300. (define/override ((type-check-def env) d)
  11301. (verbose 'type-check "poly/def" d)
  11302. (match d
  11303. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11304. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11305. (for ([p ps]) ((check-well-formed ts-env) p))
  11306. ((check-well-formed ts-env) rt)
  11307. (define new-env (append ts-env (map cons xs ps) env))
  11308. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11309. (check-type-equal? ty^ rt body)
  11310. (Generic ts (Def f p:t* rt info body^))]
  11311. [else ((super type-check-def env) d)]))
  11312. (define/override (type-check-program p)
  11313. (match p
  11314. [(Program info body)
  11315. (type-check-program (ProgramDefsExp info '() body))]
  11316. [(ProgramDefsExp info ds body)
  11317. (define ds^ (combine-decls-defs ds))
  11318. (define new-env (for/list ([d ds^])
  11319. (cons (def-name d) (fun-def-type d))))
  11320. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11321. (define-values (body^ ty) ((type-check-exp new-env) body))
  11322. (check-type-equal? ty 'Integer body)
  11323. (ProgramDefsExp info ds^^ body^)]))
  11324. ))
  11325. \end{lstlisting}
  11326. \caption{Type checker for the \LangPoly{} language.}
  11327. \label{fig:type-check-Rvar0}
  11328. \end{figure}
  11329. \begin{figure}[tbp]
  11330. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11331. (define/override (type-equal? t1 t2)
  11332. (match* (t1 t2)
  11333. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11334. (define env (map cons xs ys))
  11335. (type-equal? (subst-type env T1) T2)]
  11336. [(other wise)
  11337. (super type-equal? t1 t2)]))
  11338. (define/public (match-types env pt at)
  11339. (match* (pt at)
  11340. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11341. [('Void 'Void) env] [('Any 'Any) env]
  11342. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11343. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11344. (match-types env^ pt1 at1))]
  11345. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11346. (define env^ (match-types env prt art))
  11347. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11348. (match-types env^^ pt1 at1))]
  11349. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11350. (define env^ (append (map cons pxs axs) env))
  11351. (match-types env^ pt1 at1)]
  11352. [((? symbol? x) at)
  11353. (match (dict-ref env x (lambda () #f))
  11354. [#f (error 'type-check "undefined type variable ~a" x)]
  11355. ['Type (cons (cons x at) env)]
  11356. [t^ (check-type-equal? at t^ 'matching) env])]
  11357. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11358. (define/public (subst-type env pt)
  11359. (match pt
  11360. ['Integer 'Integer] ['Boolean 'Boolean]
  11361. ['Void 'Void] ['Any 'Any]
  11362. [`(Vector ,ts ...)
  11363. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11364. [`(,ts ... -> ,rt)
  11365. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11366. [`(All ,xs ,t)
  11367. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11368. [(? symbol? x) (dict-ref env x)]
  11369. [else (error 'type-check "expected a type not ~a" pt)]))
  11370. (define/public (combine-decls-defs ds)
  11371. (match ds
  11372. ['() '()]
  11373. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11374. (unless (equal? name f)
  11375. (error 'type-check "name mismatch, ~a != ~a" name f))
  11376. (match type
  11377. [`(All ,xs (,ps ... -> ,rt))
  11378. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11379. (cons (Generic xs (Def name params^ rt info body))
  11380. (combine-decls-defs ds^))]
  11381. [`(,ps ... -> ,rt)
  11382. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11383. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11384. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11385. [`(,(Def f params rt info body) . ,ds^)
  11386. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11387. \end{lstlisting}
  11388. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11389. \label{fig:type-check-Rvar0-aux}
  11390. \end{figure}
  11391. \begin{figure}[tbp]
  11392. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11393. (define/public ((check-well-formed env) ty)
  11394. (match ty
  11395. ['Integer (void)]
  11396. ['Boolean (void)]
  11397. ['Void (void)]
  11398. [(? symbol? a)
  11399. (match (dict-ref env a (lambda () #f))
  11400. ['Type (void)]
  11401. [else (error 'type-check "undefined type variable ~a" a)])]
  11402. [`(Vector ,ts ...)
  11403. (for ([t ts]) ((check-well-formed env) t))]
  11404. [`(,ts ... -> ,t)
  11405. (for ([t ts]) ((check-well-formed env) t))
  11406. ((check-well-formed env) t)]
  11407. [`(All ,xs ,t)
  11408. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11409. ((check-well-formed env^) t)]
  11410. [else (error 'type-check "unrecognized type ~a" ty)]))
  11411. \end{lstlisting}
  11412. \caption{Well-formed types.}
  11413. \label{fig:well-formed-types}
  11414. \end{figure}
  11415. % TODO: interpreter for R'_10
  11416. \section{Compiling Polymorphism}
  11417. \label{sec:compiling-poly}
  11418. Broadly speaking, there are four approaches to compiling parametric
  11419. polymorphism, which we describe below.
  11420. \begin{description}
  11421. \item[Monomorphization] generates a different version of a polymorphic
  11422. function for each set of type arguments that it is used with,
  11423. producing type-specialized code. This approach results in the most
  11424. efficient code but requires whole-program compilation (no separate
  11425. compilation) and increases code size. For our current purposes
  11426. monomorphization is a non-starter because, with first-class
  11427. polymorphism, it is sometimes not possible to determine which
  11428. generic functions are used with which type arguments during
  11429. compilation. (It can be done at runtime, with just-in-time
  11430. compilation.) This approach is used to compile C++
  11431. templates~\citep{stroustrup88:_param_types} and polymorphic
  11432. functions in NESL~\citep{Blelloch:1993aa} and
  11433. ML~\citep{Weeks:2006aa}.
  11434. \item[Uniform representation] generates one version of each
  11435. polymorphic function but requires all values have a common ``boxed''
  11436. format, such as the tagged values of type \code{Any} in
  11437. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  11438. similarly to code in a dynamically typed language (like \LangDyn{}), in
  11439. which primitive operators require their arguments to be projected
  11440. from \code{Any} and their results are injected into \code{Any}. (In
  11441. object-oriented languages, the projection is accomplished via
  11442. virtual method dispatch.) The uniform representation approach is
  11443. compatible with separate compilation and with first-class
  11444. polymorphism. However, it produces the least-efficient code because
  11445. it introduces overhead in the entire program, including
  11446. non-polymorphic code. This approach is used in the implementation of
  11447. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  11448. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  11449. Java~\citep{Bracha:1998fk}.
  11450. \item[Mixed representation] generates one version of each polymorphic
  11451. function, using a boxed representation for type
  11452. variables. Monomorphic code is compiled as usual (as in \LangLoop{}) and
  11453. conversions are performed at the boundaries between monomorphic and
  11454. polymorphic (e.g. when a polymorphic function is instantiated and
  11455. called). This approach is compatible with separate compilation and
  11456. first-class polymorphism and maintains the efficiency for
  11457. monomorphic code. The tradeoff is increased overhead at the boundary
  11458. between monomorphic and polymorphic code. This approach is used in
  11459. compilers for variants of ML~\citep{Leroy:1992qb} and starting in
  11460. Java 5 with the addition of autoboxing.
  11461. \item[Type passing] uses the unboxed representation in both
  11462. monomorphic and polymorphic code. Each polymorphic function is
  11463. compiled to a single function with extra parameters that describe
  11464. the type arguments. The type information is used by the generated
  11465. code to direct access of the unboxed values at runtime. This
  11466. approach is used in compilers for the Napier88
  11467. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. This
  11468. approach is compatible with separate compilation and first-class
  11469. polymorphism and maintains the efficiency for monomorphic
  11470. code. There is runtime overhead in polymorphic code from dispatching
  11471. on type information.
  11472. \end{description}
  11473. In this chapter we use the mixed representation approach, partly
  11474. because of its favorable attributes, and partly because it is
  11475. straightforward to implement using the tools that we have already
  11476. built to support gradual typing. To compile polymorphic functions, we
  11477. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  11478. \LangCast{}.
  11479. \section{Erase Types}
  11480. \label{sec:erase-types}
  11481. We use the \code{Any} type from Chapter~\ref{ch:type-dynamic} to
  11482. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  11483. shows the output of the \code{erase-types} pass on the polymorphic
  11484. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  11485. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  11486. \code{All} types are removed from the type of \code{map-vec}.
  11487. \begin{figure}[tbp]
  11488. \begin{lstlisting}
  11489. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  11490. : (Vector Any Any)
  11491. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11492. (define (add1 [x : Integer]) : Integer (+ x 1))
  11493. (vector-ref ((cast map-vec
  11494. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11495. ((Integer -> Integer) (Vector Integer Integer)
  11496. -> (Vector Integer Integer)))
  11497. add1 (vector 0 41)) 1)
  11498. \end{lstlisting}
  11499. \caption{The polymorphic \code{map-vec} example after type erasure.}
  11500. \label{fig:map-vec-erase}
  11501. \end{figure}
  11502. This process of type erasure creates a challenge at points of
  11503. instantiation. For example, consider the instantiation of
  11504. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  11505. The type of \code{map-vec} is
  11506. \begin{lstlisting}
  11507. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11508. \end{lstlisting}
  11509. and it is instantiated to
  11510. \begin{lstlisting}
  11511. ((Integer -> Integer) (Vector Integer Integer)
  11512. -> (Vector Integer Integer))
  11513. \end{lstlisting}
  11514. After erasure, the type of \code{map-vec} is
  11515. \begin{lstlisting}
  11516. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11517. \end{lstlisting}
  11518. but we need to convert it to the instantiated type. This is easy to
  11519. do in the target language \LangCast{} with a single \code{cast}. In
  11520. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  11521. has been compiled to a \code{cast} from the type of \code{map-vec} to
  11522. the instantiated type. The source and target type of a cast must be
  11523. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  11524. because both the source and target are obtained from the same
  11525. polymorphic type of \code{map-vec}, replacing the type parameters with
  11526. \code{Any} in the former and with the deduced type arguments in the
  11527. later. (Recall that the \code{Any} type is consistent with any type.)
  11528. To implement the \code{erase-types} pass, we recommend defining a
  11529. recursive auxiliary function named \code{erase-type} that applies the
  11530. following two transformations. It replaces type variables with
  11531. \code{Any}
  11532. \begin{lstlisting}
  11533. |$x$|
  11534. |$\Rightarrow$|
  11535. Any
  11536. \end{lstlisting}
  11537. and it removes the polymorphic \code{All} types.
  11538. \begin{lstlisting}
  11539. (All |$xs$| |$T_1$|)
  11540. |$\Rightarrow$|
  11541. |$T'_1$|
  11542. \end{lstlisting}
  11543. Apply the \code{erase-type} function to all of the type annotations in
  11544. the program.
  11545. Regarding the translation of expressions, the case for \code{Inst} is
  11546. the interesting one. We translate it into a \code{Cast}, as shown
  11547. below. The type of the subexpression $e$ is the polymorphic type
  11548. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  11549. $T$, the type $T'$. The target type $T''$ is the result of
  11550. substituting the arguments types $ts$ for the type parameters $xs$ in
  11551. $T$ followed by doing type erasure.
  11552. \begin{lstlisting}
  11553. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  11554. |$\Rightarrow$|
  11555. (Cast |$e'$| |$T'$| |$T''$|)
  11556. \end{lstlisting}
  11557. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  11558. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  11559. Finally, each polymorphic function is translated to a regular
  11560. functions in which type erasure has been applied to all the type
  11561. annotations and the body.
  11562. \begin{lstlisting}
  11563. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  11564. |$\Rightarrow$|
  11565. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  11566. \end{lstlisting}
  11567. \begin{exercise}\normalfont
  11568. Implement a compiler for the polymorphic language \LangPoly{} by
  11569. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  11570. programs that use polymorphic functions. Some of them should make
  11571. use of first-class polymorphism.
  11572. \end{exercise}
  11573. \begin{figure}[p]
  11574. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11575. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  11576. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  11577. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11578. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11579. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11580. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11581. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11582. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11583. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11584. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11585. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11586. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11587. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11588. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11589. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11590. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11591. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11592. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11593. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11594. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11595. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11596. \path[->,bend right=15] (Rpoly) edge [above] node
  11597. {\ttfamily\footnotesize type-check} (Rpolyp);
  11598. \path[->,bend right=15] (Rpolyp) edge [above] node
  11599. {\ttfamily\footnotesize erase-types} (Rgradualp);
  11600. \path[->,bend right=15] (Rgradualp) edge [above] node
  11601. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11602. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11603. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11604. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11605. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11606. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11607. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11608. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11609. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11610. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11611. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11612. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11613. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11614. \path[->,bend left=15] (F1-1) edge [below] node
  11615. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11616. \path[->,bend right=15] (F1-2) edge [above] node
  11617. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11618. \path[->,bend right=15] (F1-3) edge [above] node
  11619. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11620. \path[->,bend right=15] (F1-4) edge [above] node
  11621. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11622. \path[->,bend right=15] (F1-5) edge [right] node
  11623. {\ttfamily\footnotesize explicate-control} (C3-2);
  11624. \path[->,bend left=15] (C3-2) edge [left] node
  11625. {\ttfamily\footnotesize select-instr.} (x86-2);
  11626. \path[->,bend right=15] (x86-2) edge [left] node
  11627. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11628. \path[->,bend right=15] (x86-2-1) edge [below] node
  11629. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11630. \path[->,bend right=15] (x86-2-2) edge [left] node
  11631. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11632. \path[->,bend left=15] (x86-3) edge [above] node
  11633. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11634. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11635. \end{tikzpicture}
  11636. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  11637. \label{fig:Rpoly-passes}
  11638. \end{figure}
  11639. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  11640. for the compilation of \LangPoly{}.
  11641. % TODO: challenge problem: specialization of instantiations
  11642. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11643. \chapter{Appendix}
  11644. \section{Interpreters}
  11645. \label{appendix:interp}
  11646. \index{interpreter}
  11647. We provide interpreters for each of the source languages \LangInt{},
  11648. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  11649. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  11650. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  11651. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  11652. and x86 are in the \key{interp.rkt} file.
  11653. \section{Utility Functions}
  11654. \label{appendix:utilities}
  11655. The utility functions described in this section are in the
  11656. \key{utilities.rkt} file of the support code.
  11657. \paragraph{\code{interp-tests}}
  11658. The \key{interp-tests} function runs the compiler passes and the
  11659. interpreters on each of the specified tests to check whether each pass
  11660. is correct. The \key{interp-tests} function has the following
  11661. parameters:
  11662. \begin{description}
  11663. \item[name (a string)] a name to identify the compiler,
  11664. \item[typechecker] a function of exactly one argument that either
  11665. raises an error using the \code{error} function when it encounters a
  11666. type error, or returns \code{\#f} when it encounters a type
  11667. error. If there is no type error, the type checker returns the
  11668. program.
  11669. \item[passes] a list with one entry per pass. An entry is a list with
  11670. four things:
  11671. \begin{enumerate}
  11672. \item a string giving the name of the pass,
  11673. \item the function that implements the pass (a translator from AST
  11674. to AST),
  11675. \item a function that implements the interpreter (a function from
  11676. AST to result value) for the output language,
  11677. \item and a type checker for the output language. Type checkers for
  11678. the $R$ and $C$ languages are provided in the support code. For
  11679. example, the type checkers for \LangVar{} and \LangCVar{} are in
  11680. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  11681. type checker entry is optional. The support code does not provide
  11682. type checkers for the x86 languages.
  11683. \end{enumerate}
  11684. \item[source-interp] an interpreter for the source language. The
  11685. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  11686. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  11687. \item[tests] a list of test numbers that specifies which tests to
  11688. run. (see below)
  11689. \end{description}
  11690. %
  11691. The \key{interp-tests} function assumes that the subdirectory
  11692. \key{tests} has a collection of Racket programs whose names all start
  11693. with the family name, followed by an underscore and then the test
  11694. number, ending with the file extension \key{.rkt}. Also, for each test
  11695. program that calls \code{read} one or more times, there is a file with
  11696. the same name except that the file extension is \key{.in} that
  11697. provides the input for the Racket program. If the test program is
  11698. expected to fail type checking, then there should be an empty file of
  11699. the same name but with extension \key{.tyerr}.
  11700. \paragraph{\code{compiler-tests}}
  11701. runs the compiler passes to generate x86 (a \key{.s} file) and then
  11702. runs the GNU C compiler (gcc) to generate machine code. It runs the
  11703. machine code and checks that the output is $42$. The parameters to the
  11704. \code{compiler-tests} function are similar to those of the
  11705. \code{interp-tests} function, and consist of
  11706. \begin{itemize}
  11707. \item a compiler name (a string),
  11708. \item a type checker,
  11709. \item description of the passes,
  11710. \item name of a test-family, and
  11711. \item a list of test numbers.
  11712. \end{itemize}
  11713. \paragraph{\code{compile-file}}
  11714. takes a description of the compiler passes (see the comment for
  11715. \key{interp-tests}) and returns a function that, given a program file
  11716. name (a string ending in \key{.rkt}), applies all of the passes and
  11717. writes the output to a file whose name is the same as the program file
  11718. name but with \key{.rkt} replaced with \key{.s}.
  11719. \paragraph{\code{read-program}}
  11720. takes a file path and parses that file (it must be a Racket program)
  11721. into an abstract syntax tree.
  11722. \paragraph{\code{parse-program}}
  11723. takes an S-expression representation of an abstract syntax tree and converts it into
  11724. the struct-based representation.
  11725. \paragraph{\code{assert}}
  11726. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  11727. and displays the message \key{msg} if the Boolean \key{bool} is false.
  11728. \paragraph{\code{lookup}}
  11729. % remove discussion of lookup? -Jeremy
  11730. takes a key and an alist, and returns the first value that is
  11731. associated with the given key, if there is one. If not, an error is
  11732. triggered. The alist may contain both immutable pairs (built with
  11733. \key{cons}) and mutable pairs (built with \key{mcons}).
  11734. %The \key{map2} function ...
  11735. \section{x86 Instruction Set Quick-Reference}
  11736. \label{sec:x86-quick-reference}
  11737. \index{x86}
  11738. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  11739. do. We write $A \to B$ to mean that the value of $A$ is written into
  11740. location $B$. Address offsets are given in bytes. The instruction
  11741. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  11742. registers (such as \code{\%rax}), or memory references (such as
  11743. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  11744. reference per instruction. Other operands must be immediates or
  11745. registers.
  11746. \begin{table}[tbp]
  11747. \centering
  11748. \begin{tabular}{l|l}
  11749. \textbf{Instruction} & \textbf{Operation} \\ \hline
  11750. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  11751. \texttt{negq} $A$ & $- A \to A$ \\
  11752. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  11753. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  11754. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  11755. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  11756. \texttt{retq} & Pops the return address and jumps to it \\
  11757. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  11758. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  11759. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  11760. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  11761. be an immediate) \\
  11762. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  11763. matches the condition code of the instruction, otherwise go to the
  11764. next instructions. The condition codes are \key{e} for ``equal'',
  11765. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  11766. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  11767. \texttt{jl} $L$ & \\
  11768. \texttt{jle} $L$ & \\
  11769. \texttt{jg} $L$ & \\
  11770. \texttt{jge} $L$ & \\
  11771. \texttt{jmp} $L$ & Jump to label $L$ \\
  11772. \texttt{movq} $A$, $B$ & $A \to B$ \\
  11773. \texttt{movzbq} $A$, $B$ &
  11774. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  11775. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  11776. and the extra bytes of $B$ are set to zero.} \\
  11777. & \\
  11778. & \\
  11779. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  11780. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  11781. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  11782. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  11783. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  11784. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  11785. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  11786. description of the condition codes. $A$ must be a single byte register
  11787. (e.g., \texttt{al} or \texttt{cl}).} \\
  11788. \texttt{setl} $A$ & \\
  11789. \texttt{setle} $A$ & \\
  11790. \texttt{setg} $A$ & \\
  11791. \texttt{setge} $A$ &
  11792. \end{tabular}
  11793. \vspace{5pt}
  11794. \caption{Quick-reference for the x86 instructions used in this book.}
  11795. \label{tab:x86-instr}
  11796. \end{table}
  11797. \cleardoublepage
  11798. \section{Concrete Syntax for Intermediate Languages}
  11799. The concrete syntax of \LangAny{} is defined in
  11800. Figure~\ref{fig:r6-concrete-syntax}.
  11801. \begin{figure}[tp]
  11802. \centering
  11803. \fbox{
  11804. \begin{minipage}{0.97\textwidth}\small
  11805. \[
  11806. \begin{array}{lcl}
  11807. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  11808. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  11809. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  11810. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  11811. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  11812. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  11813. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  11814. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  11815. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  11816. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  11817. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  11818. \mid \LP\key{void?}\;\Exp\RP \\
  11819. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  11820. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11821. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  11822. \end{array}
  11823. \]
  11824. \end{minipage}
  11825. }
  11826. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  11827. (Figure~\ref{fig:r5-syntax}) with \key{Any}.}
  11828. \label{fig:r6-concrete-syntax}
  11829. \end{figure}
  11830. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  11831. defined in Figures~\ref{fig:c0-concrete-syntax},
  11832. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  11833. and \ref{fig:c3-concrete-syntax}, respectively.
  11834. \begin{figure}[tbp]
  11835. \fbox{
  11836. \begin{minipage}{0.96\textwidth}
  11837. \[
  11838. \begin{array}{lcl}
  11839. \Atm &::=& \Int \mid \Var \\
  11840. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  11841. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  11842. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  11843. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  11844. \end{array}
  11845. \]
  11846. \end{minipage}
  11847. }
  11848. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  11849. \label{fig:c0-concrete-syntax}
  11850. \end{figure}
  11851. \begin{figure}[tbp]
  11852. \fbox{
  11853. \begin{minipage}{0.96\textwidth}
  11854. \small
  11855. \[
  11856. \begin{array}{lcl}
  11857. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  11858. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  11859. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11860. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  11861. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  11862. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11863. \mid \key{goto}~\itm{label}\key{;}\\
  11864. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  11865. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11866. \end{array}
  11867. \]
  11868. \end{minipage}
  11869. }
  11870. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  11871. \label{fig:c1-concrete-syntax}
  11872. \end{figure}
  11873. \begin{figure}[tbp]
  11874. \fbox{
  11875. \begin{minipage}{0.96\textwidth}
  11876. \small
  11877. \[
  11878. \begin{array}{lcl}
  11879. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  11880. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11881. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11882. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  11883. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  11884. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  11885. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  11886. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  11887. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11888. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  11889. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  11890. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11891. \end{array}
  11892. \]
  11893. \end{minipage}
  11894. }
  11895. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  11896. \label{fig:c2-concrete-syntax}
  11897. \end{figure}
  11898. \begin{figure}[tp]
  11899. \fbox{
  11900. \begin{minipage}{0.96\textwidth}
  11901. \small
  11902. \[
  11903. \begin{array}{lcl}
  11904. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  11905. \\
  11906. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11907. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  11908. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  11909. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  11910. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  11911. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  11912. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  11913. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  11914. \mid \LP\key{collect} \,\itm{int}\RP }\\
  11915. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  11916. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  11917. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  11918. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  11919. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  11920. \LangCFun{} & ::= & \Def\ldots
  11921. \end{array}
  11922. \]
  11923. \end{minipage}
  11924. }
  11925. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  11926. \label{fig:c3-concrete-syntax}
  11927. \end{figure}
  11928. \cleardoublepage
  11929. \addcontentsline{toc}{chapter}{Index}
  11930. \printindex
  11931. \cleardoublepage
  11932. \bibliographystyle{plainnat}
  11933. \bibliography{all}
  11934. \addcontentsline{toc}{chapter}{Bibliography}
  11935. \end{document}
  11936. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  11937. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  11938. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  11939. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  11940. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  11941. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  11942. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  11943. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  11944. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  11945. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  11946. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  11947. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  11948. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  11949. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  11950. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  11951. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  11952. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  11953. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  11954. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  11955. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  11956. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  11957. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  11958. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  11959. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  11960. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  11961. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  11962. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  11963. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  11964. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  11965. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  11966. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  11967. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  11968. % LocalWords: alists arity github unordered pqueue exprs ret param
  11969. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  11970. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  11971. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  11972. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  11973. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  11974. % LocalWords: ValueOf typechecker