book.tex 270 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216
  1. % Why direct style instead of continuation passing style?
  2. \documentclass[11pt]{book}
  3. \usepackage[T1]{fontenc}
  4. \usepackage[utf8]{inputenc}
  5. \usepackage{lmodern}
  6. \usepackage{hyperref}
  7. \usepackage{graphicx}
  8. \usepackage[english]{babel}
  9. \usepackage{listings}
  10. \usepackage{amsmath}
  11. \usepackage{amsthm}
  12. \usepackage{amssymb}
  13. \usepackage{natbib}
  14. \usepackage{stmaryrd}
  15. \usepackage{xypic}
  16. \usepackage{semantic}
  17. \usepackage{wrapfig}
  18. \usepackage{multirow}
  19. \usepackage{color}
  20. \definecolor{lightgray}{gray}{1}
  21. \newcommand{\black}[1]{{\color{black} #1}}
  22. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  23. %% For pictures
  24. \usepackage{tikz}
  25. \usetikzlibrary{arrows.meta}
  26. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  27. % Computer Modern is already the default. -Jeremy
  28. %\renewcommand{\ttdefault}{cmtt}
  29. \definecolor{comment-red}{rgb}{0.8,0,0}
  30. \if{0}
  31. % Peanut gallery comments:
  32. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  33. \newcommand{\margincomment}[1]{\marginpar{#1}}
  34. \else
  35. \newcommand{\rn}[1]{}
  36. \newcommand{\margincomment}[1]{}
  37. % \newcommand{\margincomment}[1]{}
  38. \fi
  39. \lstset{%
  40. language=Lisp,
  41. basicstyle=\ttfamily\small,
  42. escapechar=|,
  43. columns=flexible,
  44. moredelim=[is][\color{red}]{~}{~}
  45. }
  46. \newtheorem{theorem}{Theorem}
  47. \newtheorem{lemma}[theorem]{Lemma}
  48. \newtheorem{corollary}[theorem]{Corollary}
  49. \newtheorem{proposition}[theorem]{Proposition}
  50. \newtheorem{constraint}[theorem]{Constraint}
  51. \newtheorem{definition}[theorem]{Definition}
  52. \newtheorem{exercise}[theorem]{Exercise}
  53. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  54. % 'dedication' environment: To add a dedication paragraph at the start of book %
  55. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  56. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  57. \newenvironment{dedication}
  58. {
  59. \cleardoublepage
  60. \thispagestyle{empty}
  61. \vspace*{\stretch{1}}
  62. \hfill\begin{minipage}[t]{0.66\textwidth}
  63. \raggedright
  64. }
  65. {
  66. \end{minipage}
  67. \vspace*{\stretch{3}}
  68. \clearpage
  69. }
  70. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  71. % Chapter quote at the start of chapter %
  72. % Source: http://tex.stackexchange.com/a/53380 %
  73. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  74. \makeatletter
  75. \renewcommand{\@chapapp}{}% Not necessary...
  76. \newenvironment{chapquote}[2][2em]
  77. {\setlength{\@tempdima}{#1}%
  78. \def\chapquote@author{#2}%
  79. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  80. \itshape}
  81. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  82. \makeatother
  83. \input{defs}
  84. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  85. \title{\Huge \textbf{Essentials of Compilation} \\
  86. \huge An Incremental Approach}
  87. \author{\textsc{Jeremy G. Siek, Ryan R. Newton} \\
  88. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  89. Indiana University \\
  90. \\
  91. with contributions from: \\
  92. Carl Factora \\
  93. Andre Kuhlenschmidt \\
  94. Michael M. Vitousek \\
  95. Michael Vollmer \\
  96. Ryan Scott \\
  97. Cameron Swords
  98. }
  99. \begin{document}
  100. \frontmatter
  101. \maketitle
  102. \begin{dedication}
  103. This book is dedicated to the programming language wonks at Indiana
  104. University.
  105. \end{dedication}
  106. \tableofcontents
  107. \listoffigures
  108. %\listoftables
  109. \mainmatter
  110. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  111. \chapter*{Preface}
  112. The tradition of compiler writing at Indiana University goes back to
  113. research and courses about programming languages by Daniel Friedman in
  114. the 1970's and 1980's. Dan had conducted research on lazy
  115. evaluation~\citep{Friedman:1976aa} in the context of
  116. Lisp~\citep{McCarthy:1960dz} and then studied
  117. continuations~\citep{Felleisen:kx} and
  118. macros~\citep{Kohlbecker:1986dk} in the context of the
  119. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  120. of those courses, Kent Dybvig, went on to build Chez
  121. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  122. compiler for Scheme. After completing his Ph.D. at the University of
  123. North Carolina, Kent returned to teach at Indiana University.
  124. Throughout the 1990's and 2000's, Kent continued development of Chez
  125. Scheme and taught the compiler course.
  126. The compiler course evolved to incorporate novel pedagogical ideas
  127. while also including elements of effective real-world compilers. One
  128. of Dan's ideas was to split the compiler into many small ``passes'' so
  129. that the code for each pass would be easy to understood in isolation.
  130. (In contrast, most compilers of the time were organized into only a
  131. few monolithic passes for reasons of compile-time efficiency.) Kent,
  132. with later help from his students Dipanwita Sarkar and Andrew Keep,
  133. developed infrastructure to support this approach and evolved the
  134. course, first to use micro-sized passes and then into even smaller
  135. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  136. student in this compiler course in the early 2000's, as part of his
  137. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  138. the course immensely!
  139. One of Jeremy's classmates, Abdulaziz Ghuloum, observed that the
  140. front-to-back organization of the course made it difficult for
  141. students to understand the rationale for the compiler
  142. design. Abdulaziz proposed an incremental approach in which the
  143. students build the compiler in stages; they start by implementing a
  144. complete compiler for a very small subset of the input language, then
  145. in each subsequent stage they add a feature to the input language and
  146. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  147. In this way, the students see how the language features motivate
  148. aspects of the compiler design.
  149. After graduating from Indiana University in 2005, Jeremy went on to
  150. teach at the University of Colorado. He adapted the nano pass and
  151. incremental approaches to compiling a subset of the Python
  152. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  153. on the surface but there is a large overlap in the compiler techniques
  154. required for the two languages. Thus, Jeremy was able to teach much of
  155. the same content from the Indiana compiler course. He very much
  156. enjoyed teaching the course organized in this way, and even better,
  157. many of the students learned a lot and got excited about compilers.
  158. Jeremy returned to teach at Indiana University in 2013. In his
  159. absence the compiler course had switched from the front-to-back
  160. organization to a back-to-front organization. Seeing how well the
  161. incremental approach worked at Colorado, he started porting and
  162. adapting the structure of the Colorado course back into the land of
  163. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  164. the course is now about compiling a subset of Racket (and Typed
  165. Racket) to the x86 assembly language. The compiler is implemented in
  166. Racket~\citep{plt-tr}.
  167. This is the textbook for the incremental version of the compiler
  168. course at Indiana University (Spring 2016 - present) and it is the
  169. first open textbook for an Indiana compiler course. With this book we
  170. hope to make the Indiana compiler course available to people that have
  171. not had the chance to study in Bloomington in person. Many of the
  172. compiler design decisions in this book are drawn from the assignment
  173. descriptions of \cite{Dybvig:2010aa}. We have captured what we think are
  174. the most important topics from \cite{Dybvig:2010aa} but we have omitted
  175. topics that we think are less interesting conceptually and we have made
  176. simplifications to reduce complexity. In this way, this book leans
  177. more towards pedagogy than towards the absolute efficiency of the
  178. generated code. Also, the book differs in places where we saw the
  179. opportunity to make the topics more fun, such as in relating register
  180. allocation to Sudoku (Chapter~\ref{ch:register-allocation}).
  181. \section*{Prerequisites}
  182. The material in this book is challenging but rewarding. It is meant to
  183. prepare students for a lifelong career in programming languages. We do
  184. not recommend this book for students who want to dabble in programming
  185. languages.
  186. The book uses the Racket language both for the implementation of the
  187. compiler and for the language that is compiled, so a student should be
  188. proficient with Racket (or Scheme) prior to reading this book. There
  189. are many other excellent resources for learning Scheme and
  190. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  191. is helpful but not necessary for the student to have prior exposure to
  192. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  193. obtain from a computer systems
  194. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  195. parts of x86-64 assembly language that are needed.
  196. %\section*{Structure of book}
  197. % You might want to add short description about each chapter in this book.
  198. %\section*{About the companion website}
  199. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  200. %\begin{itemize}
  201. % \item A link to (freely downlodable) latest version of this document.
  202. % \item Link to download LaTeX source for this document.
  203. % \item Miscellaneous material (e.g. suggested readings etc).
  204. %\end{itemize}
  205. \section*{Acknowledgments}
  206. Many people have contributed to the ideas, techniques, organization,
  207. and teaching of the materials in this book. We especially thank the
  208. following people.
  209. \begin{itemize}
  210. \item Bor-Yuh Evan Chang
  211. \item Kent Dybvig
  212. \item Daniel P. Friedman
  213. \item Ronald Garcia
  214. \item Abdulaziz Ghuloum
  215. \item Jay McCarthy
  216. \item Dipanwita Sarkar
  217. \item Andrew Keep
  218. \item Oscar Waddell
  219. \item Michael Wollowski
  220. \end{itemize}
  221. \mbox{}\\
  222. \noindent Jeremy G. Siek \\
  223. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  224. %\noindent Spring 2016
  225. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  226. \chapter{Preliminaries}
  227. \label{ch:trees-recur}
  228. In this chapter, we review the basic tools that are needed for implementing a
  229. compiler. We use abstract syntax trees (ASTs), which refer to data structures in
  230. the compilers memory, rather than programs as they are stored on disk, in
  231. \emph{concrete syntax}.
  232. %
  233. ASTs can be represented in many different ways, depending on the programming
  234. language used to write the compiler.
  235. %
  236. Because this book uses Racket (\url{http://racket-lang.org}), a
  237. descendant of Lisp, we use S-expressions to represent programs
  238. (Section~\ref{sec:ast}). We use grammars to defined programming languages
  239. (Section~\ref{sec:grammar}) and pattern matching to inspect
  240. individual nodes in an AST (Section~\ref{sec:pattern-matching}). We
  241. use recursion to construct and deconstruct entire ASTs
  242. (Section~\ref{sec:recursion}). This chapter provides an brief
  243. introduction to these ideas.
  244. \section{Abstract Syntax Trees and S-expressions}
  245. \label{sec:ast}
  246. The primary data structure that is commonly used for representing
  247. programs is the \emph{abstract syntax tree} (AST). When considering
  248. some part of a program, a compiler needs to ask what kind of part it
  249. is and what sub-parts it has. For example, the program on the left,
  250. represented by an S-expression, corresponds to the AST on the right.
  251. \begin{center}
  252. \begin{minipage}{0.4\textwidth}
  253. \begin{lstlisting}
  254. (+ (read) (- 8))
  255. \end{lstlisting}
  256. \end{minipage}
  257. \begin{minipage}{0.4\textwidth}
  258. \begin{equation}
  259. \begin{tikzpicture}
  260. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  261. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  262. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  263. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  264. \draw[->] (plus) to (read);
  265. \draw[->] (plus) to (minus);
  266. \draw[->] (minus) to (8);
  267. \end{tikzpicture}
  268. \label{eq:arith-prog}
  269. \end{equation}
  270. \end{minipage}
  271. \end{center}
  272. We shall use the standard terminology for trees: each circle above is
  273. called a \emph{node}. The arrows connect a node to its \emph{children}
  274. (which are also nodes). The top-most node is the \emph{root}. Every
  275. node except for the root has a \emph{parent} (the node it is the child
  276. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  277. it is an \emph{internal} node.
  278. Recall that an \emph{symbolic expression} (S-expression) is either
  279. \begin{enumerate}
  280. \item an atom, or
  281. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  282. where $e_1$ and $e_2$ are each an S-expression.
  283. \end{enumerate}
  284. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the null
  285. value \code{'()}, etc.
  286. We can create an S-expression in Racket simply by writing a backquote
  287. (called a quasi-quote in Racket).
  288. followed by the textual representation of the S-expression.
  289. It is quite common to use S-expressions
  290. to represent a list, such as $a, b ,c$ in the following way:
  291. \begin{lstlisting}
  292. `(a . (b . (c . ())))
  293. \end{lstlisting}
  294. Each element of the list is in the first slot of a pair, and the
  295. second slot is either the rest of the list or the null value, to mark
  296. the end of the list. Such lists are so common that Racket provides
  297. special notation for them that removes the need for the periods
  298. and so many parenthesis:
  299. \begin{lstlisting}
  300. `(a b c)
  301. \end{lstlisting}
  302. For another example,
  303. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  304. by the following Racket expression:
  305. \begin{center}
  306. \texttt{`(+ (read) (- 8))}
  307. \end{center}
  308. When using S-expressions to represent ASTs, the convention is to
  309. represent each AST node as a list and to put the operation symbol at
  310. the front of the list. The rest of the list contains the children. So
  311. in the above case, the root AST node has operation \code{`+} and its
  312. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  313. diagram \eqref{eq:arith-prog}.
  314. To build larger S-expressions one often needs to splice together
  315. several smaller S-expressions. Racket provides the comma operator to
  316. splice an S-expression into a larger one. For example, instead of
  317. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  318. we could have first created an S-expression for AST
  319. \eqref{eq:arith-neg8} and then spliced that into the addition
  320. S-expression.
  321. \begin{lstlisting}
  322. (define ast1.4 `(- 8))
  323. (define ast1.1 `(+ (read) ,ast1.4))
  324. \end{lstlisting}
  325. In general, the Racket expression that follows the comma (splice)
  326. can be any expression that computes an S-expression.
  327. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  328. know that the operation associated with the root node is addition and
  329. that it has two children: \texttt{read} and a negation. The AST data
  330. structure directly supports these queries, as we shall see in
  331. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  332. in compilers. In this book, we will often write down the S-expression
  333. representation of a program even when we really have in mind the AST
  334. because the S-expression is more concise. We recommend that, in your
  335. mind, you always think of programs as abstract syntax trees.
  336. \section{Grammars}
  337. \label{sec:grammar}
  338. A programming language can be thought of as a \emph{set} of programs.
  339. The set is typically infinite (one can always create larger and larger
  340. programs), so one cannot simply describe a language by listing all of
  341. the programs in the language. Instead we write down a set of rules, a
  342. \emph{grammar}, for building programs. We shall write our rules in a
  343. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  344. As an example, we describe a small language, named $R_0$, of
  345. integers and arithmetic operations. The first rule says that any
  346. integer is an expression, $\Exp$, in the language:
  347. \begin{equation}
  348. \Exp ::= \Int \label{eq:arith-int}
  349. \end{equation}
  350. %
  351. Each rule has a left-hand-side and a right-hand-side. The way to read
  352. a rule is that if you have all the program parts on the
  353. right-hand-side, then you can create an AST node and categorize it
  354. according to the left-hand-side.
  355. %
  356. A name such as $\Exp$ that is
  357. defined by the grammar rules is a \emph{non-terminal}.
  358. %
  359. The name $\Int$ is a also a non-terminal, however,
  360. we do not define $\Int$ because the
  361. reader already knows what an integer is.
  362. %
  363. Further, we make the simplifying design decision that all of the languages in
  364. this book only handle machine-representable integers. On most modern machines
  365. this corresponds to integers represented with 64-bits, i.e., the in range
  366. $-2^{63}$ to $2^{63}-1$.
  367. %
  368. However, we restrict this range further to match the Racket \texttt{fixnum}
  369. datatype, which allows 63-bit integers on a 64-bit machine.
  370. The second grammar rule is the \texttt{read} operation that receives
  371. an input integer from the user of the program.
  372. \begin{equation}
  373. \Exp ::= (\key{read}) \label{eq:arith-read}
  374. \end{equation}
  375. The third rule says that, given an $\Exp$ node, you can build another
  376. $\Exp$ node by negating it.
  377. \begin{equation}
  378. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  379. \end{equation}
  380. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  381. and must literally appear in the program for the rule to be
  382. applicable.
  383. We can apply the rules to build ASTs in the $R_0$
  384. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  385. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  386. an $\Exp$.
  387. \begin{center}
  388. \begin{minipage}{0.25\textwidth}
  389. \begin{lstlisting}
  390. (- 8)
  391. \end{lstlisting}
  392. \end{minipage}
  393. \begin{minipage}{0.25\textwidth}
  394. \begin{equation}
  395. \begin{tikzpicture}
  396. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  397. \node[draw, circle] (8) at (0, -1.2) {$8$};
  398. \draw[->] (minus) to (8);
  399. \end{tikzpicture}
  400. \label{eq:arith-neg8}
  401. \end{equation}
  402. \end{minipage}
  403. \end{center}
  404. The following grammar rule defines addition expressions:
  405. \begin{equation}
  406. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  407. \end{equation}
  408. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  409. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  410. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  411. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  412. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  413. If you have an AST for which the above rules do not apply, then the
  414. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  415. not in $R_0$ because there are no rules for \key{+} with only one
  416. argument, nor for \key{-} with two arguments. Whenever we define a
  417. language with a grammar, we implicitly mean for the language to be the
  418. smallest set of programs that are justified by the rules. That is, the
  419. language only includes those programs that the rules allow.
  420. The last grammar rule for $R_0$ states that there is a \key{program}
  421. node to mark the top of the whole program:
  422. \[
  423. R_0 ::= (\key{program} \; \Exp)
  424. \]
  425. The \code{read-program} function provided in \code{utilities.rkt}
  426. reads programs in from a file (the sequence of characters in the
  427. concrete syntax of Racket) and parses them into the abstract syntax
  428. tree. The concrete syntax does not include a \key{program} form; that
  429. is added by the \code{read-program} function as it creates the
  430. AST. See the description of \code{read-program} in
  431. Appendix~\ref{appendix:utilities} for more details.
  432. It is common to have many rules with the same left-hand side, such as
  433. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  434. for gathering several rules, as shown in
  435. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  436. called an {\em alternative}.
  437. \begin{figure}[tp]
  438. \fbox{
  439. \begin{minipage}{0.96\textwidth}
  440. \[
  441. \begin{array}{rcl}
  442. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  443. (\key{+} \; \Exp \; \Exp) \\
  444. R_0 &::=& (\key{program} \; \Exp)
  445. \end{array}
  446. \]
  447. \end{minipage}
  448. }
  449. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  450. \label{fig:r0-syntax}
  451. \end{figure}
  452. \section{Pattern Matching}
  453. \label{sec:pattern-matching}
  454. As mentioned above, one of the operations that a compiler needs to
  455. perform on an AST is to access the children of a node. Racket
  456. provides the \texttt{match} form to access the parts of an
  457. S-expression. Consider the following example and the output on the
  458. right.
  459. \begin{center}
  460. \begin{minipage}{0.5\textwidth}
  461. \begin{lstlisting}
  462. (match ast1.1
  463. [`(,op ,child1 ,child2)
  464. (print op) (newline)
  465. (print child1) (newline)
  466. (print child2)])
  467. \end{lstlisting}
  468. \end{minipage}
  469. \vrule
  470. \begin{minipage}{0.25\textwidth}
  471. \begin{lstlisting}
  472. '+
  473. '(read)
  474. '(- 8)
  475. \end{lstlisting}
  476. \end{minipage}
  477. \end{center}
  478. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  479. parts to the three variables \texttt{op}, \texttt{child1}, and
  480. \texttt{child2}. In general, a match clause consists of a
  481. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  482. that may contain pattern-variables (each one preceded by a comma).
  483. %
  484. The pattern is not the same thing as a quasiquote expression used to
  485. \emph{construct} ASTs, however, the similarity is intentional: constructing and
  486. deconstructing ASTs uses similar syntax.
  487. %
  488. While the pattern uses a restricted syntax,
  489. the body of the match clause may contain any Racket code whatsoever.
  490. A \texttt{match} form may contain several clauses, as in the following
  491. function \texttt{leaf?} that recognizes when an $R_0$ node is
  492. a leaf. The \texttt{match} proceeds through the clauses in order,
  493. checking whether the pattern can match the input S-expression. The
  494. body of the first clause that matches is executed. The output of
  495. \texttt{leaf?} for several S-expressions is shown on the right. In the
  496. below \texttt{match}, we see another form of pattern: the \texttt{(?
  497. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  498. S-expression to see if it is a machine-representable integer.
  499. \begin{center}
  500. \begin{minipage}{0.5\textwidth}
  501. \begin{lstlisting}
  502. (define (leaf? arith)
  503. (match arith
  504. [(? fixnum?) #t]
  505. [`(read) #t]
  506. [`(- ,c1) #f]
  507. [`(+ ,c1 ,c2) #f]))
  508. (leaf? `(read))
  509. (leaf? `(- 8))
  510. (leaf? `(+ (read) (- 8)))
  511. \end{lstlisting}
  512. \end{minipage}
  513. \vrule
  514. \begin{minipage}{0.25\textwidth}
  515. \begin{lstlisting}
  516. #t
  517. #f
  518. #f
  519. \end{lstlisting}
  520. \end{minipage}
  521. \end{center}
  522. \section{Recursion}
  523. \label{sec:recursion}
  524. Programs are inherently recursive in that an $R_0$ expression ($\Exp$)
  525. is made up of smaller expressions. Thus, the natural way to process an
  526. entire program is with a recursive function. As a first example of
  527. such a function, we define \texttt{exp?} below, which takes an
  528. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  529. sexp} is an $R_0$ expression. Note that each match clause
  530. corresponds to one grammar rule the body of each clause makes a
  531. recursive call for each child node. This pattern of recursive function
  532. is so common that it has a name, \emph{structural recursion}. In
  533. general, when a recursive function is defined using a sequence of
  534. match clauses that correspond to a grammar, and each clause body makes
  535. a recursive call on each child node, then we say the function is
  536. defined by structural recursion. Below we also define a second
  537. function, named \code{R0?}, determines whether an S-expression is an
  538. $R_0$ program.
  539. %
  540. \begin{center}
  541. \begin{minipage}{0.7\textwidth}
  542. \begin{lstlisting}
  543. (define (exp? sexp)
  544. (match sexp
  545. [(? fixnum?) #t]
  546. [`(read) #t]
  547. [`(- ,e) (exp? e)]
  548. [`(+ ,e1 ,e2)
  549. (and (exp? e1) (exp? e2))]
  550. [else #f]))
  551. (define (R0? sexp)
  552. (match sexp
  553. [`(program ,e) (exp? e)]
  554. [else #f]))
  555. (R0? `(program (+ (read) (- 8))))
  556. (R0? `(program (- (read) (+ 8))))
  557. \end{lstlisting}
  558. \end{minipage}
  559. \vrule
  560. \begin{minipage}{0.25\textwidth}
  561. \begin{lstlisting}
  562. #t
  563. #f
  564. \end{lstlisting}
  565. \end{minipage}
  566. \end{center}
  567. Indeed, the structural recursion follows the grammar itself. We can
  568. generally expect to write a recursive function to handle each
  569. non-terminal in the grammar.\footnote{This principle of structuring
  570. code according to the data definition is advocated in the book
  571. \emph{How to Design Programs}
  572. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}
  573. You may be tempted to write the program with just one function, like this:
  574. \begin{center}
  575. \begin{minipage}{0.5\textwidth}
  576. \begin{lstlisting}
  577. (define (R0? sexp)
  578. (match sexp
  579. [(? fixnum?) #t]
  580. [`(read) #t]
  581. [`(- ,e) (R0? e)]
  582. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  583. [`(program ,e) (R0? e)]
  584. [else #f]))
  585. \end{lstlisting}
  586. \end{minipage}
  587. \end{center}
  588. %
  589. Sometimes such a trick will save a few lines of code, especially when it comes
  590. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  591. recommended because it can get you into trouble.
  592. %
  593. For instance, the above function is subtly wrong:
  594. \lstinline{(R0? `(program (program 3)))} will return true, when it
  595. should return false.
  596. %% NOTE FIXME - must check for consistency on this issue throughout.
  597. \section{Interpreters}
  598. \label{sec:interp-R0}
  599. The meaning, or semantics, of a program is typically defined in the
  600. specification of the language. For example, the Scheme language is
  601. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  602. defined in its reference manual~\citep{plt-tr}. In this book we use an
  603. interpreter to define the meaning of each language that we consider,
  604. following Reynold's advice in this
  605. regard~\citep{reynolds72:_def_interp}. Here we warm up by writing an
  606. interpreter for the $R_0$ language, which serves as a second example
  607. of structural recursion. The \texttt{interp-R0} function is defined in
  608. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  609. input program \texttt{p} and then a call to the \lstinline{interp-exp}
  610. helper function, which in turn has one match clause per grammar rule
  611. for $R_0$ expressions.
  612. \begin{figure}[tbp]
  613. \begin{lstlisting}
  614. (define (interp-exp e)
  615. (match e
  616. [(? fixnum?) e]
  617. [`(read)
  618. (let ([r (read)])
  619. (cond [(fixnum? r) r]
  620. [else (error 'interp-R0 "input not an integer" r)]))]
  621. [`(- ,e1) (fx- 0 (interp-exp e1))]
  622. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]
  623. ))
  624. (define (interp-R0 p)
  625. (match p
  626. [`(program ,e) (interp-exp e)]))
  627. \end{lstlisting}
  628. \caption{Interpreter for the $R_0$ language.}
  629. \label{fig:interp-R0}
  630. \end{figure}
  631. Let us consider the result of interpreting a few $R_0$ programs. The
  632. following program simply adds two integers.
  633. \begin{lstlisting}
  634. (+ 10 32)
  635. \end{lstlisting}
  636. The result is \key{42}, as you might have expected. Here we have written the
  637. program in concrete syntax, whereas the parsed abstract syntax would be the
  638. slightly different: \lstinline{(program (+ 10 32))}.
  639. The next example demonstrates that expressions may be nested within
  640. each other, in this case nesting several additions and negations.
  641. \begin{lstlisting}
  642. (+ 10 (- (+ 12 20)))
  643. \end{lstlisting}
  644. What is the result of the above program?
  645. As mentioned previously, the $R0$ language does not support
  646. arbitrarily-large integers, but only $63$-bit integers, so we
  647. interpret the arithmetic operations of $R0$ using fixnum arithmetic.
  648. What happens when we run the following program?
  649. \begin{lstlisting}
  650. (define large 999999999999999999)
  651. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  652. (+ (+ ,large ,large) (+ ,large ,large)))))
  653. \end{lstlisting}
  654. It produces an error:
  655. \begin{lstlisting}
  656. fx+: result is not a fixnum
  657. \end{lstlisting}
  658. We shall use the convention that if the interpreter for a language
  659. produces an error when run on a program, then the meaning of the
  660. program is unspecified. The compiler for the language is under no
  661. obligation for such a program; it can produce an executable that does
  662. anything.
  663. \noindent
  664. Moving on, the \key{read} operation prompts the user of the program
  665. for an integer. If we interpret the AST \eqref{eq:arith-prog} and give
  666. it the input \texttt{50}
  667. \begin{lstlisting}
  668. (interp-R0 ast1.1)
  669. \end{lstlisting}
  670. we get the answer to life, the universe, and everything:
  671. \begin{lstlisting}
  672. 42
  673. \end{lstlisting}
  674. We include the \key{read} operation in $R_0$ so a clever student
  675. cannot implement a compiler for $R_0$ simply by running the
  676. interpreter at compilation time to obtain the output and then
  677. generating the trivial code to return the output. (A clever student
  678. did this in a previous version of the course.)
  679. The job of a compiler is to translate a program in one language into a
  680. program in another language so that the output program behaves the
  681. same way as the input program. This idea is depicted in the following
  682. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  683. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  684. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  685. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  686. and $P_2$ on their respective interpreters with input $i$ should yield
  687. the same output $o$.
  688. \begin{equation} \label{eq:compile-correct}
  689. \begin{tikzpicture}[baseline=(current bounding box.center)]
  690. \node (p1) at (0, 0) {$P_1$};
  691. \node (p2) at (3, 0) {$P_2$};
  692. \node (o) at (3, -2.5) {$o$};
  693. \path[->] (p1) edge [above] node {compile} (p2);
  694. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  695. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  696. \end{tikzpicture}
  697. \end{equation}
  698. In the next section we see our first example of a compiler, which is
  699. another example of structural recursion.
  700. \section{Example Compiler: a Partial Evaluator}
  701. \label{sec:partial-evaluation}
  702. In this section we consider a compiler that translates $R_0$
  703. programs into $R_0$ programs that are more efficient, that is,
  704. this compiler is an optimizer. Our optimizer will accomplish this by
  705. trying to eagerly compute the parts of the program that do not depend
  706. on any inputs. For example, given the following program
  707. \begin{lstlisting}
  708. (+ (read) (- (+ 5 3)))
  709. \end{lstlisting}
  710. our compiler will translate it into the program
  711. \begin{lstlisting}
  712. (+ (read) -8)
  713. \end{lstlisting}
  714. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  715. evaluator for the $R_0$ language. The output of the partial evaluator
  716. is an $R_0$ program, which we build up using a combination of
  717. quasiquotes and commas. (Though no quasiquote is necessary for
  718. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  719. recursion is captured in the main \texttt{pe-arith} function whereas
  720. the code for partially evaluating negation and addition is factored
  721. into two separate helper functions: \texttt{pe-neg} and
  722. \texttt{pe-add}. The input to these helper functions is the output of
  723. partially evaluating the children nodes.
  724. \begin{figure}[tbp]
  725. \begin{lstlisting}
  726. (define (pe-neg r)
  727. (cond [(fixnum? r) (fx- 0 r)]
  728. [else `(- ,r)]))
  729. (define (pe-add r1 r2)
  730. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  731. [else `(+ ,r1 ,r2)]))
  732. (define (pe-arith e)
  733. (match e
  734. [(? fixnum?) e]
  735. [`(read) `(read)]
  736. [`(- ,(app pe-arith r1))
  737. (pe-neg r1)]
  738. [`(+ ,(app pe-arith r1) ,(app pe-arith r2))
  739. (pe-add r1 r2)]))
  740. \end{lstlisting}
  741. \caption{A partial evaluator for $R_0$ expressions.}
  742. \label{fig:pe-arith}
  743. \end{figure}
  744. Note that in the recursive cases in \code{pe-arith} for negation and
  745. addition, we have made use of the \key{app} feature of Racket's
  746. \key{match} to apply a function and bind the result. Here we use
  747. \lstinline{(app pe-arith r1)} to recursively apply \texttt{pe-arith}
  748. to the child node and bind the \emph{result value} to variable
  749. \texttt{r1}. The choice of whether to use \key{app} is mainly
  750. stylistic, although if side effects are involved the change in order
  751. of evaluation may be in issue. Further, when we write functions with
  752. multiple return values, the \key{app} form can be convenient for
  753. binding the resulting values.
  754. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  755. idea of checking whether the inputs are integers and if they are, to
  756. go ahead and perform the arithmetic. Otherwise, we use quasiquote to
  757. create an AST node for the appropriate operation (either negation or
  758. addition) and use comma to splice in the child nodes.
  759. To gain some confidence that the partial evaluator is correct, we can
  760. test whether it produces programs that get the same result as the
  761. input program. That is, we can test whether it satisfies Diagram
  762. \eqref{eq:compile-correct}. The following code runs the partial
  763. evaluator on several examples and tests the output program. The
  764. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  765. \begin{lstlisting}
  766. (define (test-pe p)
  767. (assert "testing pe-arith"
  768. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  769. (test-pe `(+ (read) (- (+ 5 3))))
  770. (test-pe `(+ 1 (+ (read) 1)))
  771. (test-pe `(- (+ (read) (- 5))))
  772. \end{lstlisting}
  773. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  774. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  775. \begin{exercise}
  776. \normalfont % I don't like the italics for exercises. -Jeremy
  777. We challenge the reader to improve on the simple partial evaluator in
  778. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  779. \texttt{pe-add} helper functions with functions that know more about
  780. arithmetic. For example, your partial evaluator should translate
  781. \begin{lstlisting}
  782. (+ 1 (+ (read) 1))
  783. \end{lstlisting}
  784. into
  785. \begin{lstlisting}
  786. (+ 2 (read))
  787. \end{lstlisting}
  788. To accomplish this, we recommend that your partial evaluator produce
  789. output that takes the form of the $\itm{residual}$ non-terminal in the
  790. following grammar.
  791. \[
  792. \begin{array}{lcl}
  793. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  794. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  795. \end{array}
  796. \]
  797. \end{exercise}
  798. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  799. \chapter{Integers and Variables}
  800. \label{ch:int-exp}
  801. This chapter concerns the challenge of compiling a subset of Racket
  802. that includes integer arithmetic and local variable binding, which we
  803. name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. Henceforth
  804. we shall refer to x86-64 simply as x86. The chapter begins with a
  805. description of the $R_1$ language (Section~\ref{sec:s0}) followed by a
  806. description of x86 (Section~\ref{sec:x86}). The x86 assembly language
  807. is quite large, so we only discuss what is needed for compiling
  808. $R_1$. We introduce more of x86 in later chapters. Once we have
  809. introduced $R_1$ and x86, we reflect on their differences and come up
  810. with a plan to break down the translation from $R_1$ to x86 into a
  811. handful of steps (Section~\ref{sec:plan-s0-x86}). The rest of the
  812. sections in this Chapter give detailed hints regarding each step
  813. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  814. to give enough hints that the well-prepared reader can implement a
  815. compiler from $R_1$ to x86 while at the same time leaving room for
  816. some fun and creativity.
  817. \section{The $R_1$ Language}
  818. \label{sec:s0}
  819. The $R_1$ language extends the $R_0$ language
  820. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  821. the $R_1$ language is defined by the grammar in
  822. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  823. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  824. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  825. the $R_1$ language includes the \key{program} form to mark the top of
  826. the program, which is helpful in some of the compiler passes. The
  827. $R_1$ language is rich enough to exhibit several compilation
  828. techniques but simple enough so that the reader, together with couple
  829. friends, can implement a compiler for it in a week or two of part-time
  830. work. To give the reader a feeling for the scale of this first
  831. compiler, the instructor solution for the $R_1$ compiler consists of 6
  832. recursive functions and a few small helper functions that together
  833. span 256 lines of code.
  834. \begin{figure}[btp]
  835. \centering
  836. \fbox{
  837. \begin{minipage}{0.96\textwidth}
  838. \[
  839. \begin{array}{rcl}
  840. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  841. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  842. R_1 &::=& (\key{program} \; \Exp)
  843. \end{array}
  844. \]
  845. \end{minipage}
  846. }
  847. \caption{The syntax of $R_1$, a language of integers and variables.}
  848. \label{fig:r1-syntax}
  849. \end{figure}
  850. Let us dive into the description of the $R_1$ language. The \key{let}
  851. construct defines a variable for use within its body and initializes
  852. the variable with the value of an expression. So the following
  853. program initializes \code{x} to \code{32} and then evaluates the body
  854. \code{(+ 10 x)}, producing \code{42}.
  855. \begin{lstlisting}
  856. (program
  857. (let ([x (+ 12 20)]) (+ 10 x)))
  858. \end{lstlisting}
  859. When there are multiple \key{let}'s for the same variable, the closest
  860. enclosing \key{let} is used. That is, variable definitions overshadow
  861. prior definitions. Consider the following program with two \key{let}'s
  862. that define variables named \code{x}. Can you figure out the result?
  863. \begin{lstlisting}
  864. (program
  865. (let ([x 32]) (+ (let ([x 10]) x) x)))
  866. \end{lstlisting}
  867. For the purposes of showing which variable uses correspond to which
  868. definitions, the following shows the \code{x}'s annotated with subscripts
  869. to distinguish them. Double check that your answer for the above is
  870. the same as your answer for this annotated version of the program.
  871. \begin{lstlisting}
  872. (program
  873. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  874. \end{lstlisting}
  875. The initializing expression is always evaluated before the body of the
  876. \key{let}, so in the following, the \key{read} for \code{x} is
  877. performed before the \key{read} for \code{y}. Given the input
  878. \code{52} then \code{10}, the following produces \code{42} (and not
  879. \code{-42}).
  880. \begin{lstlisting}
  881. (program
  882. (let ([x (read)]) (let ([y (read)]) (- x y))))
  883. \end{lstlisting}
  884. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  885. language. It extends the interpreter for $R_0$ with two new
  886. \key{match} clauses for variables and for \key{let}. For \key{let},
  887. we will need a way to communicate the initializing value of a variable
  888. to all the uses of a variable. To accomplish this, we maintain a
  889. mapping from variables to values, which is traditionally called an
  890. \emph{environment}. For simplicity, here we use an association list to
  891. represent the environment. The \code{interp-R1} function takes the
  892. current environment, \code{env}, as an extra parameter. When the
  893. interpreter encounters a variable, it finds the corresponding value
  894. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  895. When the interpreter encounters a \key{let}, it evaluates the
  896. initializing expression, extends the environment with the result bound
  897. to the variable, then evaluates the body of the \key{let}.
  898. \begin{figure}[tbp]
  899. \begin{lstlisting}
  900. (define (interp-exp env)
  901. (lambda (e)
  902. (match e
  903. [(? fixnum?) e]
  904. [`(read)
  905. (define r (read))
  906. (cond [(fixnum? r) r]
  907. [else (error 'interp-R1 "expected an integer" r)])]
  908. [`(- ,(app (interp-exp env) v))
  909. (fx- 0 v)]
  910. [`(+ ,(app (interp-exp env) v1) ,(app (interp-exp env) v2))
  911. (fx+ v1 v2)]
  912. [(? symbol?) (lookup e env)]
  913. [`(let ([,x ,(app (interp-exp env) v)]) ,body)
  914. (define new-env (cons (cons x v) env))
  915. ((interp-exp new-env) body)]
  916. )))
  917. (define (interp-R1 env)
  918. (lambda (p)
  919. (match p
  920. [`(program ,e) ((interp-exp '()) e)])))
  921. \end{lstlisting}
  922. \caption{Interpreter for the $R_1$ language.}
  923. \label{fig:interp-R1}
  924. \end{figure}
  925. The goal for this chapter is to implement a compiler that translates
  926. any program $P_1$ in the $R_1$ language into an x86 assembly
  927. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  928. computer as the $R_1$ program running in a Racket implementation.
  929. That is, they both output the same integer $n$.
  930. \[
  931. \begin{tikzpicture}[baseline=(current bounding box.center)]
  932. \node (p1) at (0, 0) {$P_1$};
  933. \node (p2) at (4, 0) {$P_2$};
  934. \node (o) at (4, -2) {$n$};
  935. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  936. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  937. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  938. \end{tikzpicture}
  939. \]
  940. In the next section we introduce enough of the x86 assembly
  941. language to compile $R_1$.
  942. \section{The x86 Assembly Language}
  943. \label{sec:x86}
  944. An x86 program is a sequence of instructions. The program is stored in the
  945. computer's memory and the \emph{program counter} points to the address of the
  946. next instruction to be executed. For most instructions, once the instruction is
  947. executed, the program counter is incremented to point to the immediately
  948. following instruction in memory. Each instruction may refer to integer
  949. constants (called \emph{immediate values}), variables called \emph{registers},
  950. and instructions may load and store values into memory. For our purposes, we
  951. can think of the computer's memory as a mapping of 64-bit addresses to 64-bit
  952. %
  953. values\footnote{This simple story doesn't fully cover contemporary x86
  954. processors, which combine multiple processing cores per silicon chip, together
  955. with hardware memory caches. The result is that, at some instants in real
  956. time, different threads of program execution may hold conflicting
  957. cached values for a given memory address.}.
  958. %
  959. Figure~\ref{fig:x86-a} defines the syntax for the
  960. subset of the x86 assembly language needed for this chapter.
  961. %
  962. (We use the AT\&T syntax expected by the GNU assembler that comes with the C
  963. compiler that we use in this course: \key{gcc}.)
  964. %
  965. Also, Appendix~\ref{sec:x86-quick-reference} includes a quick-reference of all
  966. the x86 instructions used in this book and a short explanation of what they do.
  967. % to do: finish treatment of imulq
  968. % it's needed for vector's in R6/R7
  969. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  970. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  971. && \key{r8} \mid \key{r9} \mid \key{r10}
  972. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  973. \mid \key{r14} \mid \key{r15}}
  974. \begin{figure}[tp]
  975. \fbox{
  976. \begin{minipage}{0.96\textwidth}
  977. \[
  978. \begin{array}{lcl}
  979. \Reg &::=& \allregisters{} \\
  980. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  981. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  982. \key{subq} \; \Arg, \Arg \mid
  983. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  984. && \key{callq} \; \mathit{label} \mid
  985. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  986. \Prog &::= & \key{.globl main}\\
  987. & & \key{main:} \; \Instr^{+}
  988. \end{array}
  989. \]
  990. \end{minipage}
  991. }
  992. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  993. \label{fig:x86-a}
  994. \end{figure}
  995. An immediate value is written using the notation \key{\$}$n$ where $n$
  996. is an integer.
  997. %
  998. A register is written with a \key{\%} followed by the register name,
  999. such as \key{\%rax}.
  1000. %
  1001. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1002. which obtains the address stored in register $r$ and then
  1003. offsets the address by $n$ bytes
  1004. (8 bits). The address is then used to either load or store to memory
  1005. depending on whether it occurs as a source or destination argument of
  1006. an instruction.
  1007. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  1008. source $s$ and destination $d$, applies the arithmetic operation, then
  1009. writes the result in $d$.
  1010. %
  1011. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  1012. result in $d$.
  1013. %
  1014. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1015. specified by the label.
  1016. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1017. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1018. \key{main} procedure is externally visible, which is necessary so
  1019. that the operating system can call it. The label \key{main:}
  1020. indicates the beginning of the \key{main} procedure which is where
  1021. the operating system starts executing this program. The instruction
  1022. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1023. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1024. $10$ in \key{rax} and puts the result, $42$, back into
  1025. \key{rax}.
  1026. The last instruction, \key{retq}, finishes the \key{main} function by
  1027. returning the integer in \key{rax} to the operating system. The
  1028. operating system interprets this integer as the program's exit
  1029. code. By convention, an exit code of 0 indicates the program was
  1030. successful, and all other exit codes indicate various errors.
  1031. Nevertheless, we return the result of the program as the exit code.
  1032. %\begin{wrapfigure}{r}{2.25in}
  1033. \begin{figure}[tbp]
  1034. \begin{lstlisting}
  1035. .globl main
  1036. main:
  1037. movq $10, %rax
  1038. addq $32, %rax
  1039. retq
  1040. \end{lstlisting}
  1041. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1042. \label{fig:p0-x86}
  1043. %\end{wrapfigure}
  1044. \end{figure}
  1045. Unfortunately, x86 varies in a couple ways depending on what operating
  1046. system it is assembled in. The code examples shown here are correct on
  1047. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1048. labels like \key{main} must be prefixed with an underscore. So the
  1049. correct output for the above program on Mac would begin with:
  1050. \begin{lstlisting}
  1051. .globl _main
  1052. _main:
  1053. ...
  1054. \end{lstlisting}
  1055. We exhibit the use of memory for storing intermediate results in the
  1056. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1057. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1058. region of memory called the \emph{procedure call stack} (or
  1059. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1060. for each procedure call. The memory layout for an individual frame is
  1061. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1062. \emph{stack pointer} and points to the item at the top of the
  1063. stack. The stack grows downward in memory, so we increase the size of
  1064. the stack by subtracting from the stack pointer. The frame size is
  1065. required to be a multiple of 16 bytes. In the context of a procedure
  1066. call, the \emph{return address} is the next instruction on the caller
  1067. side that comes after the call instruction. During a function call,
  1068. the return address is pushed onto the stack. The register \key{rbp}
  1069. is the \emph{base pointer} which serves two purposes: 1) it saves the
  1070. location of the stack pointer for the calling procedure and 2) it is
  1071. used to access variables associated with the current procedure. The
  1072. base pointer of the calling procedure is pushed onto the stack after
  1073. the return address. We number the variables from $1$ to $n$. Variable
  1074. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1075. $-16\key{(\%rbp)}$, etc.
  1076. \begin{figure}[tbp]
  1077. \begin{lstlisting}
  1078. .globl main
  1079. main:
  1080. pushq %rbp
  1081. movq %rsp, %rbp
  1082. subq $16, %rsp
  1083. movq $10, -8(%rbp)
  1084. negq -8(%rbp)
  1085. movq $52, %rax
  1086. addq -8(%rbp), %rax
  1087. addq $16, %rsp
  1088. popq %rbp
  1089. retq
  1090. \end{lstlisting}
  1091. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1092. \label{fig:p1-x86}
  1093. \end{figure}
  1094. \begin{figure}[tbp]
  1095. \centering
  1096. \begin{tabular}{|r|l|} \hline
  1097. Position & Contents \\ \hline
  1098. 8(\key{\%rbp}) & return address \\
  1099. 0(\key{\%rbp}) & old \key{rbp} \\
  1100. -8(\key{\%rbp}) & variable $1$ \\
  1101. -16(\key{\%rbp}) & variable $2$ \\
  1102. \ldots & \ldots \\
  1103. 0(\key{\%rsp}) & variable $n$\\ \hline
  1104. \end{tabular}
  1105. \caption{Memory layout of a frame.}
  1106. \label{fig:frame}
  1107. \end{figure}
  1108. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1109. three instructions are the typical \emph{prelude} for a procedure.
  1110. The instruction \key{pushq \%rbp} saves the base pointer for the
  1111. procedure that called the current one onto the stack and subtracts $8$
  1112. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  1113. changes the base pointer to the top of the stack. The instruction
  1114. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1115. room for storing variables. This program just needs one variable ($8$
  1116. bytes) but because the frame size is required to be a multiple of 16
  1117. bytes, it rounds to 16 bytes.
  1118. The next four instructions carry out the work of computing
  1119. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  1120. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  1121. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  1122. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  1123. adds the contents of variable $1$ to \key{rax}, at which point
  1124. \key{rax} contains $42$.
  1125. The next two instructions print the final result of the program.
  1126. The last four instructions are the typical \emph{conclusion} of a
  1127. procedure. The first three are necessary to get the state of the
  1128. machine back to where it was before the current procedure was called.
  1129. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  1130. point at the old base pointer. The amount added here needs to match
  1131. the amount that was subtracted in the prelude of the procedure. The
  1132. \key{movq \$0, \%rax} instruction ensures that the returned exit code
  1133. is 0. Then \key{popq \%rbp} returns the old base pointer to \key{rbp}
  1134. and adds $8$ to the stack pointer. The \key{retq} instruction jumps
  1135. back to the procedure that called this one and adds 8 to the stack
  1136. pointer, returning the stack pointer to where it was prior to the
  1137. procedure call.
  1138. The compiler will need a convenient representation for manipulating
  1139. x86 programs, so we define an abstract syntax for x86 in
  1140. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1141. a subscript $0$ because later we introduce extended versions of this
  1142. assembly language. The $\Int$ field of the \key{program} AST node
  1143. records the number of bytes of stack space needed for variables in the
  1144. program. (Some of the intermediate languages will store other
  1145. information in that part of the S-expression for the purposes of
  1146. communicating auxiliary data from one step of the compiler to the
  1147. next.
  1148. \begin{figure}[tp]
  1149. \fbox{
  1150. \begin{minipage}{0.96\textwidth}
  1151. \[
  1152. \begin{array}{lcl}
  1153. \itm{register} &::=& \allregisters{} \\
  1154. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1155. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1156. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1157. (\key{subq} \; \Arg\; \Arg) \mid
  1158. (\key{movq} \; \Arg\; \Arg) \mid
  1159. (\key{retq})\\
  1160. &\mid& (\key{negq} \; \Arg) \mid
  1161. (\key{callq} \; \mathit{label}) \mid
  1162. (\key{pushq}\;\Arg) \mid
  1163. (\key{popq}\;\Arg) \\
  1164. x86_0 &::= & (\key{program} \;\Int \; \Instr^{+})
  1165. \end{array}
  1166. \]
  1167. \end{minipage}
  1168. }
  1169. \caption{Abstract syntax for $x86_0$ assembly.}
  1170. \label{fig:x86-ast-a}
  1171. \end{figure}
  1172. \section{Planning the trip to x86 via the $C_0$ language}
  1173. \label{sec:plan-s0-x86}
  1174. To compile one language to another it helps to focus on the
  1175. differences between the two languages. It is these differences that
  1176. the compiler will need to bridge. What are the differences between
  1177. $R_1$ and x86 assembly? Here we list some of the most important ones.
  1178. \begin{enumerate}
  1179. \item[(a)] x86 arithmetic instructions typically have two arguments
  1180. and update the second argument in place. In contrast, $R_1$
  1181. arithmetic operations take two arguments and produce a new value.
  1182. An x86 instruction may have at most one memory-accessing argument.
  1183. Some instructions place custom restrictions on the kinds of
  1184. their arguments.
  1185. \item[(b)] An argument to an $R_1$ operator can be any expression,
  1186. whereas x86 instructions restrict their arguments to \emph{simple
  1187. expression} like integers, registers, and memory locations.
  1188. (All other kinds of expressions are called \emph{complex}.)
  1189. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1190. sequence of instructions, whereas in $R_1$ it is a left-to-right
  1191. depth-first traversal of the abstract syntax tree.
  1192. \item[(d)] An $R_1$ program can have any number of variables whereas
  1193. x86 has only 16 registers.
  1194. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1195. same name. The registers and memory locations of x86 all have unique
  1196. names.
  1197. \end{enumerate}
  1198. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1199. the problem into several steps, dealing with the above differences one
  1200. at a time. The main question then becomes: in what order do we tackle
  1201. these differences? This can be a challenging question for a compiler
  1202. writer to answer because some orderings may be much more difficult to
  1203. implement than others. It is difficult to know ahead of time which
  1204. orders will be better so often some trial-and-error is
  1205. involved. However, we can try to plan ahead and choose the orderings
  1206. based on this planning.
  1207. % (e) uniquify
  1208. % (b) rco
  1209. % (c) explicate-control
  1210. % (a) instr-sel.
  1211. % (d) assign-homes (register allocation)
  1212. % (e) -> (b)
  1213. For example, to handle difference (b) (nested expressions), we shall
  1214. introduce temporary variables to hold the intermediate results of each
  1215. complex subexpression. To deal with (e) (variable overshadowing) we
  1216. shall renaming variables to make sure they have unique names. The
  1217. plan for (b) involves moving expressions, which could change the
  1218. shadowing of variables. However, if we deal with (e) first, then
  1219. shadowing will not be an issue. Of course, this means that during (b),
  1220. when we insert temporary variables, we need to make sure that they are
  1221. unique.
  1222. % (c) -> (a)
  1223. To handle difference (c) (order of execution), we shall transform the
  1224. program into a control flow graph: each vertex is a basic block,
  1225. within which the order of execution is sequential. At the end of each
  1226. block there is a jump to one or two other blocks, which form the edges
  1227. of the graph. We need to handle this difference prior to (a)
  1228. (operations vs. instructions) because it will determine where we need
  1229. to generate x86 labels and jump instructions.
  1230. % (e),(b) -> (c)
  1231. With respect to (e) and (b), it perhaps does not matter very much
  1232. whether (c) comes before or after them. We find it convenient to place
  1233. (c) after (e) and (b).
  1234. % (b) -> (d), (c) -> (d)
  1235. To deal with difference (d) we replace variables with registers and
  1236. stack locations. Thus, it makes sense to deal with (b) before (d) so
  1237. that (d) can replace both the original variables and the temporary
  1238. variables generated in dealing with (b). Also, it's good to handle (c)
  1239. before (d) because while analyzing the control flow, we sometimes
  1240. notice that some code and the variables it uses are unnecessary, so we
  1241. can remove them which speeds up (d).
  1242. % (a) -> (d)
  1243. Last but not least, we need to decide on the ordering of (a)
  1244. (selecting instructions) and (d) (mapping variables to stack locations
  1245. and registers). These two issues are intertwined, creating a bit of a
  1246. Gordian Knot. To handle difference (d), we need to map some variables
  1247. to registers (there are only 16 registers) and the remaining variables
  1248. to locations on the stack (which is unbounded). But recall that x86
  1249. instructions have restrictions about which of their arguments can be
  1250. registers versus memory accesses (stack locations). So to make good
  1251. decisions regarding this mapping, it is helpful to know which
  1252. instructions use which variables. On the other hand,
  1253. We cut this knot by doing an optimistic selection of instructions in
  1254. the \key{select-instructions} pass, followed by the \key{assign-homes}
  1255. pass to map variables to registers or stack locations, and conclude by
  1256. finalizing the instruction selection in the \key{patch-instructions}
  1257. pass.
  1258. [ordering of reg. alloc versus instr. sel? -jeremy]
  1259. \[
  1260. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1261. \foreach \i/\p in {1/1,2/2,3/3,4/4,5/5,6/6}
  1262. {
  1263. \node (\i) at (\p*1.5,0) {$\bullet$};
  1264. }
  1265. \foreach \x/\y/\lbl in {1/2/e,2/3/b,3/4/c,4/5/a,5/6/d}
  1266. {
  1267. \path[->,bend left=15] (\x) edge [above] node {\small\lbl} (\y);
  1268. }
  1269. \end{tikzpicture}
  1270. \]
  1271. We further simplify the translation from $R_1$ to x86 by identifying
  1272. an intermediate language named $C_0$, roughly half-way between $R_1$
  1273. and x86, to provide a rest stop along the way. We name the language
  1274. $C_0$ because it is vaguely similar to the $C$
  1275. language~\citep{Kernighan:1988nx}. The differences (e) and (a),
  1276. regarding variables and nested expressions, will be handled by two
  1277. steps, \key{uniquify} and \key{flatten}, which bring us to
  1278. $C_0$.
  1279. \[
  1280. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1281. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1282. {
  1283. \node (\p) at (\p*3,0) {\large $\i$};
  1284. }
  1285. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1286. {
  1287. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1288. }
  1289. \end{tikzpicture}
  1290. \]
  1291. Each of these steps in the compiler is implemented by a function,
  1292. typically a structurally recursive function that translates an input
  1293. AST into an output AST. We refer to such a function as a \emph{pass}
  1294. because it makes a pass over, i.e. it traverses, the entire AST.
  1295. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1296. $C_0$ language supports the same operators as $R_1$ but the arguments
  1297. of operators are now restricted to just variables and integers, so all
  1298. intermediate results are bound to variables. In the literature this
  1299. style of intermediate language is called administrative normal form,
  1300. or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}. The \key{let}
  1301. construct of $R_1$ is replaced by an assignment statement and there is
  1302. a \key{return} construct to specify the return value of the program. A
  1303. program consists of a sequence of statements that include at least one
  1304. \key{return} statement. Each program is also annotated with a list of
  1305. variables (viz. {\tt (var*)}). At the start of the program, these
  1306. variables are uninitialized (they contain garbage) and each variable
  1307. becomes initialized on its first assignment. All of the variables used
  1308. in the program must be present in this list exactly once.
  1309. \begin{figure}[tp]
  1310. \fbox{
  1311. \begin{minipage}{0.96\textwidth}
  1312. \[
  1313. \begin{array}{lcl}
  1314. \Arg &::=& \Int \mid \Var \\
  1315. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1316. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1317. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1318. \end{array}
  1319. \]
  1320. \end{minipage}
  1321. }
  1322. \caption{The $C_0$ intermediate language.}
  1323. \label{fig:c0-syntax}
  1324. \end{figure}
  1325. To get from $C_0$ to x86 assembly, it remains for us to handle
  1326. difference (a) (the format of instructions) and difference (d)
  1327. (variables versus stack locations and registers). These two
  1328. differences are intertwined, creating a bit of a Gordian Knot. To
  1329. handle difference (d), we need to map some variables to registers
  1330. (there are only 16 registers) and the remaining variables to locations
  1331. on the stack (which is unbounded). To make good decisions regarding
  1332. this mapping, we need the program to be close to its final form (in
  1333. x86 assembly) so we know exactly when which variables are used. After
  1334. all, variables that are used at different time periods during program
  1335. execution can be assigned to the same register. However, our choice
  1336. of x86 instructions depends on whether the variables are mapped to
  1337. registers or stack locations, so we have a circular dependency. We cut
  1338. this knot by doing an optimistic selection of instructions in the
  1339. \key{select-instructions} pass, followed by the \key{assign-homes}
  1340. pass to map variables to registers or stack locations, and conclude by
  1341. finalizing the instruction selection in the \key{patch-instructions}
  1342. pass.
  1343. \[
  1344. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1345. \node (1) at (0,0) {\large $C_0$};
  1346. \node (2) at (3,0) {\large $\text{x86}^{*}_0$};
  1347. \node (3) at (6,0) {\large $\text{x86}^{*}_0$};
  1348. \node (4) at (9,0) {\large $\text{x86}_0$};
  1349. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1350. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1351. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1352. \end{tikzpicture}
  1353. \]
  1354. The \key{select-instructions} pass is optimistic in the sense that it
  1355. treats variables as if they were all mapped to registers. The
  1356. \key{select-instructions} pass generates a program that consists of
  1357. x86 instructions but that still uses variables, so it is an
  1358. intermediate language that is technically different than x86, which
  1359. explains the asterisks in the diagram above.
  1360. In this Chapter we shall take the easy road to implementing
  1361. \key{assign-homes} and simply map all variables to stack locations.
  1362. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1363. smarter approach in which we make a best-effort to map variables to
  1364. registers, resorting to the stack only when necessary.
  1365. Once variables have been assigned to their homes, we can finalize the
  1366. instruction selection by dealing with an idiosyncrasy of x86
  1367. assembly. Many x86 instructions have two arguments but only one of the
  1368. arguments may be a memory reference (and the stack is a part of
  1369. memory). Because some variables may get mapped to stack locations,
  1370. some of our generated instructions may violate this restriction. The
  1371. purpose of the \key{patch-instructions} pass is to fix this problem by
  1372. replacing every violating instruction with a short sequence of
  1373. instructions that use the \key{rax} register. Once we have implemented
  1374. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1375. need to patch instructions will be relatively rare.
  1376. \section{Uniquify Variables}
  1377. \label{sec:uniquify-s0}
  1378. The purpose of this pass is to make sure that each \key{let} uses a
  1379. unique variable name. For example, the \code{uniquify} pass should
  1380. translate the program on the left into the program on the right. \\
  1381. \begin{tabular}{lll}
  1382. \begin{minipage}{0.4\textwidth}
  1383. \begin{lstlisting}
  1384. (program
  1385. (let ([x 32])
  1386. (+ (let ([x 10]) x) x)))
  1387. \end{lstlisting}
  1388. \end{minipage}
  1389. &
  1390. $\Rightarrow$
  1391. &
  1392. \begin{minipage}{0.4\textwidth}
  1393. \begin{lstlisting}
  1394. (program
  1395. (let ([x.1 32])
  1396. (+ (let ([x.2 10]) x.2) x.1)))
  1397. \end{lstlisting}
  1398. \end{minipage}
  1399. \end{tabular} \\
  1400. %
  1401. The following is another example translation, this time of a program
  1402. with a \key{let} nested inside the initializing expression of another
  1403. \key{let}.\\
  1404. \begin{tabular}{lll}
  1405. \begin{minipage}{0.4\textwidth}
  1406. \begin{lstlisting}
  1407. (program
  1408. (let ([x (let ([x 4])
  1409. (+ x 1))])
  1410. (+ x 2)))
  1411. \end{lstlisting}
  1412. \end{minipage}
  1413. &
  1414. $\Rightarrow$
  1415. &
  1416. \begin{minipage}{0.4\textwidth}
  1417. \begin{lstlisting}
  1418. (program
  1419. (let ([x.2 (let ([x.1 4])
  1420. (+ x.1 1))])
  1421. (+ x.2 2)))
  1422. \end{lstlisting}
  1423. \end{minipage}
  1424. \end{tabular}
  1425. We recommend implementing \code{uniquify} as a structurally recursive
  1426. function that mostly copies the input program. However, when
  1427. encountering a \key{let}, it should generate a unique name for the
  1428. variable (the Racket function \code{gensym} is handy for this) and
  1429. associate the old name with the new unique name in an association
  1430. list. The \code{uniquify} function will need to access this
  1431. association list when it gets to a variable reference, so we add
  1432. another parameter to \code{uniquify} for the association list. It is
  1433. quite common for a compiler pass to need a map to store extra
  1434. information about variables. Such maps are often called \emph{symbol
  1435. tables}.
  1436. The skeleton of the \code{uniquify} function is shown in
  1437. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1438. convenient to partially apply it to an association list and then apply
  1439. it to different expressions, as in the last clause for primitive
  1440. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1441. clause for the primitive operators, note the use of the comma-@
  1442. operator to splice a list of S-expressions into an enclosing
  1443. S-expression.
  1444. \begin{exercise}
  1445. \normalfont % I don't like the italics for exercises. -Jeremy
  1446. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1447. implement the clauses for variables and for the \key{let} construct.
  1448. \end{exercise}
  1449. \begin{figure}[tbp]
  1450. \begin{lstlisting}
  1451. (define (uniquify-exp alist)
  1452. (lambda (e)
  1453. (match e
  1454. [(? symbol?) ___]
  1455. [(? integer?) e]
  1456. [`(let ([,x ,e]) ,body) ___]
  1457. [`(,op ,es ...)
  1458. `(,op ,@(map (uniquify-exp alist) es))]
  1459. )))
  1460. (define (uniquify alist)
  1461. (lambda (e)
  1462. (match e
  1463. [`(program ,e)
  1464. `(program ,((uniquify-exp alist) e))]
  1465. )))
  1466. \end{lstlisting}
  1467. \caption{Skeleton for the \key{uniquify} pass.}
  1468. \label{fig:uniquify-s0}
  1469. \end{figure}
  1470. \begin{exercise}
  1471. \normalfont % I don't like the italics for exercises. -Jeremy
  1472. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1473. and checking whether the output programs produce the same result as
  1474. the input programs. The $R_1$ programs should be designed to test the
  1475. most interesting parts of the \key{uniquify} pass, that is, the
  1476. programs should include \key{let} constructs, variables, and variables
  1477. that overshadow each other. The five programs should be in a
  1478. subdirectory named \key{tests} and they should have the same file name
  1479. except for a different integer at the end of the name, followed by the
  1480. ending \key{.rkt}. Use the \key{interp-tests} function
  1481. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1482. your \key{uniquify} pass on the example programs.
  1483. \end{exercise}
  1484. \section{Flatten Expressions}
  1485. \label{sec:flatten-r1}
  1486. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1487. programs. In particular, the purpose of the \code{flatten} pass is to
  1488. get rid of nested expressions, such as the \code{(- 10)} in the program
  1489. below. This can be accomplished by introducing a new variable,
  1490. assigning the nested expression to the new variable, and then using
  1491. the new variable in place of the nested expressions, as shown in the
  1492. output of \code{flatten} on the right.\\
  1493. \begin{tabular}{lll}
  1494. \begin{minipage}{0.4\textwidth}
  1495. \begin{lstlisting}
  1496. (program
  1497. (+ 52 (- 10)))
  1498. \end{lstlisting}
  1499. \end{minipage}
  1500. &
  1501. $\Rightarrow$
  1502. &
  1503. \begin{minipage}{0.4\textwidth}
  1504. \begin{lstlisting}
  1505. (program (tmp.1 tmp.2)
  1506. (assign tmp.1 (- 10))
  1507. (assign tmp.2 (+ 52 tmp.1))
  1508. (return tmp.2))
  1509. \end{lstlisting}
  1510. \end{minipage}
  1511. \end{tabular}
  1512. The clause of \code{flatten} for \key{let} is straightforward to
  1513. implement as it just requires the generation of an assignment
  1514. statement for the \key{let}-bound variable. The following shows the
  1515. result of \code{flatten} for a \key{let}. \\
  1516. \begin{tabular}{lll}
  1517. \begin{minipage}{0.4\textwidth}
  1518. \begin{lstlisting}
  1519. (program
  1520. (let ([x (+ (- 10) 11)])
  1521. (+ x 41)))
  1522. \end{lstlisting}
  1523. \end{minipage}
  1524. &
  1525. $\Rightarrow$
  1526. &
  1527. \begin{minipage}{0.4\textwidth}
  1528. \begin{lstlisting}
  1529. (program (tmp.1 x tmp.2)
  1530. (assign tmp.1 (- 10))
  1531. (assign x (+ tmp.1 11))
  1532. (assign tmp.2 (+ x 41))
  1533. (return tmp.2))
  1534. \end{lstlisting}
  1535. \end{minipage}
  1536. \end{tabular}
  1537. We recommend implementing a helper function,
  1538. \key{flatten-exp}, as a structurally recursive
  1539. function that takes an expression in $R_1$ and
  1540. returns three things: 1) the newly flattened expression,
  1541. 2) a list of assignment statements, one for each of the new variables
  1542. introduced during the flattening the expression, and 3) a list of all
  1543. the variables including both let-bound variables and the generated
  1544. temporary variables. The newly flattened expression should be an
  1545. $\Arg$ in the $C_0$ syntax (Figure~\ref{fig:c0-syntax}), that is, it
  1546. should be an integer or a variable. You can return multiple things
  1547. from a function using the \key{values} form and you can receive
  1548. multiple things from a function call using the \key{define-values}
  1549. form. If you are not familiar with these constructs, the Racket
  1550. documentation will be of help.
  1551. Also, the \key{map3} function
  1552. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1553. to each element of a list, in the case where the function returns
  1554. three values. The result of \key{map3} is three lists.
  1555. \begin{tabular}{lll}
  1556. \begin{minipage}{0.4\textwidth}
  1557. \begin{lstlisting}
  1558. (flatten-exp `(+ 52 (- 10)))
  1559. \end{lstlisting}
  1560. \end{minipage}
  1561. &
  1562. $\Rightarrow$
  1563. &
  1564. \begin{minipage}{0.4\textwidth}
  1565. \begin{lstlisting}
  1566. (values 'tmp.2
  1567. '((assign tmp.1 (- 10))
  1568. (assign tmp.2 (+ 52 tmp.1)))
  1569. '(tmp.1 tmp.2))
  1570. \end{lstlisting}
  1571. \end{minipage}
  1572. \end{tabular}
  1573. The clause of \key{flatten} for the \key{program} node needs to
  1574. apply this helper function to the body of the program and the newly flattened
  1575. expression should be placed in a \key{return} statement. Remember that
  1576. the variable list in the \key{program} node should contain no duplicates.
  1577. %% The
  1578. %% \key{flatten} pass should also compute the list of variables used in
  1579. %% the program.
  1580. %% I recommend traversing the statements in the body of the
  1581. %% program (after it has been flattened) and collect all variables that
  1582. %% appear on the left-hand-side of an assignment.
  1583. %% Note that each variable
  1584. %% should only occur once in the list of variables that you place in the
  1585. %% \key{program} form.
  1586. Take special care for programs such as the following that initialize
  1587. variables with integers or other variables. It should be translated
  1588. to the program on the right \\
  1589. \begin{tabular}{lll}
  1590. \begin{minipage}{0.4\textwidth}
  1591. \begin{lstlisting}
  1592. (let ([a 42])
  1593. (let ([b a])
  1594. b))
  1595. \end{lstlisting}
  1596. \end{minipage}
  1597. &
  1598. $\Rightarrow$
  1599. &
  1600. \begin{minipage}{0.4\textwidth}
  1601. \begin{lstlisting}
  1602. (program (a b)
  1603. (assign a 42)
  1604. (assign b a)
  1605. (return b))
  1606. \end{lstlisting}
  1607. \end{minipage}
  1608. \end{tabular} \\
  1609. and not to the following, which could result from a naive
  1610. implementation of \key{flatten}.
  1611. \begin{lstlisting}
  1612. (program (tmp.1 a tmp.2 b)
  1613. (assign tmp.1 42)
  1614. (assign a tmp.1)
  1615. (assign tmp.2 a)
  1616. (assign b tmp.2)
  1617. (return b))
  1618. \end{lstlisting}
  1619. \begin{exercise}
  1620. \normalfont
  1621. Implement the \key{flatten} pass and test it on all of the example
  1622. programs that you created to test the \key{uniquify} pass and create
  1623. three new example programs that are designed to exercise all of the
  1624. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1625. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1626. test your passes on the example programs.
  1627. \end{exercise}
  1628. \section{Select Instructions}
  1629. \label{sec:select-s0}
  1630. In the \key{select-instructions} pass we begin the work of translating
  1631. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1632. language that still uses variables, so we add an AST node of the form
  1633. $\VAR{\itm{var}}$ to the x86 abstract syntax. Also, the \key{program}
  1634. form should still list the variables (similar to $C_0$):
  1635. \[
  1636. (\key{program}\;(\Var^{*})\;\Instr^{+})
  1637. \]
  1638. The \key{select-instructions} pass deals with the differing format of
  1639. arithmetic operations. For example, in $C_0$ an addition operation can
  1640. take the form below. To translate to x86, we need to use the
  1641. \key{addq} instruction which does an in-place update. So we must first
  1642. move \code{10} to \code{x}. \\
  1643. \begin{tabular}{lll}
  1644. \begin{minipage}{0.4\textwidth}
  1645. \begin{lstlisting}
  1646. (assign x (+ 10 32))
  1647. \end{lstlisting}
  1648. \end{minipage}
  1649. &
  1650. $\Rightarrow$
  1651. &
  1652. \begin{minipage}{0.4\textwidth}
  1653. \begin{lstlisting}
  1654. (movq (int 10) (var x))
  1655. (addq (int 32) (var x))
  1656. \end{lstlisting}
  1657. \end{minipage}
  1658. \end{tabular} \\
  1659. There are some cases that require special care to avoid generating
  1660. needlessly complicated code. If one of the arguments is the same as
  1661. the left-hand side of the assignment, then there is no need for the
  1662. extra move instruction. For example, the following assignment
  1663. statement can be translated into a single \key{addq} instruction.\\
  1664. \begin{tabular}{lll}
  1665. \begin{minipage}{0.4\textwidth}
  1666. \begin{lstlisting}
  1667. (assign x (+ 10 x))
  1668. \end{lstlisting}
  1669. \end{minipage}
  1670. &
  1671. $\Rightarrow$
  1672. &
  1673. \begin{minipage}{0.4\textwidth}
  1674. \begin{lstlisting}
  1675. (addq (int 10) (var x))
  1676. \end{lstlisting}
  1677. \end{minipage}
  1678. \end{tabular} \\
  1679. The \key{read} operation does not have a direct counterpart in x86
  1680. assembly, so we have instead implemented this functionality in the C
  1681. language, with the function \code{read\_int} in the file
  1682. \code{runtime.c}. In general, we refer to all of the functionality in
  1683. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1684. for short. When compiling your generated x86 assembly code, you
  1685. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1686. file'', using \code{gcc} option \code{-c}) and link it into the final
  1687. executable. For our purposes of code generation, all you need to do is
  1688. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1689. (for left-hand side) into a call to the \code{read\_int} function
  1690. followed by a move from \code{rax} to the left-hand side. The move
  1691. from \code{rax} is needed because the return value from
  1692. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1693. \begin{tabular}{lll}
  1694. \begin{minipage}{0.4\textwidth}
  1695. \begin{lstlisting}
  1696. (assign |$\itm{lhs}$| (read))
  1697. \end{lstlisting}
  1698. \end{minipage}
  1699. &
  1700. $\Rightarrow$
  1701. &
  1702. \begin{minipage}{0.4\textwidth}
  1703. \begin{lstlisting}
  1704. (callq read_int)
  1705. (movq (reg rax) (var |$\itm{lhs}$|))
  1706. \end{lstlisting}
  1707. \end{minipage}
  1708. \end{tabular} \\
  1709. Regarding the \RETURN{\Arg} statement of $C_0$, we recommend treating it
  1710. as an assignment to the \key{rax} register and let the procedure
  1711. conclusion handle the transfer of control back to the calling
  1712. procedure.
  1713. \begin{exercise}
  1714. \normalfont
  1715. Implement the \key{select-instructions} pass and test it on all of the
  1716. example programs that you created for the previous passes and create
  1717. three new example programs that are designed to exercise all of the
  1718. interesting code in this pass. Use the \key{interp-tests} function
  1719. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1720. your passes on the example programs.
  1721. \end{exercise}
  1722. \section{Assign Homes}
  1723. \label{sec:assign-s0}
  1724. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1725. \key{assign-homes} pass places all of the variables on the stack.
  1726. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1727. which after \key{select-instructions} looks like the following.
  1728. \begin{lstlisting}
  1729. (movq (int 10) (var tmp.1))
  1730. (negq (var tmp.1))
  1731. (movq (var tmp.1) (var tmp.2))
  1732. (addq (int 52) (var tmp.2))
  1733. (movq (var tmp.2) (reg rax)))
  1734. \end{lstlisting}
  1735. The variable \code{tmp.1} is assigned to stack location
  1736. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1737. the \code{assign-homes} pass translates the above to
  1738. \begin{lstlisting}
  1739. (movq (int 10) (deref rbp -8))
  1740. (negq (deref rbp -8))
  1741. (movq (deref rbp -8) (deref rbp -16))
  1742. (addq (int 52) (deref rbp -16))
  1743. (movq (deref rbp -16) (reg rax)))
  1744. \end{lstlisting}
  1745. In the process of assigning stack locations to variables, it is
  1746. convenient to compute and store the size of the frame (in bytes) in
  1747. the first field of the \key{program} node which will be needed later
  1748. to generate the procedure conclusion.
  1749. \[
  1750. (\key{program}\;\Int\;\Instr^{+})
  1751. \]
  1752. Some operating systems place restrictions on
  1753. the frame size. For example, Mac OS X requires the frame size to be a
  1754. multiple of 16 bytes.
  1755. \begin{exercise}
  1756. \normalfont Implement the \key{assign-homes} pass and test it on all
  1757. of the example programs that you created for the previous passes pass.
  1758. We recommend that \key{assign-homes} take an extra parameter that is a
  1759. mapping of variable names to homes (stack locations for now). Use the
  1760. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1761. \key{utilities.rkt} to test your passes on the example programs.
  1762. \end{exercise}
  1763. \section{Patch Instructions}
  1764. \label{sec:patch-s0}
  1765. The purpose of this pass is to make sure that each instruction adheres
  1766. to the restrictions regarding which arguments can be memory
  1767. references. For most instructions, the rule is that at most one
  1768. argument may be a memory reference.
  1769. Consider again the following example.
  1770. \begin{lstlisting}
  1771. (let ([a 42])
  1772. (let ([b a])
  1773. b))
  1774. \end{lstlisting}
  1775. After \key{assign-homes} pass, the above has been translated to
  1776. \begin{lstlisting}
  1777. (movq (int 42) (deref rbp -8))
  1778. (movq (deref rbp -8) (deref rbp -16))
  1779. (movq (deref rbp -16) (reg rax))
  1780. \end{lstlisting}
  1781. The second \key{movq} instruction is problematic because both
  1782. arguments are stack locations. We suggest fixing this problem by
  1783. moving from the source to the register \key{rax} and then from
  1784. \key{rax} to the destination, as follows.
  1785. \begin{lstlisting}
  1786. (movq (int 42) (deref rbp -8))
  1787. (movq (deref rbp -8) (reg rax))
  1788. (movq (reg rax) (deref rbp -16))
  1789. (movq (deref rbp -16) (reg rax))
  1790. \end{lstlisting}
  1791. \begin{exercise}
  1792. \normalfont
  1793. Implement the \key{patch-instructions} pass and test it on all of the
  1794. example programs that you created for the previous passes and create
  1795. three new example programs that are designed to exercise all of the
  1796. interesting code in this pass. Use the \key{interp-tests} function
  1797. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1798. your passes on the example programs.
  1799. \end{exercise}
  1800. \section{Print x86}
  1801. \label{sec:print-x86}
  1802. The last step of the compiler from $R_1$ to x86 is to convert the x86
  1803. AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1804. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1805. \key{format} and \key{string-append} functions are useful in this
  1806. regard. The main work that this step needs to perform is to create the
  1807. \key{main} function and the standard instructions for its prelude and
  1808. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1809. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1810. variables, so we suggest computing it in the \key{assign-homes} pass
  1811. (Section~\ref{sec:assign-s0}) and storing it in the $\itm{info}$ field
  1812. of the \key{program} node.
  1813. Your compiled code should print the result of the program's execution
  1814. by using the \code{print\_int} function provided in
  1815. \code{runtime.c}. If your compiler has been implemented correctly so
  1816. far, this final result should be stored in the \key{rax} register.
  1817. We'll talk more about how to perform function calls with arguments in
  1818. general later on, but for now, place the following after the compiled
  1819. code for the $R_1$ program but before the conclusion:
  1820. \begin{lstlisting}
  1821. movq %rax, %rdi
  1822. callq print_int
  1823. \end{lstlisting}
  1824. These lines move the value in \key{rax} into the \key{rdi} register, which
  1825. stores the first argument to be passed into \key{print\_int}.
  1826. If you want your program to run on Mac OS X, your code needs to
  1827. determine whether or not it is running on a Mac, and prefix
  1828. underscores to labels like \key{main}. You can determine the platform
  1829. with the Racket call \code{(system-type 'os)}, which returns
  1830. \code{'macosx}, \code{'unix}, or \code{'windows}. In addition to
  1831. placing underscores on \key{main}, you need to put them in front of
  1832. \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1833. \_print\_int}).
  1834. \begin{exercise}
  1835. \normalfont Implement the \key{print-x86} pass and test it on all of
  1836. the example programs that you created for the previous passes. Use the
  1837. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1838. \key{utilities.rkt} to test your complete compiler on the example
  1839. programs.
  1840. % The following is specific to P423/P523. -Jeremy
  1841. %Mac support is optional, but your compiler has to output
  1842. %valid code for Unix machines.
  1843. \end{exercise}
  1844. \begin{figure}[p]
  1845. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1846. \node (R1) at (0,2) {\large $R_1$};
  1847. \node (R1-2) at (3,2) {\large $R_1$};
  1848. \node (R1-3) at (6,2) {\large $R_1$};
  1849. \node (C0-1) at (6,0) {\large $C_0$};
  1850. \node (C0-2) at (3,0) {\large $C_0$};
  1851. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1852. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1853. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1854. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1855. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1856. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1857. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  1858. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1859. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1860. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1861. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1862. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1863. \end{tikzpicture}
  1864. \caption{Overview of the passes for compiling $R_1$. }
  1865. \label{fig:R1-passes}
  1866. \end{figure}
  1867. Figure~\ref{fig:R1-passes} provides an overview of all the compiler
  1868. passes described in this Chapter. The x86$^{*}$ language extends x86
  1869. with variables and looser rules regarding instruction arguments. The
  1870. x86$^{\dagger}$ language is the concrete syntax (string) for x86.
  1871. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1872. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1873. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1874. \chapter{Register Allocation}
  1875. \label{ch:register-allocation}
  1876. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1877. assembly by placing all variables on the stack. We can improve the
  1878. performance of the generated code considerably if we instead try to
  1879. place as many variables as possible into registers. The CPU can
  1880. access a register in a single cycle, whereas accessing the stack takes
  1881. many cycles to go to cache or many more to access main memory.
  1882. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1883. serves as a running example. We show the source program and also the
  1884. output of instruction selection. At that point the program is almost
  1885. x86 assembly but not quite; it still contains variables instead of
  1886. stack locations or registers.
  1887. \begin{figure}
  1888. \begin{minipage}{0.45\textwidth}
  1889. Source program:
  1890. \begin{lstlisting}
  1891. (program
  1892. (let ([v 1])
  1893. (let ([w 46])
  1894. (let ([x (+ v 7)])
  1895. (let ([y (+ 4 x)])
  1896. (let ([z (+ x w)])
  1897. (+ z (- y))))))))
  1898. \end{lstlisting}
  1899. \end{minipage}
  1900. \begin{minipage}{0.45\textwidth}
  1901. After instruction selection:
  1902. \begin{lstlisting}
  1903. (program (v w x y z t.1 t.2)
  1904. (movq (int 1) (var v))
  1905. (movq (int 46) (var w))
  1906. (movq (var v) (var x))
  1907. (addq (int 7) (var x))
  1908. (movq (var x) (var y))
  1909. (addq (int 4) (var y))
  1910. (movq (var x) (var z))
  1911. (addq (var w) (var z))
  1912. (movq (var y) (var t.1))
  1913. (negq (var t.1))
  1914. (movq (var z) (var t.2))
  1915. (addq (var t.1) (var t.2))
  1916. (movq (var t.2) (reg rax)))
  1917. \end{lstlisting}
  1918. \end{minipage}
  1919. \caption{An example program for register allocation.}
  1920. \label{fig:reg-eg}
  1921. \end{figure}
  1922. The goal of register allocation is to fit as many variables into
  1923. registers as possible. It is often the case that we have more
  1924. variables than registers, so we cannot map each variable to a
  1925. different register. Fortunately, it is common for different variables
  1926. to be needed during different periods of time, and in such cases
  1927. several variables can be mapped to the same register. Consider
  1928. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1929. variable \code{x} is moved to \code{z} it is no longer needed.
  1930. Variable \code{y}, on the other hand, is used only after this point,
  1931. so \code{x} and \code{y} could share the same register. The topic of
  1932. Section~\ref{sec:liveness-analysis} is how we compute where a variable
  1933. is needed. Once we have that information, we compute which variables
  1934. are needed at the same time, i.e., which ones \emph{interfere}, and
  1935. represent this relation as graph whose vertices are variables and
  1936. edges indicate when two variables interfere with eachother
  1937. (Section~\ref{sec:build-interference}). We then model register
  1938. allocation as a graph coloring problem, which we discuss in
  1939. Section~\ref{sec:graph-coloring}.
  1940. In the event that we run out of registers despite these efforts, we
  1941. place the remaining variables on the stack, similar to what we did in
  1942. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1943. that is assigned to a stack location, it has been \emph{spilled}. The
  1944. process of spilling variables is handled as part of the graph coloring
  1945. process described in \ref{sec:graph-coloring}.
  1946. \section{Registers and Calling Conventions}
  1947. \label{sec:calling-conventions}
  1948. As we perform register allocation, we will need to be aware of the
  1949. conventions that govern the way in which registers interact with
  1950. function calls. The convention for x86 is that the caller is
  1951. responsible for freeing up some registers, the \emph{caller-saved
  1952. registers}, prior to the function call, and the callee is
  1953. responsible for saving and restoring some other registers, the
  1954. \emph{callee-saved registers}, before and after using them. The
  1955. caller-saved registers are
  1956. \begin{lstlisting}
  1957. rax rdx rcx rsi rdi r8 r9 r10 r11
  1958. \end{lstlisting}
  1959. while the callee-saved registers are
  1960. \begin{lstlisting}
  1961. rsp rbp rbx r12 r13 r14 r15
  1962. \end{lstlisting}
  1963. Another way to think about this caller/callee convention is the
  1964. following. The caller should assume that all the caller-saved registers
  1965. get overwritten with arbitrary values by the callee. On the other
  1966. hand, the caller can safely assume that all the callee-saved registers
  1967. contain the same values after the call that they did before the call.
  1968. The callee can freely use any of the caller-saved registers. However,
  1969. if the callee wants to use a callee-saved register, the callee must
  1970. arrange to put the original value back in the register prior to
  1971. returning to the caller, which is usually accomplished by saving and
  1972. restoring the value from the stack.
  1973. \section{Liveness Analysis}
  1974. \label{sec:liveness-analysis}
  1975. A variable is \emph{live} if the variable is used at some later point
  1976. in the program and there is not an intervening assignment to the
  1977. variable.
  1978. %
  1979. To understand the latter condition, consider the following code
  1980. fragment in which there are two writes to \code{b}. Are \code{a} and
  1981. \code{b} both live at the same time?
  1982. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1983. (movq (int 5) (var a))
  1984. (movq (int 30) (var b))
  1985. (movq (var a) (var c))
  1986. (movq (int 10) (var b))
  1987. (addq (var b) (var c))
  1988. \end{lstlisting}
  1989. The answer is no because the value \code{30} written to \code{b} on
  1990. line 2 is never used. The variable \code{b} is read on line 5 and
  1991. there is an intervening write to \code{b} on line 4, so the read on
  1992. line 5 receives the value written on line 4, not line 2.
  1993. The live variables can be computed by traversing the instruction
  1994. sequence back to front (i.e., backwards in execution order). Let
  1995. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1996. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1997. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1998. variables before instruction $I_k$. The live variables after an
  1999. instruction are always the same as the live variables before the next
  2000. instruction.
  2001. \begin{equation*}
  2002. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2003. \end{equation*}
  2004. To start things off, there are no live variables after the last
  2005. instruction, so
  2006. \begin{equation*}
  2007. L_{\mathsf{after}}(n) = \emptyset
  2008. \end{equation*}
  2009. We then apply the following rule repeatedly, traversing the
  2010. instruction sequence back to front.
  2011. \begin{equation*}
  2012. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2013. \end{equation*}
  2014. where $W(k)$ are the variables written to by instruction $I_k$ and
  2015. $R(k)$ are the variables read by instruction $I_k$.
  2016. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2017. for the running example, with each instruction aligned with its
  2018. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2019. \margincomment{JM: I think you should walk through the explanation of this formula,
  2020. connecting it back to the example from before. \\
  2021. JS: Agreed.}
  2022. \begin{figure}[tbp]
  2023. \hspace{20pt}
  2024. \begin{minipage}{0.45\textwidth}
  2025. \begin{lstlisting}[numbers=left]
  2026. (program (v w x y z t.1 t.2)
  2027. (movq (int 1) (var v))
  2028. (movq (int 46) (var w))
  2029. (movq (var v) (var x))
  2030. (addq (int 7) (var x))
  2031. (movq (var x) (var y))
  2032. (addq (int 4) (var y))
  2033. (movq (var x) (var z))
  2034. (addq (var w) (var z))
  2035. (movq (var y) (var t.1))
  2036. (negq (var t.1))
  2037. (movq (var z) (var t.2))
  2038. (addq (var t.1) (var t.2))
  2039. (movq (var t.2) (reg rax)))
  2040. \end{lstlisting}
  2041. \end{minipage}
  2042. \vrule\hspace{10pt}
  2043. \begin{minipage}{0.45\textwidth}
  2044. \begin{lstlisting}
  2045. |$\{ v \}$|
  2046. |$\{ v, w \}$|
  2047. |$\{ w, x \}$|
  2048. |$\{ w, x \}$|
  2049. |$\{ w, x, y\}$|
  2050. |$\{ w, x, y \}$|
  2051. |$\{ w, y, z \}$|
  2052. |$\{ y, z \}$|
  2053. |$\{ t.1, z \}$|
  2054. |$\{ t.1, z \}$|
  2055. |$\{t.1,t.2\}$|
  2056. |$\{t.2\}$|
  2057. |$\{\}$|
  2058. \end{lstlisting}
  2059. \end{minipage}
  2060. \caption{An example program annotated with live-after sets.}
  2061. \label{fig:live-eg}
  2062. \end{figure}
  2063. \begin{exercise}\normalfont
  2064. Implement the compiler pass named \code{uncover-live} that computes
  2065. the live-after sets. We recommend storing the live-after sets (a list
  2066. of lists of variables) in the $\itm{info}$ field of the \key{program}
  2067. node alongside the list of variables as follows.
  2068. \begin{lstlisting}
  2069. (program (|$\Var^{*}$| |$\itm{live}$-$\itm{afters}$|) |$\Instr^{+}$|)
  2070. \end{lstlisting}
  2071. We recommend organizing your code to use a helper function that takes a
  2072. list of statements and an initial live-after set (typically empty) and
  2073. returns the list of statements and the list of live-after sets. For
  2074. this chapter, returning the list of statements is unnecessary, as they
  2075. will be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  2076. \key{if} statements and will need to annotate them with the live-after
  2077. sets of the two branches.
  2078. We recommend creating helper functions to 1) compute the set of
  2079. variables that appear in an argument (of an instruction), 2) compute
  2080. the variables read by an instruction which corresponds to the $R$
  2081. function discussed above, and 3) the variables written by an
  2082. instruction which corresponds to $W$.
  2083. \end{exercise}
  2084. \section{Building the Interference Graph}
  2085. \label{sec:build-interference}
  2086. Based on the liveness analysis, we know where each variable is needed.
  2087. However, during register allocation, we need to answer questions of
  2088. the specific form: are variables $u$ and $v$ live at the same time?
  2089. (And therefore cannot be assigned to the same register.) To make this
  2090. question easier to answer, we create an explicit data structure, an
  2091. \emph{interference graph}. An interference graph is an undirected
  2092. graph that has an edge between two variables if they are live at the
  2093. same time, that is, if they interfere with each other.
  2094. The most obvious way to compute the interference graph is to look at
  2095. the set of live variables between each statement in the program, and
  2096. add an edge to the graph for every pair of variables in the same set.
  2097. This approach is less than ideal for two reasons. First, it can be
  2098. rather expensive because it takes $O(n^2)$ time to look at every pair
  2099. in a set of $n$ live variables. Second, there is a special case in
  2100. which two variables that are live at the same time do not actually
  2101. interfere with each other: when they both contain the same value
  2102. because we have assigned one to the other.
  2103. A better way to compute the interference graph is to focus on the
  2104. writes. That is, for each instruction, create an edge between the
  2105. variable being written to and all the \emph{other} live variables.
  2106. (One should not create self edges.) For a \key{callq} instruction,
  2107. think of all caller-saved registers as being written to, so and edge
  2108. must be added between every live variable and every caller-saved
  2109. register. For \key{movq}, we deal with the above-mentioned special
  2110. case by not adding an edge between a live variable $v$ and destination
  2111. $d$ if $v$ matches the source of the move. So we have the following
  2112. three rules.
  2113. \begin{enumerate}
  2114. \item If instruction $I_k$ is an arithmetic instruction such as
  2115. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2116. L_{\mathsf{after}}(k)$ unless $v = d$.
  2117. \item If instruction $I_k$ is of the form (\key{callq}
  2118. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2119. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2120. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2121. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2122. d$ or $v = s$.
  2123. \end{enumerate}
  2124. \margincomment{JM: I think you could give examples of each one of these
  2125. using the example program and use those to help explain why these
  2126. rules are correct.\\
  2127. JS: Agreed.}
  2128. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2129. the following interference for the instruction at the specified line
  2130. number.
  2131. \begin{quote}
  2132. Line 2: no interference,\\
  2133. Line 3: $w$ interferes with $v$,\\
  2134. Line 4: $x$ interferes with $w$,\\
  2135. Line 5: $x$ interferes with $w$,\\
  2136. Line 6: $y$ interferes with $w$,\\
  2137. Line 7: $y$ interferes with $w$ and $x$,\\
  2138. Line 8: $z$ interferes with $w$ and $y$,\\
  2139. Line 9: $z$ interferes with $y$, \\
  2140. Line 10: $t.1$ interferes with $z$, \\
  2141. Line 11: $t.1$ interferes with $z$, \\
  2142. Line 12: $t.2$ interferes with $t.1$, \\
  2143. Line 13: no interference. \\
  2144. Line 14: no interference.
  2145. \end{quote}
  2146. The resulting interference graph is shown in
  2147. Figure~\ref{fig:interfere}.
  2148. \begin{figure}[tbp]
  2149. \large
  2150. \[
  2151. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2152. \node (v) at (0,0) {$v$};
  2153. \node (w) at (2,0) {$w$};
  2154. \node (x) at (4,0) {$x$};
  2155. \node (t1) at (6,0) {$t.1$};
  2156. \node (y) at (2,-2) {$y$};
  2157. \node (z) at (4,-2) {$z$};
  2158. \node (t2) at (6,-2) {$t.2$};
  2159. \draw (v) to (w);
  2160. \foreach \i in {w,x,y}
  2161. {
  2162. \foreach \j in {w,x,y}
  2163. {
  2164. \draw (\i) to (\j);
  2165. }
  2166. }
  2167. \draw (z) to (w);
  2168. \draw (z) to (y);
  2169. \draw (t1) to (z);
  2170. \draw (t2) to (t1);
  2171. \end{tikzpicture}
  2172. \]
  2173. \caption{The interference graph of the example program.}
  2174. \label{fig:interfere}
  2175. \end{figure}
  2176. Our next concern is to choose a data structure for representing the
  2177. interference graph. There are many standard choices for how to
  2178. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  2179. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  2180. structure is to study the algorithm that uses the data structure,
  2181. determine what operations need to be performed, and then choose the
  2182. data structure that provide the most efficient implementations of
  2183. those operations. Often times the choice of data structure can have an
  2184. effect on the time complexity of the algorithm, as it does here. If
  2185. you skim the next section, you will see that the register allocation
  2186. algorithm needs to ask the graph for all of its vertices and, given a
  2187. vertex, it needs to known all of the adjacent vertices. Thus, the
  2188. correct choice of graph representation is that of an adjacency
  2189. list. There are helper functions in \code{utilities.rkt} for
  2190. representing graphs using the adjacency list representation:
  2191. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2192. (Appendix~\ref{appendix:utilities}). In particular, those functions
  2193. use a hash table to map each vertex to the set of adjacent vertices,
  2194. and the sets are represented using Racket's \key{set}, which is also a
  2195. hash table.
  2196. \begin{exercise}\normalfont
  2197. Implement the compiler pass named \code{build-interference} according
  2198. to the algorithm suggested above. The output of this pass should
  2199. replace the live-after sets with the interference $\itm{graph}$ as
  2200. follows.
  2201. \begin{lstlisting}
  2202. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  2203. \end{lstlisting}
  2204. \end{exercise}
  2205. \section{Graph Coloring via Sudoku}
  2206. \label{sec:graph-coloring}
  2207. We now come to the main event, mapping variables to registers (or to
  2208. stack locations in the event that we run out of registers). We need
  2209. to make sure not to map two variables to the same register if the two
  2210. variables interfere with each other. In terms of the interference
  2211. graph, this means that adjacent vertices must be mapped to different
  2212. registers. If we think of registers as colors, the register
  2213. allocation problem becomes the widely-studied graph coloring
  2214. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2215. The reader may be more familiar with the graph coloring problem then he
  2216. or she realizes; the popular game of Sudoku is an instance of the
  2217. graph coloring problem. The following describes how to build a graph
  2218. out of an initial Sudoku board.
  2219. \begin{itemize}
  2220. \item There is one vertex in the graph for each Sudoku square.
  2221. \item There is an edge between two vertices if the corresponding squares
  2222. are in the same row, in the same column, or if the squares are in
  2223. the same $3\times 3$ region.
  2224. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2225. \item Based on the initial assignment of numbers to squares in the
  2226. Sudoku board, assign the corresponding colors to the corresponding
  2227. vertices in the graph.
  2228. \end{itemize}
  2229. If you can color the remaining vertices in the graph with the nine
  2230. colors, then you have also solved the corresponding game of Sudoku.
  2231. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2232. the corresponding graph with colored vertices. We map the Sudoku
  2233. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2234. sampling of the vertices (those that are colored) because showing
  2235. edges for all of the vertices would make the graph unreadable.
  2236. \begin{figure}[tbp]
  2237. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2238. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2239. \caption{A Sudoku game board and the corresponding colored graph.}
  2240. \label{fig:sudoku-graph}
  2241. \end{figure}
  2242. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  2243. come up with an algorithm for allocating registers. For example, one
  2244. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  2245. that you use a process of elimination to determine what numbers no
  2246. longer make sense for a square, and write down those numbers in the
  2247. square (writing very small). For example, if the number $1$ is
  2248. assigned to a square, then by process of elimination, you can write
  2249. the pencil mark $1$ in all the squares in the same row, column, and
  2250. region. Many Sudoku computer games provide automatic support for
  2251. Pencil Marks. This heuristic also reduces the degree of branching in
  2252. the search tree.
  2253. The Pencil Marks technique corresponds to the notion of color
  2254. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2255. vertex, in Sudoku terms, is the set of colors that are no longer
  2256. available. In graph terminology, we have the following definition:
  2257. \begin{equation*}
  2258. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  2259. \text{ and } \mathrm{color}(v) = c \}
  2260. \end{equation*}
  2261. where $\mathrm{adjacent}(u)$ is the set of vertices adjacent to $u$.
  2262. Using the Pencil Marks technique leads to a simple strategy for
  2263. filling in numbers: if there is a square with only one possible number
  2264. left, then write down that number! But what if there are no squares
  2265. with only one possibility left? One brute-force approach is to just
  2266. make a guess. If that guess ultimately leads to a solution, great. If
  2267. not, backtrack to the guess and make a different guess. Of course,
  2268. backtracking can be horribly time consuming. One standard way to
  2269. reduce the amount of backtracking is to use the most-constrained-first
  2270. heuristic. That is, when making a guess, always choose a square with
  2271. the fewest possibilities left (the vertex with the highest saturation).
  2272. The idea is that choosing highly constrained squares earlier rather
  2273. than later is better because later there may not be any possibilities.
  2274. In some sense, register allocation is easier than Sudoku because we
  2275. can always cheat and add more numbers by mapping variables to the
  2276. stack. We say that a variable is \emph{spilled} when we decide to map
  2277. it to a stack location. We would like to minimize the time needed to
  2278. color the graph, and backtracking is expensive. Thus, it makes sense
  2279. to keep the most-constrained-first heuristic but drop the backtracking
  2280. in favor of greedy search (guess and just keep going).
  2281. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2282. greedy algorithm for register allocation based on saturation and the
  2283. most-constrained-first heuristic, which is roughly equivalent to the
  2284. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2285. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2286. as in Sudoku, the algorithm represents colors with integers, with the
  2287. first $k$ colors corresponding to the $k$ registers in a given machine
  2288. and the rest of the integers corresponding to stack locations.
  2289. \begin{figure}[btp]
  2290. \centering
  2291. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2292. Algorithm: DSATUR
  2293. Input: a graph |$G$|
  2294. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2295. |$W \gets \mathit{vertices}(G)$|
  2296. while |$W \neq \emptyset$| do
  2297. pick a vertex |$u$| from |$W$| with the highest saturation,
  2298. breaking ties randomly
  2299. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2300. |$\mathrm{color}[u] \gets c$|
  2301. |$W \gets W - \{u\}$|
  2302. \end{lstlisting}
  2303. \caption{The saturation-based greedy graph coloring algorithm.}
  2304. \label{fig:satur-algo}
  2305. \end{figure}
  2306. With this algorithm in hand, let us return to the running example and
  2307. consider how to color the interference graph in
  2308. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2309. register allocation because we use it to patch instructions, so we
  2310. remove that vertex from the graph. Initially, all of the vertices are
  2311. not yet colored and they are unsaturated, so we annotate each of them
  2312. with a dash for their color and an empty set for the saturation.
  2313. \[
  2314. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2315. \node (v) at (0,0) {$v:-,\{\}$};
  2316. \node (w) at (3,0) {$w:-,\{\}$};
  2317. \node (x) at (6,0) {$x:-,\{\}$};
  2318. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2319. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2320. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2321. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2322. \draw (v) to (w);
  2323. \foreach \i in {w,x,y}
  2324. {
  2325. \foreach \j in {w,x,y}
  2326. {
  2327. \draw (\i) to (\j);
  2328. }
  2329. }
  2330. \draw (z) to (w);
  2331. \draw (z) to (y);
  2332. \draw (t1) to (z);
  2333. \draw (t2) to (t1);
  2334. \end{tikzpicture}
  2335. \]
  2336. We select a maximally saturated vertex and color it $0$. In this case we
  2337. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2338. as no longer available for $w$, $x$, and $z$ because they interfere
  2339. with $y$.
  2340. \[
  2341. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2342. \node (v) at (0,0) {$v:-,\{\}$};
  2343. \node (w) at (3,0) {$w:-,\{0\}$};
  2344. \node (x) at (6,0) {$x:-,\{0\}$};
  2345. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2346. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2347. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2348. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2349. \draw (v) to (w);
  2350. \foreach \i in {w,x,y}
  2351. {
  2352. \foreach \j in {w,x,y}
  2353. {
  2354. \draw (\i) to (\j);
  2355. }
  2356. }
  2357. \draw (z) to (w);
  2358. \draw (z) to (y);
  2359. \draw (t1) to (z);
  2360. \draw (t2) to (t1);
  2361. \end{tikzpicture}
  2362. \]
  2363. Now we repeat the process, selecting another maximally saturated vertex.
  2364. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2365. $w$ with $1$.
  2366. \[
  2367. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2368. \node (v) at (0,0) {$v:-,\{1\}$};
  2369. \node (w) at (3,0) {$w:1,\{0\}$};
  2370. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2371. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2372. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2373. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2374. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2375. \draw (t1) to (z);
  2376. \draw (t2) to (t1);
  2377. \draw (v) to (w);
  2378. \foreach \i in {w,x,y}
  2379. {
  2380. \foreach \j in {w,x,y}
  2381. {
  2382. \draw (\i) to (\j);
  2383. }
  2384. }
  2385. \draw (z) to (w);
  2386. \draw (z) to (y);
  2387. \end{tikzpicture}
  2388. \]
  2389. The most saturated vertices are now $x$ and $z$. We color $x$ with the
  2390. next available color which is $2$.
  2391. \[
  2392. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2393. \node (v) at (0,0) {$v:-,\{1\}$};
  2394. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2395. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2396. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2397. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2398. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2399. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2400. \draw (t1) to (z);
  2401. \draw (t2) to (t1);
  2402. \draw (v) to (w);
  2403. \foreach \i in {w,x,y}
  2404. {
  2405. \foreach \j in {w,x,y}
  2406. {
  2407. \draw (\i) to (\j);
  2408. }
  2409. }
  2410. \draw (z) to (w);
  2411. \draw (z) to (y);
  2412. \end{tikzpicture}
  2413. \]
  2414. Vertex $z$ is the next most highly saturated, so we color $z$ with $2$.
  2415. \[
  2416. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2417. \node (v) at (0,0) {$v:-,\{1\}$};
  2418. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2419. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2420. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2421. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2422. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2423. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2424. \draw (t1) to (z);
  2425. \draw (t2) to (t1);
  2426. \draw (v) to (w);
  2427. \foreach \i in {w,x,y}
  2428. {
  2429. \foreach \j in {w,x,y}
  2430. {
  2431. \draw (\i) to (\j);
  2432. }
  2433. }
  2434. \draw (z) to (w);
  2435. \draw (z) to (y);
  2436. \end{tikzpicture}
  2437. \]
  2438. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2439. $0$.
  2440. \[
  2441. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2442. \node (v) at (0,0) {$v:0,\{1\}$};
  2443. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2444. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2445. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2446. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2447. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2448. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2449. \draw (t1) to (z);
  2450. \draw (t2) to (t1);
  2451. \draw (v) to (w);
  2452. \foreach \i in {w,x,y}
  2453. {
  2454. \foreach \j in {w,x,y}
  2455. {
  2456. \draw (\i) to (\j);
  2457. }
  2458. }
  2459. \draw (z) to (w);
  2460. \draw (z) to (y);
  2461. \end{tikzpicture}
  2462. \]
  2463. In the last two steps of the algorithm, we color $t.1$ with $0$
  2464. then $t.2$ with $1$.
  2465. \[
  2466. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2467. \node (v) at (0,0) {$v:0,\{1\}$};
  2468. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2469. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2470. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2471. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2472. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2473. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2474. \draw (t1) to (z);
  2475. \draw (t2) to (t1);
  2476. \draw (v) to (w);
  2477. \foreach \i in {w,x,y}
  2478. {
  2479. \foreach \j in {w,x,y}
  2480. {
  2481. \draw (\i) to (\j);
  2482. }
  2483. }
  2484. \draw (z) to (w);
  2485. \draw (z) to (y);
  2486. \end{tikzpicture}
  2487. \]
  2488. With the coloring complete, we can finalize the assignment of
  2489. variables to registers and stack locations. Recall that if we have $k$
  2490. registers, we map the first $k$ colors to registers and the rest to
  2491. stack locations. Suppose for the moment that we just have one extra
  2492. register to use for register allocation, just \key{rbx}. Then the
  2493. following is the mapping of colors to registers and stack allocations.
  2494. \[
  2495. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2496. \]
  2497. Putting this mapping together with the above coloring of the variables, we
  2498. arrive at the assignment:
  2499. \begin{gather*}
  2500. \{ v \mapsto \key{\%rbx}, \,
  2501. w \mapsto \key{-8(\%rbp)}, \,
  2502. x \mapsto \key{-16(\%rbp)}, \,
  2503. y \mapsto \key{\%rbx}, \,
  2504. z\mapsto \key{-16(\%rbp)}, \\
  2505. t.1\mapsto \key{\%rbx} ,\,
  2506. t.2\mapsto \key{-8(\%rbp)} \}
  2507. \end{gather*}
  2508. Applying this assignment to our running example
  2509. (Figure~\ref{fig:reg-eg}) yields the program on the right.\\
  2510. % why frame size of 32? -JGS
  2511. \begin{minipage}{0.4\textwidth}
  2512. \begin{lstlisting}
  2513. (program (v w x y z)
  2514. (movq (int 1) (var v))
  2515. (movq (int 46) (var w))
  2516. (movq (var v) (var x))
  2517. (addq (int 7) (var x))
  2518. (movq (var x) (var y))
  2519. (addq (int 4) (var y))
  2520. (movq (var x) (var z))
  2521. (addq (var w) (var z))
  2522. (movq (var y) (var t.1))
  2523. (negq (var t.1))
  2524. (movq (var z) (var t.2))
  2525. (addq (var t.1) (var t.2))
  2526. (movq (var t.2) (reg rax)))
  2527. \end{lstlisting}
  2528. \end{minipage}
  2529. $\Rightarrow$
  2530. \begin{minipage}{0.45\textwidth}
  2531. \begin{lstlisting}
  2532. (program 16
  2533. (movq (int 1) (reg rbx))
  2534. (movq (int 46) (deref rbp -8))
  2535. (movq (reg rbx) (deref rbp -16))
  2536. (addq (int 7) (deref rbp -16))
  2537. (movq (deref rbp -16) (reg rbx))
  2538. (addq (int 4) (reg rbx))
  2539. (movq (deref rbp -16) (deref rbp -16))
  2540. (addq (deref rbp -8) (deref rbp -16))
  2541. (movq (reg rbx) (reg rbx))
  2542. (negq (reg rbx))
  2543. (movq (deref rbp -16) (deref rbp -8))
  2544. (addq (reg rbx) (deref rbp -8))
  2545. (movq (deref rbp -8) (reg rax)))
  2546. \end{lstlisting}
  2547. \end{minipage}
  2548. The resulting program is almost an x86 program. The remaining step
  2549. is to apply the patch instructions pass. In this example, the trivial
  2550. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2551. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2552. \code{rax}. The following shows the portion of the program that
  2553. changed.
  2554. \begin{lstlisting}
  2555. (addq (int 4) (reg rbx))
  2556. (movq (deref rbp -8) (reg rax)
  2557. (addq (reg rax) (deref rbp -16))
  2558. \end{lstlisting}
  2559. An overview of all of the passes involved in register allocation is
  2560. shown in Figure~\ref{fig:reg-alloc-passes}.
  2561. \begin{figure}[p]
  2562. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2563. \node (R1) at (0,2) {\large $R_1$};
  2564. \node (R1-2) at (3,2) {\large $R_1$};
  2565. \node (C0-1) at (3,0) {\large $C_0$};
  2566. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2567. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2568. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2569. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2570. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2571. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2572. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2573. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2574. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2575. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2576. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2577. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2578. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2579. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2580. \end{tikzpicture}
  2581. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2582. \label{fig:reg-alloc-passes}
  2583. \end{figure}
  2584. \begin{exercise}\normalfont
  2585. Implement the pass \code{allocate-registers}, which should come
  2586. after the \code{build-interference} pass. The three new passes,
  2587. \code{uncover-live}, \code{build-interference}, and
  2588. \code{allocate-registers} replace the \code{assign-homes} pass of
  2589. Section~\ref{sec:assign-s0}. Just like \code{assign-homes}, the
  2590. output of \code{allocate-registers} should be in the form
  2591. \[
  2592. (\key{program}\;\Int\;\Instr^{+})
  2593. \]
  2594. We recommend that you create a helper function named
  2595. \code{color-graph} that takes an interference graph and a list of
  2596. all the variables in the program. This function should return a
  2597. mapping of variables to their colors (represented as natural
  2598. numbers). By creating this helper function, you will be able to
  2599. reuse it in Chapter~\ref{ch:functions} when you add support for
  2600. functions.
  2601. Once you have obtained the coloring from \code{color-graph}, you can
  2602. assign the variables to registers or stack locations and then reuse
  2603. code from the \code{assign-homes} pass from
  2604. Section~\ref{sec:assign-s0} to replace the variables with their
  2605. assigned location.
  2606. Test your updated compiler by creating new example programs that
  2607. exercise all of the register allocation algorithm, such as forcing
  2608. variables to be spilled to the stack.
  2609. \end{exercise}
  2610. \section{Print x86 and Conventions for Registers}
  2611. \label{sec:print-x86-reg-alloc}
  2612. Recall the \code{print-x86} pass generates the prelude and
  2613. conclusion instructions for the \code{main} function.
  2614. %
  2615. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2616. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2617. reason for this is that our \code{main} function must adhere to the
  2618. x86 calling conventions that we described in
  2619. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2620. function needs and restore (in the conclusion) any callee-saved
  2621. registers that get used during register allocation. The simplest
  2622. approach is to save and restore all of the callee-saved registers. The
  2623. more efficient approach is to keep track of which callee-saved
  2624. registers were used and only save and restore them. Either way, make
  2625. sure to take this use of stack space into account when you are
  2626. calculating the size of the frame. Also, don't forget that the size of
  2627. the frame needs to be a multiple of 16 bytes.
  2628. \section{Challenge: Move Biasing$^{*}$}
  2629. \label{sec:move-biasing}
  2630. This section describes an optional enhancement to register allocation
  2631. for those students who are looking for an extra challenge or who have
  2632. a deeper interest in register allocation.
  2633. We return to the running example, but we remove the supposition that
  2634. we only have one register to use. So we have the following mapping of
  2635. color numbers to registers.
  2636. \[
  2637. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2638. \]
  2639. Using the same assignment that was produced by register allocator
  2640. described in the last section, we get the following program.
  2641. \begin{minipage}{0.45\textwidth}
  2642. \begin{lstlisting}
  2643. (program (v w x y z)
  2644. (movq (int 1) (var v))
  2645. (movq (int 46) (var w))
  2646. (movq (var v) (var x))
  2647. (addq (int 7) (var x))
  2648. (movq (var x) (var y))
  2649. (addq (int 4) (var y))
  2650. (movq (var x) (var z))
  2651. (addq (var w) (var z))
  2652. (movq (var y) (var t.1))
  2653. (negq (var t.1))
  2654. (movq (var z) (var t.2))
  2655. (addq (var t.1) (var t.2))
  2656. (movq (var t.2) (reg rax)))
  2657. \end{lstlisting}
  2658. \end{minipage}
  2659. $\Rightarrow$
  2660. \begin{minipage}{0.45\textwidth}
  2661. \begin{lstlisting}
  2662. (program 0
  2663. (movq (int 1) (reg rbx))
  2664. (movq (int 46) (reg rcx))
  2665. (movq (reg rbx) (reg rdx))
  2666. (addq (int 7) (reg rdx))
  2667. (movq (reg rdx) (reg rbx))
  2668. (addq (int 4) (reg rbx))
  2669. (movq (reg rdx) (reg rdx))
  2670. (addq (reg rcx) (reg rdx))
  2671. (movq (reg rbx) (reg rbx))
  2672. (negq (reg rbx))
  2673. (movq (reg rdx) (reg rcx))
  2674. (addq (reg rbx) (reg rcx))
  2675. (movq (reg rcx) (reg rax)))
  2676. \end{lstlisting}
  2677. \end{minipage}
  2678. While this allocation is quite good, we could do better. For example,
  2679. the variables \key{v} and \key{x} ended up in different registers, but
  2680. if they had been placed in the same register, then the move from
  2681. \key{v} to \key{x} could be removed.
  2682. We say that two variables $p$ and $q$ are \emph{move related} if they
  2683. participate together in a \key{movq} instruction, that is, \key{movq
  2684. p, q} or \key{movq q, p}. When the register allocator chooses a
  2685. color for a variable, it should prefer a color that has already been
  2686. used for a move-related variable (assuming that they do not
  2687. interfere). Of course, this preference should not override the
  2688. preference for registers over stack locations, but should only be used
  2689. as a tie breaker when choosing between registers or when choosing
  2690. between stack locations.
  2691. We recommend that you represent the move relationships in a graph,
  2692. similar to how we represented interference. The following is the
  2693. \emph{move graph} for our running example.
  2694. \[
  2695. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2696. \node (v) at (0,0) {$v$};
  2697. \node (w) at (3,0) {$w$};
  2698. \node (x) at (6,0) {$x$};
  2699. \node (y) at (3,-1.5) {$y$};
  2700. \node (z) at (6,-1.5) {$z$};
  2701. \node (t1) at (9,0) {$t.1$};
  2702. \node (t2) at (9,-1.5) {$t.2$};
  2703. \draw (t1) to (y);
  2704. \draw (t2) to (z);
  2705. \draw[bend left=20] (v) to (x);
  2706. \draw (x) to (y);
  2707. \draw (x) to (z);
  2708. \end{tikzpicture}
  2709. \]
  2710. Now we replay the graph coloring, pausing to see the coloring of $z$
  2711. and $v$. So we have the following coloring so far and the most
  2712. saturated vertex is $z$.
  2713. \[
  2714. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2715. \node (v) at (0,0) {$v:-,\{1\}$};
  2716. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2717. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2718. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2719. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2720. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2721. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2722. \draw (t1) to (z);
  2723. \draw (t2) to (t1);
  2724. \draw (v) to (w);
  2725. \foreach \i in {w,x,y}
  2726. {
  2727. \foreach \j in {w,x,y}
  2728. {
  2729. \draw (\i) to (\j);
  2730. }
  2731. }
  2732. \draw (z) to (w);
  2733. \draw (z) to (y);
  2734. \end{tikzpicture}
  2735. \]
  2736. Last time we chose to color $z$ with $2$, which so happens to be the
  2737. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2738. and if the program had been a little different, and say $x$ had been
  2739. already assigned to $3$, then $z$ would still get $2$ and our luck
  2740. would have run out. With move biasing, we use the fact that $z$ and
  2741. $x$ are move related to influence the choice of color for $z$, in this
  2742. case choosing $2$ because that's the color of $x$.
  2743. \[
  2744. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2745. \node (v) at (0,0) {$v:-,\{1\}$};
  2746. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2747. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2748. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2749. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2750. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2751. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2752. \draw (t1) to (z);
  2753. \draw (t2) to (t1);
  2754. \draw (v) to (w);
  2755. \foreach \i in {w,x,y}
  2756. {
  2757. \foreach \j in {w,x,y}
  2758. {
  2759. \draw (\i) to (\j);
  2760. }
  2761. }
  2762. \draw (z) to (w);
  2763. \draw (z) to (y);
  2764. \end{tikzpicture}
  2765. \]
  2766. Next we consider coloring the variable $v$, and we just need to avoid
  2767. choosing $1$ because of the interference with $w$. Last time we choose
  2768. the color $0$, simply because it was the lowest, but this time we know
  2769. that $v$ is move related to $x$, so we choose the color $2$.
  2770. \[
  2771. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2772. \node (v) at (0,0) {$v:2,\{1\}$};
  2773. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2774. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2775. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2776. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2777. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2778. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2779. \draw (t1) to (z);
  2780. \draw (t2) to (t1);
  2781. \draw (v) to (w);
  2782. \foreach \i in {w,x,y}
  2783. {
  2784. \foreach \j in {w,x,y}
  2785. {
  2786. \draw (\i) to (\j);
  2787. }
  2788. }
  2789. \draw (z) to (w);
  2790. \draw (z) to (y);
  2791. \end{tikzpicture}
  2792. \]
  2793. We apply this register assignment to the running example, on the left,
  2794. to obtain the code on right.
  2795. \begin{minipage}{0.45\textwidth}
  2796. \begin{lstlisting}
  2797. (program (v w x y z)
  2798. (movq (int 1) (var v))
  2799. (movq (int 46) (var w))
  2800. (movq (var v) (var x))
  2801. (addq (int 7) (var x))
  2802. (movq (var x) (var y))
  2803. (addq (int 4) (var y))
  2804. (movq (var x) (var z))
  2805. (addq (var w) (var z))
  2806. (movq (var y) (var t.1))
  2807. (negq (var t.1))
  2808. (movq (var z) (var t.2))
  2809. (addq (var t.1) (var t.2))
  2810. (movq (var t.2) (reg rax)))
  2811. \end{lstlisting}
  2812. \end{minipage}
  2813. $\Rightarrow$
  2814. \begin{minipage}{0.45\textwidth}
  2815. \begin{lstlisting}
  2816. (program 0
  2817. (movq (int 1) (reg rdx))
  2818. (movq (int 46) (reg rcx))
  2819. (movq (reg rdx) (reg rdx))
  2820. (addq (int 7) (reg rdx))
  2821. (movq (reg rdx) (reg rbx))
  2822. (addq (int 4) (reg rbx))
  2823. (movq (reg rdx) (reg rdx))
  2824. (addq (reg rcx) (reg rdx))
  2825. (movq (reg rbx) (reg rbx))
  2826. (negq (reg rbx))
  2827. (movq (reg rdx) (reg rcx))
  2828. (addq (reg rbx) (reg rcx))
  2829. (movq (reg rcx) (reg rax)))
  2830. \end{lstlisting}
  2831. \end{minipage}
  2832. The \code{patch-instructions} then removes the trivial moves from
  2833. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2834. \key{t.1}, to obtain the following result.
  2835. \begin{lstlisting}
  2836. (program 0
  2837. (movq (int 1) (reg rdx))
  2838. (movq (int 46) (reg rcx))
  2839. (addq (int 7) (reg rdx))
  2840. (movq (reg rdx) (reg rbx))
  2841. (addq (int 4) (reg rbx))
  2842. (addq (reg rcx) (reg rdx))
  2843. (negq (reg rbx))
  2844. (movq (reg rdx) (reg rcx))
  2845. (addq (reg rbx) (reg rcx))
  2846. (movq (reg rcx) (reg rax)))
  2847. \end{lstlisting}
  2848. \begin{exercise}\normalfont
  2849. Change your implementation of \code{allocate-registers} to take move
  2850. biasing into account. Make sure that your compiler still passes all of
  2851. the previous tests. Create two new tests that include at least one
  2852. opportunity for move biasing and visually inspect the output x86
  2853. programs to make sure that your move biasing is working properly.
  2854. \end{exercise}
  2855. \margincomment{\footnotesize To do: another neat challenge would be to do
  2856. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2857. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2858. \chapter{Booleans, Control Flow, and Type Checking}
  2859. \label{ch:bool-types}
  2860. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2861. integers. In this Chapter we add a second kind of value, the Booleans,
  2862. to create the $R_2$ language. The Boolean values \emph{true} and
  2863. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2864. Racket. We also introduce several operations that involve Booleans
  2865. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2866. \key{if} expression. With the addition of \key{if} expressions,
  2867. programs can have non-trivial control flow which has an impact on
  2868. several parts of the compiler. Also, because we now have two kinds of
  2869. values, we need to worry about programs that apply an operation to the
  2870. wrong kind of value, such as \code{(not 1)}.
  2871. There are two language design options for such situations. One option
  2872. is to signal an error and the other is to provide a wider
  2873. interpretation of the operation. The Racket language uses a mixture of
  2874. these two options, depending on the operation and the kind of
  2875. value. For example, the result of \code{(not 1)} in Racket is
  2876. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2877. the other hand, \code{(car 1)} results in a run-time error in Racket
  2878. stating that \code{car} expects a pair.
  2879. The Typed Racket language makes similar design choices as Racket,
  2880. except much of the error detection happens at compile time instead of
  2881. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2882. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2883. reports a compile-time error because the type of the argument is
  2884. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2885. For the $R_2$ language we choose to be more like Typed Racket in that
  2886. we shall perform type checking during compilation. In
  2887. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2888. is, how to compile a dynamically typed language like Racket. The
  2889. $R_2$ language is a subset of Typed Racket but by no means includes
  2890. all of Typed Racket. Furthermore, for many of the operations we shall
  2891. take a narrower interpretation than Typed Racket, for example,
  2892. rejecting \code{(not 1)}.
  2893. This chapter is organized as follows. We begin by defining the syntax
  2894. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2895. then introduce the idea of type checking and build a type checker for
  2896. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2897. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2898. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2899. how our compiler passes need to change to accommodate Booleans and
  2900. conditional control flow.
  2901. \section{The $R_2$ Language}
  2902. \label{sec:r2-lang}
  2903. The syntax of the $R_2$ language is defined in
  2904. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray) ,
  2905. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2906. \code{if} expression. Also, we expand the operators to include the
  2907. \key{and} and \key{not} on Booleans, the \key{eq?} operations for
  2908. comparing two integers or two Booleans, and the \key{<}, \key{<=},
  2909. \key{>}, and \key{>=} operations for comparing integers.
  2910. \begin{figure}[tp]
  2911. \centering
  2912. \fbox{
  2913. \begin{minipage}{0.96\textwidth}
  2914. \[
  2915. \begin{array}{lcl}
  2916. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2917. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2918. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2919. &\mid& \key{\#t} \mid \key{\#f} \mid
  2920. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2921. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2922. R_2 &::=& (\key{program} \; \Exp)
  2923. \end{array}
  2924. \]
  2925. \end{minipage}
  2926. }
  2927. \caption{The syntax of $R_2$, extending $R_1$ with Booleans and
  2928. conditionals.}
  2929. \label{fig:r2-syntax}
  2930. \end{figure}
  2931. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2932. the parts that are the same as the interpreter for $R_1$
  2933. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2934. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2935. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2936. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2937. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2938. operations \code{not} and \code{and} behave as you might expect, but
  2939. note that the \code{and} operation is short-circuiting. That is, given
  2940. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2941. evaluated if $e_1$ evaluates to \code{\#f}.
  2942. With the addition of the comparison operations, there are quite a few
  2943. primitive operations and the interpreter code for them is somewhat
  2944. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2945. parts into the \code{interp-op} function and the similar parts into
  2946. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2947. important for that match clause to come last because it matches
  2948. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2949. the \code{and} operation because of the short-circuiting behavior in
  2950. the order of evaluation of its arguments.
  2951. \begin{figure}[tbp]
  2952. \begin{lstlisting}
  2953. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2954. (define (interp-op op)
  2955. (match op
  2956. ...
  2957. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2958. ['eq? (lambda (v1 v2)
  2959. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2960. (and (boolean? v1) (boolean? v2))
  2961. (and (vector? v1) (vector? v2)))
  2962. (eq? v1 v2)]))]
  2963. ['< (lambda (v1 v2)
  2964. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  2965. ['<= (lambda (v1 v2)
  2966. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  2967. ['> (lambda (v1 v2)
  2968. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  2969. ['>= (lambda (v1 v2)
  2970. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  2971. [else (error 'interp-op "unknown operator")]))
  2972. (define (interp-exp env)
  2973. (lambda (e)
  2974. (define recur (interp-exp env))
  2975. (match e
  2976. ...
  2977. [(? boolean?) e]
  2978. [`(if ,(app recur cnd) ,thn ,els)
  2979. (match cnd
  2980. [#t (recur thn)]
  2981. [#f (recur els)])]
  2982. [`(and ,(app recur v1) ,e2)
  2983. (match v1
  2984. [#t (match (recur e2) [#t #t] [#f #f])]
  2985. [#f #f])]
  2986. [`(has-type ,(app recur v) ,t) v]
  2987. [`(,op ,(app recur args) ...)
  2988. #:when (set-member? primitives op)
  2989. (apply (interp-op op) args)])))
  2990. (define (interp-R2 env)
  2991. (lambda (p)
  2992. (match p
  2993. [(or `(program ,_ ,e) `(program ,e))
  2994. ((interp-exp '()) e)])))
  2995. \end{lstlisting}
  2996. \caption{Interpreter for the $R_2$ language.}
  2997. \label{fig:interp-R2}
  2998. \end{figure}
  2999. \section{Type Checking $R_2$ Programs}
  3000. \label{sec:type-check-r2}
  3001. It is helpful to think about type checking into two complementary
  3002. ways. A type checker predicts the \emph{type} of value that will be
  3003. produced by each expression in the program. For $R_2$, we have just
  3004. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3005. predict that
  3006. \begin{lstlisting}
  3007. (+ 10 (- (+ 12 20)))
  3008. \end{lstlisting}
  3009. produces an \key{Integer} while
  3010. \begin{lstlisting}
  3011. (and (not #f) #t)
  3012. \end{lstlisting}
  3013. produces a \key{Boolean}.
  3014. As mentioned at the beginning of this chapter, a type checker also
  3015. rejects programs that apply operators to the wrong type of value. Our
  3016. type checker for $R_2$ will signal an error for the following
  3017. expression because, as we have seen above, the expression \code{(+ 10
  3018. ...)} has type \key{Integer}, and we require the argument of a
  3019. \code{not} to have type \key{Boolean}.
  3020. \begin{lstlisting}
  3021. (not (+ 10 (- (+ 12 20))))
  3022. \end{lstlisting}
  3023. The type checker for $R_2$ is best implemented as a structurally
  3024. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3025. many of the clauses for the \code{typecheck-R2} function. Given an
  3026. input expression \code{e}, the type checker either returns the type
  3027. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3028. the type of an integer literal is \code{Integer} and the type of a
  3029. Boolean literal is \code{Boolean}. To handle variables, the type
  3030. checker, like the interpreter, uses an association list. However, in
  3031. this case the association list maps variables to types instead of
  3032. values. Consider the clause for \key{let}. We type check the
  3033. initializing expression to obtain its type \key{T} and then associate
  3034. type \code{T} with the variable \code{x}. When the type checker
  3035. encounters the use of a variable, it can lookup its type in the
  3036. association list.
  3037. \begin{figure}[tbp]
  3038. \begin{lstlisting}
  3039. (define (type-check-exp env)
  3040. (lambda (e)
  3041. (define recur (type-check-exp env))
  3042. (match e
  3043. [(? fixnum?) 'Integer]
  3044. [(? boolean?) 'Boolean]
  3045. [(? symbol?) (lookup e env)]
  3046. [`(read) 'Integer]
  3047. [`(let ([,x ,(app recur T)]) ,body)
  3048. (define new-env (cons (cons x T) env))
  3049. (type-check-exp new-env body)]
  3050. ...
  3051. [`(not ,(app recur T))
  3052. (match T
  3053. ['Boolean 'Boolean]
  3054. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3055. ...
  3056. )))
  3057. (define (type-check-R2 env)
  3058. (lambda (e)
  3059. (match e
  3060. [`(program ,body)
  3061. (define ty ((type-check-exp '()) body))
  3062. `(program (type ,ty) ,body)]
  3063. )))
  3064. \end{lstlisting}
  3065. \caption{Skeleton of a type checker for the $R_2$ language.}
  3066. \label{fig:type-check-R2}
  3067. \end{figure}
  3068. To print the resulting value correctly, the overall type of the
  3069. program must be threaded through the remainder of the passes. We can
  3070. store the type within the \key{program} form as shown in Figure
  3071. \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3072. intermediate language produced by the type checker, which we define as
  3073. follows: \\[1ex]
  3074. \fbox{
  3075. \begin{minipage}{0.87\textwidth}
  3076. \[
  3077. \begin{array}{lcl}
  3078. R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3079. \end{array}
  3080. \]
  3081. \end{minipage}
  3082. }
  3083. \begin{exercise}\normalfont
  3084. Complete the implementation of \code{typecheck-R2} and test it on 10
  3085. new example programs in $R_2$ that you choose based on how thoroughly
  3086. they test the type checking algorithm. Half of the example programs
  3087. should have a type error, to make sure that your type checker properly
  3088. rejects them. The other half of the example programs should not have
  3089. type errors. Your testing should check that the result of the type
  3090. checker agrees with the value returned by the interpreter, that is, if
  3091. the type checker returns \key{Integer}, then the interpreter should
  3092. return an integer. Likewise, if the type checker returns
  3093. \key{Boolean}, then the interpreter should return \code{\#t} or
  3094. \code{\#f}. Note that if your type checker does not signal an error
  3095. for a program, then interpreting that program should not encounter an
  3096. error. If it does, there is something wrong with your type checker.
  3097. \end{exercise}
  3098. \section{The $C_1$ Language}
  3099. \label{sec:c1}
  3100. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  3101. As with $R_1$, we shall compile to a C-like intermediate language, but
  3102. we need to grow that intermediate language to handle the new features
  3103. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  3104. we add logic and comparison operators to the $\Exp$ non-terminal, the
  3105. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  3106. add an \key{if} statement. The \key{if} statement of $C_1$ includes a
  3107. built-in comparison (unlike the $C$ language), which is needed for
  3108. improving code generation in Section~\ref{sec:opt-if}. We do not
  3109. include \key{and} in $C_1$ because it is not needed in the translation
  3110. of the \key{and} of $R_2$.
  3111. \begin{figure}[tp]
  3112. \fbox{
  3113. \begin{minipage}{0.96\textwidth}
  3114. \[
  3115. \begin{array}{lcl}
  3116. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3117. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3118. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3119. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3120. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  3121. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  3122. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  3123. \end{array}
  3124. \]
  3125. \end{minipage}
  3126. }
  3127. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3128. \label{fig:c1-syntax}
  3129. \end{figure}
  3130. \section{Flatten Expressions}
  3131. \label{sec:flatten-r2}
  3132. We expand the \code{flatten} pass to handle the Boolean literals
  3133. \key{\#t} and \key{\#f}, the new logic and comparison operations, and
  3134. \key{if} expressions. We shall start with a simple example of
  3135. translating a \key{if} expression, shown below on the left. \\
  3136. \begin{tabular}{lll}
  3137. \begin{minipage}{0.4\textwidth}
  3138. \begin{lstlisting}
  3139. (program (if #f 0 42))
  3140. \end{lstlisting}
  3141. \end{minipage}
  3142. &
  3143. $\Rightarrow$
  3144. &
  3145. \begin{minipage}{0.4\textwidth}
  3146. \begin{lstlisting}
  3147. (program (if.1)
  3148. (if (eq? #t #f)
  3149. ((assign if.1 0))
  3150. ((assign if.1 42)))
  3151. (return if.1))
  3152. \end{lstlisting}
  3153. \end{minipage}
  3154. \end{tabular} \\
  3155. The value of the \key{if} expression is the value of the branch that
  3156. is selected. Recall that in the \code{flatten} pass we need to replace
  3157. arbitrary expressions with $\Arg$'s (variables or literals). In the
  3158. translation above, on the right, we have replaced the \key{if}
  3159. expression with a new variable \key{if.1}, inside \code{(return
  3160. if.1)}, and we have produced code that will assign the appropriate
  3161. value to \key{if.1} using an \code{if} statement prior to the
  3162. \code{return}. For $R_1$, the \code{flatten} pass returned a list of
  3163. assignment statements. Here, for $R_2$, we return a list of statements
  3164. that can include both \key{if} statements and assignment statements.
  3165. The next example is a bit more involved, showing what happens when
  3166. there are complex expressions (not variables or literals) in the
  3167. condition and branch expressions of an \key{if}, including nested
  3168. \key{if} expressions.
  3169. \begin{tabular}{lll}
  3170. \begin{minipage}{0.4\textwidth}
  3171. \begin{lstlisting}
  3172. (program
  3173. (if (eq? (read) 0)
  3174. 777
  3175. (+ 2 (if (eq? (read) 0)
  3176. 40
  3177. 444))))
  3178. \end{lstlisting}
  3179. \end{minipage}
  3180. &
  3181. $\Rightarrow$
  3182. &
  3183. \begin{minipage}{0.4\textwidth}
  3184. \begin{lstlisting}
  3185. (program (t.1 t.2 if.1 t.3 t.4
  3186. if.2 t.5)
  3187. (assign t.1 (read))
  3188. (assign t.2 (eq? t.1 0))
  3189. (if (eq? #t t.2)
  3190. ((assign if.1 777))
  3191. ((assign t.3 (read))
  3192. (assign t.4 (eq? t.3 0))
  3193. (if (eq? #t t.4)
  3194. ((assign if.2 40))
  3195. ((assign if.2 444)))
  3196. (assign t.5 (+ 2 if.2))
  3197. (assign if.1 t.5)))
  3198. (return if.1))
  3199. \end{lstlisting}
  3200. \end{minipage}
  3201. \end{tabular} \\
  3202. The \code{flatten} clauses for the Boolean literals and the operations
  3203. \key{not} and \key{eq?} are straightforward. However, the
  3204. \code{flatten} clause for \key{and} requires some care to properly
  3205. imitate the order of evaluation of the interpreter for $R_2$
  3206. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  3207. in the code you generate for \key{and}.
  3208. The \code{flatten} clause for \key{if} also requires some care because
  3209. the condition of the \key{if} can be an arbitrary expression in $R_2$,
  3210. but in $C_1$ the condition must be an equality predicate. For now we
  3211. recommend flattening the condition into an $\Arg$ and then comparing
  3212. it with \code{\#t}. We discuss a more efficient approach in
  3213. Section~\ref{sec:opt-if}.
  3214. \begin{exercise}\normalfont
  3215. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  3216. Boolean literals, the new logic and comparison operations, and the
  3217. \key{if} expressions. Create 4 more test cases that expose whether
  3218. your flattening code is correct. Test your \code{flatten} pass by
  3219. running the output programs with \code{interp-C}
  3220. (Appendix~\ref{appendix:interp}).
  3221. \end{exercise}
  3222. \section{XOR, Comparisons, and Control Flow in x86}
  3223. \label{sec:x86-1}
  3224. To implement the new logical operations, the comparison operations,
  3225. and the \key{if} statement, we need to delve further into the x86
  3226. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3227. larger subset of x86 that includes instructions for logical
  3228. operations, comparisons, and jumps.
  3229. One small challenge is that x86 does not provide an instruction that
  3230. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3231. However, the \code{xorq} instruction can be used to encode \code{not}.
  3232. The \key{xorq} instruction takes two arguments, performs a pairwise
  3233. exclusive-or operation on each bit of its arguments, and writes the
  3234. results into its second argument. Recall the truth table for
  3235. exclusive-or:
  3236. \begin{center}
  3237. \begin{tabular}{l|cc}
  3238. & 0 & 1 \\ \hline
  3239. 0 & 0 & 1 \\
  3240. 1 & 1 & 0
  3241. \end{tabular}
  3242. \end{center}
  3243. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3244. in row of the table for the bit $1$, the result is the opposite of the
  3245. second bit. Thus, the \code{not} operation can be implemented by
  3246. \code{xorq} with $1$ as the first argument: $0001
  3247. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3248. 0001 = 0000$.
  3249. \begin{figure}[tp]
  3250. \fbox{
  3251. \begin{minipage}{0.96\textwidth}
  3252. \[
  3253. \begin{array}{lcl}
  3254. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3255. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3256. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3257. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3258. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3259. (\key{subq} \; \Arg\; \Arg) \mid
  3260. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3261. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3262. (\key{pushq}\;\Arg) \mid
  3263. (\key{popq}\;\Arg) \mid
  3264. (\key{retq})} \\
  3265. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3266. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3267. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3268. \mid (\key{jmp} \; \itm{label})
  3269. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3270. &\mid& (\key{label} \; \itm{label}) \\
  3271. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3272. \end{array}
  3273. \]
  3274. \end{minipage}
  3275. }
  3276. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3277. \label{fig:x86-1}
  3278. \end{figure}
  3279. Next we consider the x86 instructions that are relevant for
  3280. compiling the comparison operations. The \key{cmpq} instruction
  3281. compares its two arguments to determine whether one argument is less
  3282. than, equal, or greater than the other argument. The \key{cmpq}
  3283. instruction is unusual regarding the order of its arguments and where
  3284. the result is placed. The argument order is backwards: if you want to
  3285. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3286. \key{cmpq} is placed in the special EFLAGS register. This register
  3287. cannot be accessed directly but it can be queried by a number of
  3288. instructions, including the \key{set} instruction. The \key{set}
  3289. instruction puts a \key{1} or \key{0} into its destination depending
  3290. on whether the comparison came out according to the condition code
  3291. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3292. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3293. The set instruction has an annoying quirk in that its destination
  3294. argument must be single byte register, such as \code{al}, which is
  3295. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3296. instruction can then be used to move from a single byte register to a
  3297. normal 64-bit register.
  3298. For compiling the \key{if} expression, the x86 instructions for
  3299. jumping are relevant. The \key{jmp} instruction updates the program
  3300. counter to point to the instruction after the indicated label. The
  3301. \key{jmp-if} instruction updates the program counter to point to the
  3302. instruction after the indicated label depending on whether the result
  3303. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3304. the \key{jmp-if} instruction falls through to the next
  3305. instruction. Our abstract syntax for \key{jmp-if} differs from the
  3306. concrete syntax for x86 to separate the instruction name from the
  3307. condition code. For example, \code{(jmp-if le foo)} corresponds to
  3308. \code{jle foo}.
  3309. \section{Select Instructions}
  3310. \label{sec:select-r2}
  3311. The \code{select-instructions} pass lowers from $C_1$ to another
  3312. intermediate representation suitable for conducting register
  3313. allocation, that is, a language close to x86$_1$.
  3314. We can take the usual approach of encoding Booleans as integers, with
  3315. true as 1 and false as 0.
  3316. \[
  3317. \key{\#t} \Rightarrow \key{1}
  3318. \qquad
  3319. \key{\#f} \Rightarrow \key{0}
  3320. \]
  3321. The \code{not} operation can be implemented in terms of \code{xorq}
  3322. as we discussed at the beginning of this section.
  3323. %% Can you think of a bit pattern that, when XOR'd with the bit
  3324. %% representation of 0 produces 1, and when XOR'd with the bit
  3325. %% representation of 1 produces 0?
  3326. Translating the \code{eq?} and the other comparison operations to x86
  3327. is slightly involved due to the unusual nature of the \key{cmpq}
  3328. instruction discussed above. We recommend translating an assignment
  3329. from \code{eq?} into the following sequence of three instructions. \\
  3330. \begin{tabular}{lll}
  3331. \begin{minipage}{0.4\textwidth}
  3332. \begin{lstlisting}
  3333. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3334. \end{lstlisting}
  3335. \end{minipage}
  3336. &
  3337. $\Rightarrow$
  3338. &
  3339. \begin{minipage}{0.4\textwidth}
  3340. \begin{lstlisting}
  3341. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3342. (set e (byte-reg al))
  3343. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3344. \end{lstlisting}
  3345. \end{minipage}
  3346. \end{tabular} \\
  3347. % The translation of the \code{not} operator is not quite as simple
  3348. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3349. % one. For example, the following program performs bitwise negation on
  3350. % the integer 1:
  3351. %
  3352. % \begin{tabular}{lll}
  3353. % \begin{minipage}{0.4\textwidth}
  3354. % \begin{lstlisting}
  3355. % (movq (int 1) (reg rax))
  3356. % (notq (reg rax))
  3357. % \end{lstlisting}
  3358. % \end{minipage}
  3359. % \end{tabular}
  3360. %
  3361. % After the program is run, \key{rax} does not contain 0, as you might
  3362. % hope -- it contains the binary value $111\ldots10$, which is the
  3363. % two's complement representation of $-2$. We recommend implementing boolean
  3364. % not by using \key{notq} and then masking the upper bits of the result with
  3365. % the \key{andq} instruction.
  3366. Regarding \key{if} statements, we recommend delaying when they are
  3367. lowered until the \code{patch-instructions} pass. The reason is that
  3368. for purposes of liveness analysis, \key{if} statements are easier to
  3369. deal with than jump instructions.
  3370. \begin{exercise}\normalfont
  3371. Expand your \code{select-instructions} pass to handle the new features
  3372. of the $R_2$ language. Test the pass on all the examples you have
  3373. created and make sure that you have some test programs that use the
  3374. \code{eq?} operator, creating some if necessary. Test the output of
  3375. \code{select-instructions} using the \code{interp-x86} interpreter
  3376. (Appendix~\ref{appendix:interp}).
  3377. \end{exercise}
  3378. \section{Register Allocation}
  3379. \label{sec:register-allocation-r2}
  3380. The changes required for $R_2$ affect the liveness analysis, building
  3381. the interference graph, and assigning homes, but the graph coloring
  3382. algorithm itself does not need to change.
  3383. \subsection{Liveness Analysis}
  3384. \label{sec:liveness-analysis-r2}
  3385. The addition of \key{if} statements brings up an interesting issue in
  3386. liveness analysis. Recall that liveness analysis works backwards
  3387. through the program, for each instruction it computes the variables
  3388. that are live before the instruction based on which variables are live
  3389. after the instruction. Now consider the situation for \code{(\key{if}
  3390. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know
  3391. the $L_{\mathsf{after}}$ set and we need to produce the
  3392. $L_{\mathsf{before}}$ set. We can recursively perform liveness
  3393. analysis on the $\itm{thns}$ and $\itm{elss}$ branches, using
  3394. $L_{\mathsf{after}}$ as the starting point, to obtain
  3395. $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3396. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3397. know, during compilation, which way the branch will go, so we do not
  3398. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3399. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3400. the entire \key{if} statement. The solution comes from the observation
  3401. that there is no harm in identifying more variables as live than
  3402. absolutely necessary. Thus, we can take the union of the live
  3403. variables from the two branches to be the live set for the whole
  3404. \key{if}, as shown below. Of course, we also need to include the
  3405. variables that are read in $e_1$ and $e_2$.
  3406. \[
  3407. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3408. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3409. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3410. \]
  3411. We need the live-after sets for all the instructions in both branches
  3412. of the \key{if} when we build the interference graph, so I recommend
  3413. storing that data in the \key{if} statement AST as follows:
  3414. \begin{lstlisting}
  3415. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3416. \end{lstlisting}
  3417. If you wrote helper functions for computing the variables in an
  3418. instruction's argument and for computing the variables read-from ($R$)
  3419. or written-to ($W$) by an instruction, you need to update them to
  3420. handle the new kinds of arguments and instructions in x86$_1$.
  3421. \subsection{Build Interference}
  3422. \label{sec:build-interference-r2}
  3423. Many of the new instructions, such as the logical operations, can be
  3424. handled in the same way as the arithmetic instructions. Thus, if your
  3425. code was already quite general, it will not need to be changed to
  3426. handle the logical operations. If not, I recommend that you change
  3427. your code to be more general. The \key{movzbq} instruction should be
  3428. handled like the \key{movq} instruction. The \key{if} statement is
  3429. straightforward to handle because we stored the live-after sets for
  3430. the two branches in the AST node as described above. Here we just need
  3431. to recursively process the two branches. The output of this pass can
  3432. discard the live after sets, as they are no longer needed.
  3433. \subsection{Assign Homes}
  3434. \label{sec:assign-homes-r2}
  3435. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3436. to be updated to handle the \key{if} statement, simply by recursively
  3437. processing the child nodes. Hopefully your code already handles the
  3438. other new instructions, but if not, you can generalize your code.
  3439. \begin{exercise}\normalfont
  3440. Implement the additions to the \code{register-allocation} pass so that
  3441. it works for $R_2$ and test your compiler using your previously
  3442. created programs on the \code{interp-x86} interpreter
  3443. (Appendix~\ref{appendix:interp}).
  3444. \end{exercise}
  3445. \section{Lower Conditionals (New Pass)}
  3446. \label{sec:lower-conditionals}
  3447. In the \code{select-instructions} pass we decided to procrastinate in
  3448. the lowering of the \key{if} statement, thereby making liveness
  3449. analysis easier. Now we need to make up for that and turn the \key{if}
  3450. statement into the appropriate instruction sequence. The following
  3451. translation gives the general idea. If the condition is true, we need
  3452. to execute the $\itm{thns}$ branch and otherwise we need to execute
  3453. the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3454. jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3455. is appropriate for the comparison operator \itm{cmp}. If the
  3456. condition is false, we fall through to the $\itm{elss}$ branch. At the
  3457. end of the $\itm{elss}$ branch we need to take care to not fall
  3458. through to the $\itm{thns}$ branch. So we jump to the
  3459. $\itm{endlabel}$. All of the labels in the generated code should be
  3460. created with \code{gensym}.
  3461. \begin{tabular}{lll}
  3462. \begin{minipage}{0.4\textwidth}
  3463. \begin{lstlisting}
  3464. (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3465. \end{lstlisting}
  3466. \end{minipage}
  3467. &
  3468. $\Rightarrow$
  3469. &
  3470. \begin{minipage}{0.4\textwidth}
  3471. \begin{lstlisting}
  3472. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3473. (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3474. |$\itm{elss}$|
  3475. (jmp |$\itm{endlabel}$|)
  3476. (label |$\itm{thenlabel}$|)
  3477. |$\itm{thns}$|
  3478. (label |$\itm{endlabel}$|)
  3479. \end{lstlisting}
  3480. \end{minipage}
  3481. \end{tabular}
  3482. \begin{exercise}\normalfont
  3483. Implement the \code{lower-conditionals} pass. Test your compiler using
  3484. your previously created programs on the \code{interp-x86} interpreter
  3485. (Appendix~\ref{appendix:interp}).
  3486. \end{exercise}
  3487. \section{Patch Instructions}
  3488. There are no special restrictions on the x86 instructions
  3489. \key{jmp-if}, \key{jmp}, and \key{label}, but there is an unusual
  3490. restriction on \key{cmpq}. The second argument is not allowed to be an
  3491. immediate value (such as a literal integer). If you are comparing two
  3492. immediates, you must insert another \key{movq} instruction to put the
  3493. second argument in \key{rax}.
  3494. \begin{exercise}\normalfont
  3495. Update \code{patch-instructions} to handle the new x86 instructions.
  3496. Test your compiler using your previously created programs on the
  3497. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3498. \end{exercise}
  3499. \section{An Example Translation}
  3500. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3501. $R_2$ translated to x86, showing the results of \code{flatten},
  3502. \code{select-instructions}, and the final x86 assembly.
  3503. \begin{figure}[tbp]
  3504. \begin{tabular}{lll}
  3505. \begin{minipage}{0.5\textwidth}
  3506. \begin{lstlisting}
  3507. (program
  3508. (if (eq? (read) 1) 42 0))
  3509. \end{lstlisting}
  3510. $\Downarrow$
  3511. \begin{lstlisting}
  3512. (program (t.1 t.2 if.1)
  3513. (assign t.1 (read))
  3514. (assign t.2 (eq? t.1 1))
  3515. (if (eq? #t t.2)
  3516. ((assign if.1 42))
  3517. ((assign if.1 0)))
  3518. (return if.1))
  3519. \end{lstlisting}
  3520. $\Downarrow$
  3521. \begin{lstlisting}
  3522. (program (t.1 t.2 if.1)
  3523. (callq read_int)
  3524. (movq (reg rax) (var t.1))
  3525. (cmpq (int 1) (var t.1))
  3526. (set e (byte-reg al))
  3527. (movzbq (byte-reg al) (var t.2))
  3528. (if (eq? (int 1) (var t.2))
  3529. ((movq (int 42) (var if.1)))
  3530. ((movq (int 0) (var if.1))))
  3531. (movq (var if.1) (reg rax)))
  3532. \end{lstlisting}
  3533. \end{minipage}
  3534. &
  3535. $\Rightarrow$
  3536. \begin{minipage}{0.4\textwidth}
  3537. \begin{lstlisting}
  3538. .globl _main
  3539. _main:
  3540. pushq %rbp
  3541. movq %rsp, %rbp
  3542. pushq %r15
  3543. pushq %r14
  3544. pushq %r13
  3545. pushq %r12
  3546. pushq %rbx
  3547. subq $8, %rsp
  3548. callq _read_int
  3549. movq %rax, %rcx
  3550. cmpq $1, %rcx
  3551. sete %al
  3552. movzbq %al, %rcx
  3553. cmpq $1, %rcx
  3554. je then21288
  3555. movq $0, %rbx
  3556. jmp if_end21289
  3557. then21288:
  3558. movq $42, %rbx
  3559. if_end21289:
  3560. movq %rbx, %rax
  3561. movq %rax, %rdi
  3562. callq _print_int
  3563. movq $0, %rax
  3564. addq $8, %rsp
  3565. popq %rbx
  3566. popq %r12
  3567. popq %r13
  3568. popq %r14
  3569. popq %r15
  3570. popq %rbp
  3571. retq
  3572. \end{lstlisting}
  3573. \end{minipage}
  3574. \end{tabular}
  3575. \caption{Example compilation of an \key{if} expression to x86.}
  3576. \label{fig:if-example-x86}
  3577. \end{figure}
  3578. \begin{figure}[p]
  3579. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3580. \node (R2) at (0,2) {\large $R_2$};
  3581. \node (R2-2) at (3,2) {\large $R_2$};
  3582. \node (R2-3) at (6,2) {\large $R_2$};
  3583. \node (C1-1) at (3,0) {\large $C_1$};
  3584. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3585. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3586. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3587. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3588. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3589. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3590. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3591. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3592. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize uniquify} (R2-3);
  3593. \path[->,bend left=15] (R2-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C1-1);
  3594. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3595. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3596. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3597. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3598. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} lower-cond.} (x86-4);
  3599. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-5);
  3600. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3601. \end{tikzpicture}
  3602. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3603. \label{fig:R2-passes}
  3604. \end{figure}
  3605. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3606. for the compilation of $R_2$.
  3607. \section{Challenge: Optimizing Conditions$^{*}$}
  3608. \label{sec:opt-if}
  3609. A close inspection of the x86 code generated in
  3610. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3611. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3612. twice using \key{cmpq} as follows.
  3613. % Wierd LaTeX bug if I remove the following. -Jeremy
  3614. % Does it have to do with page breaks?
  3615. \begin{lstlisting}
  3616. \end{lstlisting}
  3617. \begin{lstlisting}
  3618. cmpq $1, %rcx
  3619. sete %al
  3620. movzbq %al, %rcx
  3621. cmpq $1, %rcx
  3622. je then21288
  3623. \end{lstlisting}
  3624. The reason for this non-optimal code has to do with the \code{flatten}
  3625. pass earlier in this Chapter. We recommended flattening the condition
  3626. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3627. is already an \code{eq?} test, then we would like to use that
  3628. directly. In fact, for many of the expressions of Boolean type, we can
  3629. generate more optimized code. For example, if the condition is
  3630. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3631. all. If the condition is a \code{let}, we can optimize based on the
  3632. form of its body. If the condition is a \code{not}, then we can flip
  3633. the two branches.
  3634. %
  3635. \margincomment{\tiny We could do even better by converting to basic
  3636. blocks.\\ --Jeremy}
  3637. %
  3638. On the other hand, if the condition is a \code{and}
  3639. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3640. code duplication.
  3641. Figure~\ref{fig:opt-if} shows an example program and the result of
  3642. applying the above suggested optimizations.
  3643. \begin{exercise}\normalfont
  3644. Change the \code{flatten} pass to improve the code that gets
  3645. generated for \code{if} expressions. We recommend writing a helper
  3646. function that recursively traverses the condition of the \code{if}.
  3647. \end{exercise}
  3648. \begin{figure}[tbp]
  3649. \begin{tabular}{lll}
  3650. \begin{minipage}{0.5\textwidth}
  3651. \begin{lstlisting}
  3652. (program
  3653. (if (let ([x 1])
  3654. (not (eq? x (read))))
  3655. 777
  3656. 42))
  3657. \end{lstlisting}
  3658. $\Downarrow$
  3659. \begin{lstlisting}
  3660. (program (x.1 if.2 tmp.3)
  3661. (type Integer)
  3662. (assign x.1 1)
  3663. (assign tmp.3 (read))
  3664. (if (eq? x.1 tmp.3)
  3665. ((assign if.2 42))
  3666. ((assign if.2 777)))
  3667. (return if.2))
  3668. \end{lstlisting}
  3669. $\Downarrow$
  3670. \begin{lstlisting}
  3671. (program (x.1 if.2 tmp.3)
  3672. (type Integer)
  3673. (movq (int 1) (var x.1))
  3674. (callq read_int)
  3675. (movq (reg rax) (var tmp.3))
  3676. (if (eq? (var x.1) (var tmp.3))
  3677. ((movq (int 42) (var if.2)))
  3678. ((movq (int 777) (var if.2))))
  3679. (movq (var if.2) (reg rax)))
  3680. \end{lstlisting}
  3681. \end{minipage}
  3682. &
  3683. $\Rightarrow$
  3684. \begin{minipage}{0.4\textwidth}
  3685. \begin{lstlisting}
  3686. .globl _main
  3687. _main:
  3688. pushq %rbp
  3689. movq %rsp, %rbp
  3690. pushq %r13
  3691. pushq %r14
  3692. pushq %r12
  3693. pushq %rbx
  3694. subq $0, %rsp
  3695. movq $1, %rbx
  3696. callq _read_int
  3697. movq %rax, %rcx
  3698. cmpq %rcx, %rbx
  3699. je then35989
  3700. movq $777, %rbx
  3701. jmp if_end35990
  3702. then35989:
  3703. movq $42, %rbx
  3704. if_end35990:
  3705. movq %rbx, %rax
  3706. movq %rax, %rdi
  3707. callq _print_int
  3708. movq $0, %rax
  3709. addq $0, %rsp
  3710. popq %rbx
  3711. popq %r12
  3712. popq %r14
  3713. popq %r13
  3714. popq %rbp
  3715. retq
  3716. \end{lstlisting}
  3717. \end{minipage}
  3718. \end{tabular}
  3719. \caption{Example program with optimized conditionals.}
  3720. \label{fig:opt-if}
  3721. \end{figure}
  3722. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3723. \chapter{Tuples and Garbage Collection}
  3724. \label{ch:tuples}
  3725. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  3726. things to discuss in this chapter. \\ --Jeremy}
  3727. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3728. all the IR grammars are spelled out! \\ --Jeremy}
  3729. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  3730. but keep type annotations on vector creation and local variables, function
  3731. parameters, etc. \\ --Jeremy}
  3732. In this chapter we study the implementation of mutable tuples (called
  3733. ``vectors'' in Racket). This language feature is the first to use the
  3734. computer's \emph{heap} because the lifetime of a Racket tuple is
  3735. indefinite, that is, a tuple does not follow a stack (FIFO) discipline
  3736. but instead lives forever from the programmer's viewpoint. Of course,
  3737. from an implementor's viewpoint, it is important to reclaim the space
  3738. associated with tuples when they are no longer needed, which is why we
  3739. also study \emph{garbage collection} techniques in this chapter.
  3740. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3741. interpreter and type checker. The $R_3$ language extends the $R_2$
  3742. language of Chapter~\ref{ch:bool-types} with vectors and void values
  3743. (because the \code{vector-set!} operation returns a void
  3744. value). Section~\ref{sec:GC} describes a garbage collection algorithm
  3745. based on copying live objects back and forth between two halves of the
  3746. heap. The garbage collector requires coordination with the compiler so
  3747. that it can see all of the \emph{root} pointers, that is, pointers in
  3748. registers or on the procedure call stack.
  3749. Section~\ref{sec:code-generation-gc} discusses all the necessary
  3750. changes and additions to the compiler passes, including type checking,
  3751. instruction selection, register allocation, and a new compiler pass
  3752. named \code{expose-allocation}.
  3753. \section{The $R_3$ Language}
  3754. \label{sec:r3}
  3755. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3756. includes three new forms for creating a tuple, reading an element of a
  3757. tuple, and writing to an element of a tuple. The program in
  3758. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3759. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3760. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3761. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3762. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3763. $40$, to which we add the $2$, the element at index $0$ of the
  3764. 1-tuple.
  3765. \begin{figure}[tbp]
  3766. \begin{lstlisting}
  3767. (let ([t (vector 40 #t (vector 2))])
  3768. (if (vector-ref t 1)
  3769. (+ (vector-ref t 0)
  3770. (vector-ref (vector-ref t 2) 0))
  3771. 44))
  3772. \end{lstlisting}
  3773. \caption{Example program that creates tuples and reads from them.}
  3774. \label{fig:vector-eg}
  3775. \end{figure}
  3776. \begin{figure}[tbp]
  3777. \centering
  3778. \fbox{
  3779. \begin{minipage}{0.96\textwidth}
  3780. \[
  3781. \begin{array}{lcl}
  3782. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3783. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3784. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3785. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3786. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3787. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3788. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3789. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3790. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3791. (\key{vector-ref}\;\Exp\;\Int) \\
  3792. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3793. &\mid& (\key{void}) \\
  3794. R_3 &::=& (\key{program} \; \Exp)
  3795. \end{array}
  3796. \]
  3797. \end{minipage}
  3798. }
  3799. \caption{The syntax of $R_3$, extending $R_2$ with tuples.}
  3800. \label{fig:r3-syntax}
  3801. \end{figure}
  3802. Tuples are our first encounter with heap-allocated data, which raises
  3803. several interesting issues. First, variable binding performs a
  3804. shallow-copy when dealing with tuples, which means that different
  3805. variables can refer to the same tuple, i.e., different variables can
  3806. be \emph{aliases} for the same thing. Consider the following example
  3807. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  3808. the mutation through \code{t2} is visible when referencing the tuple
  3809. from \code{t1}, so the result of this program is \code{42}.
  3810. \begin{lstlisting}
  3811. (let ([t1 (vector 3 7)])
  3812. (let ([t2 t1])
  3813. (let ([_ (vector-set! t2 0 42)])
  3814. (vector-ref t1 0))))
  3815. \end{lstlisting}
  3816. The next issue concerns the lifetime of tuples. Of course, they are
  3817. created by the \code{vector} form, but when does their lifetime end?
  3818. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3819. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  3820. is not tied to any notion of static scoping. For example, the
  3821. following program returns \code{3} even though the variable \code{t}
  3822. goes out of scope prior to accessing the vector.
  3823. \begin{lstlisting}
  3824. (vector-ref
  3825. (let ([t (vector 3 7)])
  3826. t)
  3827. 0)
  3828. \end{lstlisting}
  3829. From the perspective of programmer-observable behavior, tuples live
  3830. forever. Of course, if they really lived forever, then many programs
  3831. would run out of memory.\footnote{The $R_3$ language does not have
  3832. looping or recursive function, so it is nigh impossible to write a
  3833. program in $R_3$ that will run out of memory. However, we add
  3834. recursive functions in the next Chapter!} A Racket implementation
  3835. must therefore perform automatic garbage collection.
  3836. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3837. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3838. checker. The additions to the interpreter are straightforward but the
  3839. updates to the type checker deserve some explanation. As we shall see
  3840. in Section~\ref{sec:GC}, we need to know which variables are pointers
  3841. into the heap, that is, which variables are vectors. Also, when
  3842. allocating a vector, we shall need to know which elements of the
  3843. vector are pointers. We can obtain this information during type
  3844. checking and flattening. The type checker in
  3845. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  3846. expression, it also wraps every sub-expression $e$ with the form
  3847. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  3848. the flatten pass (Section~\ref{sec:flatten-gc}) this type information is
  3849. propagated to all variables (including temporaries generated during
  3850. flattening).
  3851. \begin{figure}[tbp]
  3852. \begin{lstlisting}
  3853. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3854. (define (interp-op op)
  3855. (match op
  3856. ...
  3857. ['vector vector]
  3858. ['vector-ref vector-ref]
  3859. ['vector-set! vector-set!]
  3860. [else (error 'interp-op "unknown operator")]))
  3861. (define (interp-R3 env)
  3862. (lambda (e)
  3863. (match e
  3864. ...
  3865. [else (error 'interp-R3 "unrecognized expression")]
  3866. )))
  3867. \end{lstlisting}
  3868. \caption{Interpreter for the $R_3$ language.}
  3869. \label{fig:interp-R3}
  3870. \end{figure}
  3871. \begin{figure}[tbp]
  3872. \begin{lstlisting}
  3873. (define (type-check-exp env)
  3874. (lambda (e)
  3875. (define recur (type-check-exp env))
  3876. (match e
  3877. ...
  3878. ['(void) (values '(has-type (void) Void) 'Void)]
  3879. [`(vector ,(app recur e* t*) ...)
  3880. (let ([t `(Vector ,@t*)])
  3881. (values `(has-type (vector ,@e*) ,t) t))]
  3882. [`(vector-ref ,(app recur e t) ,i)
  3883. (match t
  3884. [`(Vector ,ts ...)
  3885. (unless (and (exact-nonnegative-integer? i)
  3886. (i . < . (length ts)))
  3887. (error 'type-check-exp "invalid index ~a" i))
  3888. (let ([t (list-ref ts i)])
  3889. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3890. t))]
  3891. [else (error "expected a vector in vector-ref, not" t)])]
  3892. [`(vector-set! ,(app recur e-vec t-vec) ,i
  3893. ,(app recur e-arg t-arg))
  3894. (match t-vec
  3895. [`(Vector ,ts ...)
  3896. (unless (and (exact-nonnegative-integer? i)
  3897. (i . < . (length ts)))
  3898. (error 'type-check-exp "invalid index ~a" i))
  3899. (unless (equal? (list-ref ts i) t-arg)
  3900. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  3901. (list-ref ts i) t-arg))
  3902. (values `(has-type (vector-set! ,e-vec
  3903. (has-type ,i Integer)
  3904. ,e-arg) Void) 'Void)]
  3905. [else (error 'type-check-exp
  3906. "expected a vector in vector-set!, not ~a" t-vec)])]
  3907. [`(eq? ,(app recur e1 t1) ,(app recur e2 t2))
  3908. (match* (t1 t2)
  3909. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3910. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3911. [(other wise) ((super type-check-exp env) e)])]
  3912. )))
  3913. \end{lstlisting}
  3914. \caption{Type checker for the $R_3$ language.}
  3915. \label{fig:typecheck-R3}
  3916. \end{figure}
  3917. \section{Garbage Collection}
  3918. \label{sec:GC}
  3919. Here we study a relatively simple algorithm for garbage collection
  3920. that is the basis of state-of-the-art garbage
  3921. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3922. particular, we describe a two-space copying
  3923. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3924. perform the
  3925. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3926. coarse-grained depiction of what happens in a two-space collector,
  3927. showing two time steps, prior to garbage collection on the top and
  3928. after garbage collection on the bottom. In a two-space collector, the
  3929. heap is divided into two parts, the FromSpace and the
  3930. ToSpace. Initially, all allocations go to the FromSpace until there is
  3931. not enough room for the next allocation request. At that point, the
  3932. garbage collector goes to work to make more room.
  3933. The garbage collector must be careful not to reclaim tuples that will
  3934. be used by the program in the future. Of course, it is impossible in
  3935. general to predict what a program will do, but we can overapproximate
  3936. the will-be-used tuples by preserving all tuples that could be
  3937. accessed by \emph{any} program given the current computer state. A
  3938. program could access any tuple whose address is in a register or on
  3939. the procedure call stack. These addresses are called the \emph{root
  3940. set}. In addition, a program could access any tuple that is
  3941. transitively reachable from the root set. Thus, it is safe for the
  3942. garbage collector to reclaim the tuples that are not reachable in this
  3943. way.
  3944. So the goal of the garbage collector is twofold:
  3945. \begin{enumerate}
  3946. \item preserve all tuple that are reachable from the root set via a
  3947. path of pointers, that is, the \emph{live} tuples, and
  3948. \item reclaim the memory of everything else, that is, the
  3949. \emph{garbage}.
  3950. \end{enumerate}
  3951. A copying collector accomplishes this by copying all of the live
  3952. objects from the FromSpace into the ToSpace and then performs a slight
  3953. of hand, treating the ToSpace as the new FromSpace and the old
  3954. FromSpace as the new ToSpace. In the example of
  3955. Figure~\ref{fig:copying-collector}, there are three pointers in the
  3956. root set, one in a register and two on the stack. All of the live
  3957. objects have been copied to the ToSpace (the right-hand side of
  3958. Figure~\ref{fig:copying-collector}) in a way that preserves the
  3959. pointer relationships. For example, the pointer in the register still
  3960. points to a 2-tuple whose first element is a 3-tuple and second
  3961. element is a 2-tuple. There are four tuples that are not reachable
  3962. from the root set and therefore do not get copied into the ToSpace.
  3963. (The sitation in Figure~\ref{fig:copying-collector}, with a
  3964. cycle, cannot be created by a well-typed program in $R_3$. However,
  3965. creating cycles will be possible once we get to $R_6$. We design
  3966. the garbage collector to deal with cycles to begin with, so we will
  3967. not need to revisit this issue.)
  3968. \begin{figure}[tbp]
  3969. \centering
  3970. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  3971. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  3972. \caption{A copying collector in action.}
  3973. \label{fig:copying-collector}
  3974. \end{figure}
  3975. There are many alternatives to copying collectors (and their older
  3976. siblings, the generational collectors) when its comes to garbage
  3977. collection, such as mark-and-sweep and reference counting. The
  3978. strengths of copying collectors are that allocation is fast (just a
  3979. test and pointer increment), there is no fragmentation, cyclic garbage
  3980. is collected, and the time complexity of collection only depends on
  3981. the amount of live data, and not on the amount of
  3982. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  3983. copying collectors is that they use a lot of space, though that
  3984. problem is ameliorated in generational collectors. Racket and Scheme
  3985. programs tend to allocate many small objects and generate a lot of
  3986. garbage, so copying and generational collectors are a good fit. Of
  3987. course, garbage collection is an active research topic, especially
  3988. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  3989. continuously developing new techniques and revisiting old
  3990. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  3991. \subsection{Graph Copying via Cheney's Algorithm}
  3992. \label{sec:cheney}
  3993. Let us take a closer look at how the copy works. The allocated objects
  3994. and pointers can be viewed as a graph and we need to copy the part of
  3995. the graph that is reachable from the root set. To make sure we copy
  3996. all of the reachable vertices in the graph, we need an exhaustive
  3997. graph traversal algorithm, such as depth-first search or breadth-first
  3998. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3999. take into account the possibility of cycles by marking which vertices
  4000. have already been visited, so as to ensure termination of the
  4001. algorithm. These search algorithms also use a data structure such as a
  4002. stack or queue as a to-do list to keep track of the vertices that need
  4003. to be visited. We shall use breadth-first search and a trick due to
  4004. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4005. copying tuples into the ToSpace.
  4006. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4007. copy progresses. The queue is represented by a chunk of contiguous
  4008. memory at the beginning of the ToSpace, using two pointers to track
  4009. the front and the back of the queue. The algorithm starts by copying
  4010. all tuples that are immediately reachable from the root set into the
  4011. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4012. old tuple to indicate that it has been visited. (We discuss the
  4013. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4014. inside the copied tuples in the queue still point back to the
  4015. FromSpace. Once the initial queue has been created, the algorithm
  4016. enters a loop in which it repeatedly processes the tuple at the front
  4017. of the queue and pops it off the queue. To process a tuple, the
  4018. algorithm copies all the tuple that are directly reachable from it to
  4019. the ToSpace, placing them at the back of the queue. The algorithm then
  4020. updates the pointers in the popped tuple so they point to the newly
  4021. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4022. step we copy the tuple whose second element is $42$ to the back of the
  4023. queue. The other pointer goes to a tuple that has already been copied,
  4024. so we do not need to copy it again, but we do need to update the
  4025. pointer to the new location. This can be accomplished by storing a
  4026. \emph{forwarding} pointer to the new location in the old tuple, back
  4027. when we initially copied the tuple into the ToSpace. This completes
  4028. one step of the algorithm. The algorithm continues in this way until
  4029. the front of the queue is empty, that is, until the front catches up
  4030. with the back.
  4031. \begin{figure}[tbp]
  4032. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4033. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4034. \label{fig:cheney}
  4035. \end{figure}
  4036. \subsection{Data Representation}
  4037. \label{sec:data-rep-gc}
  4038. The garbage collector places some requirements on the data
  4039. representations used by our compiler. First, the garbage collector
  4040. needs to distinguish between pointers and other kinds of data. There
  4041. are several ways to accomplish this.
  4042. \begin{enumerate}
  4043. \item Attached a tag to each object that identifies what type of
  4044. object it is~\citep{McCarthy:1960dz}.
  4045. \item Store different types of objects in different
  4046. regions~\citep{Steele:1977ab}.
  4047. \item Use type information from the program to either generate
  4048. type-specific code for collecting or to generate tables that can
  4049. guide the
  4050. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4051. \end{enumerate}
  4052. Dynamically typed languages, such as Lisp, need to tag objects
  4053. anyways, so option 1 is a natural choice for those languages.
  4054. However, $R_3$ is a statically typed language, so it would be
  4055. unfortunate to require tags on every object, especially small and
  4056. pervasive objects like integers and Booleans. Option 3 is the
  4057. best-performing choice for statically typed languages, but comes with
  4058. a relatively high implementation complexity. To keep this chapter to a
  4059. 2-week time budget, we recommend a combination of options 1 and 2,
  4060. with separate strategies used for the stack and the heap.
  4061. Regarding the stack, we recommend using a separate stack for
  4062. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4063. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4064. local variable needs to be spilled and is of type \code{(Vector
  4065. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4066. of the normal procedure call stack. Furthermore, we always spill
  4067. vector-typed variables if they are live during a call to the
  4068. collector, thereby ensuring that no pointers are in registers during a
  4069. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4070. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4071. layout using a root stack. The root stack contains the two pointers
  4072. from the regular stack and also the pointer in the second
  4073. register.
  4074. \begin{figure}[tbp]
  4075. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4076. \caption{Maintaining a root stack to facilitate garbage collection.}
  4077. \label{fig:shadow-stack}
  4078. \end{figure}
  4079. The problem of distinguishing between pointers and other kinds of data
  4080. also arises inside of each tuple. We solve this problem by attaching a
  4081. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4082. in on the tags for two of the tuples in the example from
  4083. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4084. in a big-endian way, from right-to-left, with bit location 0 (the
  4085. least significant bit) on the far right, which corresponds to the
  4086. directionality of the x86 shifting instructions \key{salq} (shift
  4087. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4088. specifying which elements of the tuple are pointers, the part labeled
  4089. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4090. a pointer and a 0 bit indicates some other kind of data. The pointer
  4091. mask starts at bit location 7. We have limited tuples to a maximum
  4092. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4093. tag also contains two other pieces of information. The length of the
  4094. tuple (number of elements) is stored in bits location 1 through
  4095. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4096. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4097. has not yet been copied. If the bit has value 0 then the entire tag
  4098. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4099. always zero anyways because our tuples are 8-byte aligned.)
  4100. \begin{figure}[tbp]
  4101. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4102. \caption{Representation for tuples in the heap.}
  4103. \label{fig:tuple-rep}
  4104. \end{figure}
  4105. \subsection{Implementation of the Garbage Collector}
  4106. \label{sec:organize-gz}
  4107. The implementation of the garbage collector needs to do a lot of
  4108. bit-level data manipulation and we need to link it with our
  4109. compiler-generated x86 code. Thus, we recommend implementing the
  4110. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4111. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4112. interface to the garbage collector. The \code{initialize} function
  4113. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4114. function is meant to be called near the beginning of \code{main},
  4115. before the rest of the program executes. The \code{initialize}
  4116. function puts the address of the beginning of the FromSpace into the
  4117. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4118. points to the address that is 1-past the last element of the
  4119. FromSpace. (We use half-open intervals to represent chunks of
  4120. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4121. points to the first element of the root stack.
  4122. As long as there is room left in the FromSpace, your generated code
  4123. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4124. %
  4125. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4126. --Jeremy}
  4127. %
  4128. The amount of room left in FromSpace is the difference between the
  4129. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4130. function should be called when there is not enough room left in the
  4131. FromSpace for the next allocation. The \code{collect} function takes
  4132. a pointer to the current top of the root stack (one past the last item
  4133. that was pushed) and the number of bytes that need to be
  4134. allocated. The \code{collect} function performs the copying collection
  4135. and leaves the heap in a state such that the next allocation will
  4136. succeed.
  4137. \begin{figure}[tbp]
  4138. \begin{lstlisting}
  4139. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4140. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4141. int64_t* free_ptr;
  4142. int64_t* fromspace_begin;
  4143. int64_t* fromspace_end;
  4144. int64_t** rootstack_begin;
  4145. \end{lstlisting}
  4146. \caption{The compiler's interface to the garbage collector.}
  4147. \label{fig:gc-header}
  4148. \end{figure}
  4149. \begin{exercise}
  4150. In the file \code{runtime.c} you will find the implementation of
  4151. \code{initialize} and a partial implementation of \code{collect}.
  4152. The \code{collect} function calls another function, \code{cheney},
  4153. to perform the actual copy, and that function is left to the reader
  4154. to implement. The following is the prototype for \code{cheney}.
  4155. \begin{lstlisting}
  4156. static void cheney(int64_t** rootstack_ptr);
  4157. \end{lstlisting}
  4158. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4159. rootstack (which is an array of pointers). The \code{cheney} function
  4160. also communicates with \code{collect} through several global
  4161. variables, the \code{fromspace\_begin} and \code{fromspace\_end}
  4162. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4163. the ToSpace:
  4164. \begin{lstlisting}
  4165. static int64_t* tospace_begin;
  4166. static int64_t* tospace_end;
  4167. \end{lstlisting}
  4168. The job of the \code{cheney} function is to copy all the live
  4169. objects (reachable from the root stack) into the ToSpace, update
  4170. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4171. update the root stack so that it points to the objects in the
  4172. ToSpace, and finally to swap the global pointers for the FromSpace
  4173. and ToSpace.
  4174. \end{exercise}
  4175. \section{Compiler Passes}
  4176. \label{sec:code-generation-gc}
  4177. The introduction of garbage collection has a non-trivial impact on our
  4178. compiler passes. We introduce one new compiler pass called
  4179. \code{expose-allocation} and make non-trivial changes to
  4180. \code{type-check}, \code{flatten}, \code{select-instructions},
  4181. \code{allocate-registers}, and \code{print-x86}. The following
  4182. program will serve as our running example. It creates two tuples, one
  4183. nested inside the other. Both tuples have length one. The example then
  4184. accesses the element in the inner tuple tuple via two vector
  4185. references.
  4186. % tests/s2_17.rkt
  4187. \begin{lstlisting}
  4188. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4189. \end{lstlisting}
  4190. We already discuss the changes to \code{type-check} in
  4191. Section~\ref{sec:r3}, including the addition of \code{has-type}, so we
  4192. proceed to discuss the new \code{expose-allocation} pass.
  4193. \subsection{Expose Allocation (New)}
  4194. \label{sec:expose-allocation}
  4195. The pass \code{expose-allocation} lowers the \code{vector} creation
  4196. form into a conditional call to the collector followed by the
  4197. allocation. We choose to place the \code{expose-allocation} pass
  4198. before \code{flatten} because \code{expose-allocation} introduces new
  4199. variables, which can be done locally with \code{let}, but \code{let}
  4200. is gone after \code{flatten}. In the following, we show the
  4201. transformation for the \code{vector} form into let-bindings for the
  4202. intializing expressions, by a conditional \code{collect}, an
  4203. \code{allocate}, and the initialization of the vector.
  4204. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4205. total bytes need to be allocated for the vector, which is 8 for the
  4206. tag plus \itm{len} times 8.)
  4207. \begin{lstlisting}
  4208. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4209. |$\Longrightarrow$|
  4210. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4211. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4212. (global-value fromspace_end))
  4213. (void)
  4214. (collect |\itm{bytes}|))])
  4215. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4216. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4217. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4218. |$v$|) ... )))) ...)
  4219. \end{lstlisting}
  4220. (In the above, we suppressed all of the \code{has-type} forms in the
  4221. output for the sake of readability.) The placement of the initializing
  4222. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4223. the sequence of \code{vector-set!}'s is important, as those expressions
  4224. may trigger garbage collection and we do not want an allocated but
  4225. uninitialized tuple to be present during a garbage collection.
  4226. The output of \code{expose-allocation} is a language that extends
  4227. $R_3$ with the three new forms that we use above in the translation of
  4228. \code{vector}.
  4229. \[
  4230. \begin{array}{lcl}
  4231. \Exp &::=& \cdots
  4232. \mid (\key{collect} \,\itm{int})
  4233. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4234. \mid (\key{global-value} \,\itm{name})
  4235. \end{array}
  4236. \]
  4237. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4238. %% the beginning of the program which will instruct the garbage collector
  4239. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4240. %% two arguments of \code{initialize} specify the initial allocated space
  4241. %% for the root stack and for the heap.
  4242. %
  4243. %% The \code{expose-allocation} pass annotates all of the local variables
  4244. %% in the \code{program} form with their type.
  4245. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4246. \code{expose-allocation} pass on our running example.
  4247. \begin{figure}[tbp]
  4248. \begin{lstlisting}
  4249. (program (type Integer)
  4250. (vector-ref
  4251. (vector-ref
  4252. (let ((vecinit32990
  4253. (let ([vecinit32986 42])
  4254. (let ((collectret32988
  4255. (if (< (+ (global-value free_ptr) 16)
  4256. (global-value fromspace_end))
  4257. (void)
  4258. (collect 16))))
  4259. (let ([alloc32985
  4260. (allocate 1 (Vector Integer))])
  4261. (let ([initret32987
  4262. (vector-set! alloc32985 0 vecinit32986)])
  4263. alloc32985))))))
  4264. (let ([collectret32992
  4265. (if (< (+ (global-value free_ptr) 16)
  4266. (global-value fromspace_end))
  4267. (void)
  4268. (collect 16))])
  4269. (let ([alloc32989 (allocate 1 (Vector (Vector Integer)))])
  4270. (let ([initret32991 (vector-set! alloc32989 0 vecinit32990)])
  4271. alloc32989))))
  4272. 0)
  4273. 0))
  4274. \end{lstlisting}
  4275. \caption{Output of the \code{expose-allocation} pass, minus
  4276. all of the \code{has-type} forms.}
  4277. \label{fig:expose-alloc-output}
  4278. \end{figure}
  4279. \clearpage
  4280. \subsection{Flatten and the $C_2$ intermediate language}
  4281. \label{sec:flatten-gc}
  4282. \begin{figure}[tp]
  4283. \fbox{
  4284. \begin{minipage}{0.96\textwidth}
  4285. \[
  4286. \begin{array}{lcl}
  4287. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4288. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4289. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4290. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4291. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4292. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4293. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4294. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4295. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4296. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4297. &\mid& (\key{collect} \,\itm{int}) \\
  4298. C_2 & ::= & (\key{program}\;((\Var \key{.} \itm{type})^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  4299. \end{array}
  4300. \]
  4301. \end{minipage}
  4302. }
  4303. \caption{The $C_2$ language, extending $C_1$ with support for tuples.}
  4304. \label{fig:c2-syntax}
  4305. \end{figure}
  4306. The output of \code{flatten} is a program in the intermediate language
  4307. $C_2$, whose syntax is defined in Figure~\ref{fig:c2-syntax}. The new
  4308. forms of $C_2$ include the expressions \key{allocate},
  4309. \key{vector-ref}, and \key{vector-set!}, and \key{global-value} and
  4310. the statement \code{collect}. The \code{flatten} pass can treat these
  4311. new forms much like the other forms.
  4312. Recall that the \code{flatten} function collects all of the local
  4313. variables so that it can decorate the \code{program} form with
  4314. them. Also recall that we need to know the types of all the local
  4315. variables for purposes of identifying the root set for the garbage
  4316. collector. Thus, we change \code{flatten} to collect not just the
  4317. variables, but the variables and their types in the form of an
  4318. association list. Thanks to the \code{has-type} forms, the types are
  4319. readily available. For example, consider the translation of the
  4320. \code{let} form.
  4321. \begin{lstlisting}
  4322. (let ([|$x$| (has-type |\itm{rhs}| |\itm{type}|)]) |\itm{body}|)
  4323. |$\Longrightarrow$|
  4324. (values |\itm{body'}|
  4325. (|\itm{ss_1}| (assign |$x$| |\itm{rhs'}|) |\itm{ss_2}|)
  4326. ((|$x$| . |\itm{type}|) |\itm{xt_1}| |\itm{xt_2}|))
  4327. \end{lstlisting}
  4328. where \itm{rhs'}, \itm{ss_1}, and \itm{xs_1} are the results of
  4329. recursively flattening \itm{rhs} and \itm{body'}, \itm{ss_2}, and
  4330. \itm{xs_2} are the results of recursively flattening \itm{body}. The
  4331. output on our running example is shown in Figure~\ref{fig:flatten-gc}.
  4332. \begin{figure}[tbp]
  4333. \begin{lstlisting}
  4334. '(program
  4335. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4336. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void)
  4337. (tmp94 . Integer) (tmp93 . Integer) (tmp95 . Integer)
  4338. (tmp85 Vector Integer) (tmp87 . Void) (tmp92 . Void)
  4339. (tmp00 . Void) (tmp98 . Integer) (tmp97 . Integer)
  4340. (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4341. (tmp91 . Void))
  4342. (type Integer)
  4343. (assign tmp86 42)
  4344. (assign tmp93 (global-value free_ptr))
  4345. (assign tmp94 (+ tmp93 16))
  4346. (assign tmp95 (global-value fromspace_end))
  4347. (if (< tmp94 tmp95)
  4348. ((assign tmp96 (void)))
  4349. ((collect 16) (assign tmp96 (void))))
  4350. (assign tmp88 tmp96)
  4351. (assign tmp85 (allocate 1 (Vector Integer)))
  4352. (assign tmp87 (vector-set! tmp85 0 tmp86))
  4353. (assign tmp90 tmp85)
  4354. (assign tmp97 (global-value free_ptr))
  4355. (assign tmp98 (+ tmp97 16))
  4356. (assign tmp99 (global-value fromspace_end))
  4357. (if (< tmp98 tmp99)
  4358. ((assign tmp00 (void)))
  4359. ((collect 16) (assign tmp00 (void))))
  4360. (assign tmp92 tmp00)
  4361. (assign tmp89 (allocate 1 (Vector (Vector Integer))))
  4362. (assign tmp91 (vector-set! tmp89 0 tmp90))
  4363. (assign tmp01 (vector-ref tmp89 0))
  4364. (assign tmp02 (vector-ref tmp01 0))
  4365. (return tmp02))
  4366. \end{lstlisting}
  4367. \caption{Output of \code{flatten} for the running example.}
  4368. \label{fig:flatten-gc}
  4369. \end{figure}
  4370. \clearpage
  4371. \subsection{Select Instructions}
  4372. \label{sec:select-instructions-gc}
  4373. %% void (rep as zero)
  4374. %% allocate
  4375. %% collect (callq collect)
  4376. %% vector-ref
  4377. %% vector-set!
  4378. %% global-value (postpone)
  4379. In this pass we generate x86 code for most of the new operations that
  4380. were needed to compile tuples, including \code{allocate},
  4381. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4382. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4383. The \code{vector-ref} and \code{vector-set!} forms translate into
  4384. \code{movq} instructions with the appropriate \key{deref}. (The
  4385. plus one is to get past the tag at the beginning of the tuple
  4386. representation.)
  4387. \begin{lstlisting}
  4388. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4389. |$\Longrightarrow$|
  4390. (movq |$\itm{vec}'$| (reg r11))
  4391. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4392. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4393. |$\Longrightarrow$|
  4394. (movq |$\itm{vec}'$| (reg r11))
  4395. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4396. (movq (int 0) |$\itm{lhs}$|)
  4397. \end{lstlisting}
  4398. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4399. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4400. register \code{r11} ensures that offsets are only performed with
  4401. register operands. This requires removing \code{r11} from
  4402. consideration by the register allocating.
  4403. We compile the \code{allocate} form to operations on the
  4404. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4405. is the next free address in the FromSpace, so we move it into the
  4406. \itm{lhs} and then move it forward by enough space for the tuple being
  4407. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4408. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4409. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4410. how the tag is organized. We recommend using the Racket operations
  4411. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4412. The type annoation in the \code{vector} form is used to determine the
  4413. pointer mask region of the tag.
  4414. \begin{lstlisting}
  4415. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4416. |$\Longrightarrow$|
  4417. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4418. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4419. (movq |$\itm{lhs}'$| (reg r11))
  4420. (movq (int |$\itm{tag}$|) (deref r11 0))
  4421. \end{lstlisting}
  4422. The \code{collect} form is compiled to a call to the \code{collect}
  4423. function in the runtime. The arguments to \code{collect} are the top
  4424. of the root stack and the number of bytes that need to be allocated.
  4425. We shall use a dedicated register, \code{r15}, to store the pointer to
  4426. the top of the root stack. So \code{r15} is not available for use by
  4427. the register allocator.
  4428. \begin{lstlisting}
  4429. (collect |$\itm{bytes}$|)
  4430. |$\Longrightarrow$|
  4431. (movq (reg r15) (reg rdi))
  4432. (movq |\itm{bytes}| (reg rsi))
  4433. (callq collect)
  4434. \end{lstlisting}
  4435. \begin{figure}[tp]
  4436. \fbox{
  4437. \begin{minipage}{0.96\textwidth}
  4438. \[
  4439. \begin{array}{lcl}
  4440. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4441. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4442. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4443. \mid (\key{global-value}\; \itm{name}) \\
  4444. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4445. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4446. (\key{subq} \; \Arg\; \Arg) \mid
  4447. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4448. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4449. (\key{pushq}\;\Arg) \mid
  4450. (\key{popq}\;\Arg) \mid
  4451. (\key{retq})} \\
  4452. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4453. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4454. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4455. \mid (\key{jmp} \; \itm{label})
  4456. \mid (\key{jmp-if}\itm{cc} \; \itm{label})
  4457. \mid (\key{label} \; \itm{label}) } \\
  4458. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4459. \end{array}
  4460. \]
  4461. \end{minipage}
  4462. }
  4463. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4464. \label{fig:x86-2}
  4465. \end{figure}
  4466. The syntax of the $x86_2$ language is defined in
  4467. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4468. of the form for global variables.
  4469. %
  4470. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4471. \code{select-instructions} pass on the running example.
  4472. \begin{figure}[tbp]
  4473. \centering
  4474. \begin{minipage}{0.75\textwidth}
  4475. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4476. (program
  4477. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4478. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void) (tmp94 . Integer)
  4479. (tmp93 . Integer) (tmp95 . Integer) (tmp85 Vector Integer)
  4480. (tmp87 . Void) (tmp92 . Void) (tmp00 . Void) (tmp98 . Integer)
  4481. (tmp97 . Integer) (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4482. (tmp91 . Void)) (type Integer)
  4483. (movq (int 42) (var tmp86))
  4484. (movq (global-value free_ptr) (var tmp93))
  4485. (movq (var tmp93) (var tmp94))
  4486. (addq (int 16) (var tmp94))
  4487. (movq (global-value fromspace_end) (var tmp95))
  4488. (if (< (var tmp94) (var tmp95))
  4489. ((movq (int 0) (var tmp96)))
  4490. ((movq (reg r15) (reg rdi))
  4491. (movq (int 16) (reg rsi))
  4492. (callq collect)
  4493. (movq (int 0) (var tmp96))))
  4494. (movq (var tmp96) (var tmp88))
  4495. (movq (global-value free_ptr) (var tmp85))
  4496. (addq (int 16) (global-value free_ptr))
  4497. (movq (var tmp85) (reg r11))
  4498. (movq (int 3) (deref r11 0))
  4499. (movq (var tmp85) (reg r11))
  4500. (movq (var tmp86) (deref r11 8))
  4501. (movq (int 0) (var tmp87))
  4502. (movq (var tmp85) (var tmp90))
  4503. (movq (global-value free_ptr) (var tmp97))
  4504. (movq (var tmp97) (var tmp98))
  4505. (addq (int 16) (var tmp98))
  4506. (movq (global-value fromspace_end) (var tmp99))
  4507. (if (< (var tmp98) (var tmp99))
  4508. ((movq (int 0) (var tmp00)))
  4509. ((movq (reg r15) (reg rdi))
  4510. (movq (int 16) (reg rsi))
  4511. (callq collect)
  4512. (movq (int 0) (var tmp00))))
  4513. (movq (var tmp00) (var tmp92))
  4514. (movq (global-value free_ptr) (var tmp89))
  4515. (addq (int 16) (global-value free_ptr))
  4516. (movq (var tmp89) (reg r11))
  4517. (movq (int 131) (deref r11 0))
  4518. (movq (var tmp89) (reg r11))
  4519. (movq (var tmp90) (deref r11 8))
  4520. (movq (int 0) (var tmp91))
  4521. (movq (var tmp89) (reg r11))
  4522. (movq (deref r11 8) (var tmp01))
  4523. (movq (var tmp01) (reg r11))
  4524. (movq (deref r11 8) (var tmp02))
  4525. (movq (var tmp02) (reg rax)))
  4526. \end{lstlisting}
  4527. \end{minipage}
  4528. \caption{Output of the \code{select-instructions} pass.}
  4529. \label{fig:select-instr-output-gc}
  4530. \end{figure}
  4531. \clearpage
  4532. \subsection{Register Allocation}
  4533. \label{sec:reg-alloc-gc}
  4534. As discussed earlier in this chapter, the garbage collector needs to
  4535. access all the pointers in the root set, that is, all variables that
  4536. are vectors. It will be the responsibility of the register allocator
  4537. to make sure that:
  4538. \begin{enumerate}
  4539. \item the root stack is used for spilling vector-typed variables, and
  4540. \item if a vector-typed variable is live during a call to the
  4541. collector, it must be spilled to ensure it is visible to the
  4542. collector.
  4543. \end{enumerate}
  4544. The later responsibility can be handled during construction of the
  4545. inference graph, by adding interference edges between the call-live
  4546. vector-typed variables and all the callee-saved registers. (They
  4547. already interfere with the caller-saved registers.) The type
  4548. information for variables is in the \code{program} form, so we
  4549. recommend adding another parameter to the \code{build-interference}
  4550. function to communicate this association list.
  4551. The spilling of vector-typed variables to the root stack can be
  4552. handled after graph coloring, when choosing how to assign the colors
  4553. (integers) to registers and stack locations. The \code{program} output
  4554. of this pass changes to also record the number of spills to the root
  4555. stack.
  4556. \[
  4557. \begin{array}{lcl}
  4558. x86_2 &::= & (\key{program} \;(\itm{stackSpills} \; \itm{rootstackSpills}) \;(\key{type}\;\itm{type})\; \Instr^{+})
  4559. \end{array}
  4560. \]
  4561. % build-interference
  4562. %
  4563. % callq
  4564. % extra parameter for var->type assoc. list
  4565. % update 'program' and 'if'
  4566. % allocate-registers
  4567. % allocate spilled vectors to the rootstack
  4568. % don't change color-graph
  4569. \subsection{Print x86}
  4570. \label{sec:print-x86-gc}
  4571. \margincomment{\scriptsize We need to show the translation to x86 and what
  4572. to do about global-value. \\ --Jeremy}
  4573. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4574. \code{print-x86} pass on the running example. In the prelude and
  4575. conclusion of the \code{main} function, we treat the root stack very
  4576. much like the regular stack in that we move the root stack pointer
  4577. (\code{r15}) to make room for all of the spills to the root stack,
  4578. except that the root stack grows up instead of down. For the running
  4579. example, there was just one spill so we increment \code{r15} by 8
  4580. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4581. One issue that deserves special care is that there may be a call to
  4582. \code{collect} prior to the initializing assignments for all the
  4583. variables in the root stack. We do not want the garbage collector to
  4584. accidentaly think that some uninitialized variable is a pointer that
  4585. needs to be followed. Thus, we zero-out all locations on the root
  4586. stack in the prelude of \code{main}. In
  4587. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4588. %
  4589. \lstinline{movq $0, (%r15)}
  4590. %
  4591. accomplishes this task. The garbage collector tests each root to see
  4592. if it is null prior to dereferencing it.
  4593. \begin{figure}[htbp]
  4594. \begin{minipage}[t]{0.5\textwidth}
  4595. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4596. .globl _main
  4597. _main:
  4598. pushq %rbp
  4599. movq %rsp, %rbp
  4600. pushq %r14
  4601. pushq %r13
  4602. pushq %r12
  4603. pushq %rbx
  4604. subq $0, %rsp
  4605. movq $16384, %rdi
  4606. movq $16, %rsi
  4607. callq _initialize
  4608. movq _rootstack_begin(%rip), %r15
  4609. movq $0, (%r15)
  4610. addq $8, %r15
  4611. movq $42, %rbx
  4612. movq _free_ptr(%rip), %rcx
  4613. addq $16, %rcx
  4614. movq _fromspace_end(%rip), %rdx
  4615. cmpq %rdx, %rcx
  4616. jl then33131
  4617. movq %r15, %rdi
  4618. movq $16, %rsi
  4619. callq _collect
  4620. movq $0, %rcx
  4621. jmp if_end33132
  4622. then33131:
  4623. movq $0, %rcx
  4624. if_end33132:
  4625. movq _free_ptr(%rip), %rcx
  4626. addq $16, _free_ptr(%rip)
  4627. movq %rcx, %r11
  4628. movq $3, 0(%r11)
  4629. movq %rcx, %r11
  4630. movq %rbx, 8(%r11)
  4631. movq $0, %rbx
  4632. movq %rcx, -8(%r15)
  4633. movq _free_ptr(%rip), %rbx
  4634. movq %rbx, %rcx
  4635. addq $16, %rcx
  4636. movq _fromspace_end(%rip), %rbx
  4637. cmpq %rbx, %rcx
  4638. jl then33133
  4639. movq %r15, %rdi
  4640. movq $16, %rsi
  4641. callq _collect
  4642. movq $0, %rbx
  4643. jmp if_end33134
  4644. \end{lstlisting}
  4645. \end{minipage}
  4646. \begin{minipage}[t]{0.45\textwidth}
  4647. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4648. then33133:
  4649. movq $0, %rbx
  4650. if_end33134:
  4651. movq _free_ptr(%rip), %rbx
  4652. addq $16, _free_ptr(%rip)
  4653. movq %rbx, %r11
  4654. movq $131, 0(%r11)
  4655. movq %rbx, %r11
  4656. movq -8(%r15), %rax
  4657. movq %rax, 8(%r11)
  4658. movq $0, %rcx
  4659. movq %rbx, %r11
  4660. movq 8(%r11), %rbx
  4661. movq %rbx, %r11
  4662. movq 8(%r11), %rbx
  4663. movq %rbx, %rax
  4664. movq %rax, %rdi
  4665. callq _print_int
  4666. movq $0, %rax
  4667. subq $8, %r15
  4668. addq $0, %rsp
  4669. popq %rbx
  4670. popq %r12
  4671. popq %r13
  4672. popq %r14
  4673. popq %rbp
  4674. retq
  4675. \end{lstlisting}
  4676. \end{minipage}
  4677. \caption{Output of the \code{print-x86} pass.}
  4678. \label{fig:print-x86-output-gc}
  4679. \end{figure}
  4680. \margincomment{\scriptsize Suggest an implementation strategy
  4681. in which the students first do the code gen and test that
  4682. without GC (just use a big heap), then after that is debugged,
  4683. implement the GC. \\ --Jeremy}
  4684. \begin{figure}[p]
  4685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4686. \node (R3) at (0,2) {\large $R_3$};
  4687. \node (R3-2) at (3,2) {\large $R_3$};
  4688. \node (R3-3) at (6,2) {\large $R_3$};
  4689. \node (R3-4) at (9,2) {\large $R_3$};
  4690. \node (C2-3) at (3,0) {\large $C_2$};
  4691. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  4692. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  4693. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  4694. \node (x86-5) at (12,-2) {\large $\text{x86}_2$};
  4695. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}_2$};
  4696. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  4697. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  4698. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  4699. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  4700. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  4701. \path[->,bend left=20] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C2-3);
  4702. \path[->,bend right=15] (C2-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4703. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4704. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  4705. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  4706. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  4707. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  4708. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-6);
  4709. \end{tikzpicture}
  4710. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4711. \label{fig:R3-passes}
  4712. \end{figure}
  4713. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4714. for the compilation of $R_3$.
  4715. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4716. \chapter{Functions}
  4717. \label{ch:functions}
  4718. This chapter studies the compilation of functions (aka. procedures) at
  4719. the level of abstraction of the C language. This corresponds to a
  4720. subset of Typed Racket in which only top-level function definitions
  4721. are allowed. This abstraction level is an important stepping stone to
  4722. implementing lexically-scoped functions in the form of \key{lambda}
  4723. abstractions (Chapter~\ref{ch:lambdas}).
  4724. \section{The $R_4$ Language}
  4725. The syntax for function definitions and function application
  4726. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4727. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4728. function definitions. The function names from these definitions are
  4729. in-scope for the entire program, including all other function
  4730. definitions (so the ordering of function definitions does not matter).
  4731. Functions are first-class in the sense that a function pointer is data
  4732. and can be stored in memory or passed as a parameter to another
  4733. function. Thus, we introduce a function type, written
  4734. \begin{lstlisting}
  4735. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4736. \end{lstlisting}
  4737. for a function whose $n$ parameters have the types $\Type_1$ through
  4738. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4739. these functions (with respect to Racket functions) is that they are
  4740. not lexically scoped. That is, the only external entities that can be
  4741. referenced from inside a function body are other globally-defined
  4742. functions. The syntax of $R_4$ prevents functions from being nested
  4743. inside each other; they can only be defined at the top level.
  4744. \begin{figure}[tp]
  4745. \centering
  4746. \fbox{
  4747. \begin{minipage}{0.96\textwidth}
  4748. \[
  4749. \begin{array}{lcl}
  4750. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4751. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4752. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4753. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4754. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4755. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4756. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4757. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4758. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4759. (\key{vector-ref}\;\Exp\;\Int)} \\
  4760. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4761. &\mid& (\Exp \; \Exp^{*}) \\
  4762. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4763. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4764. \end{array}
  4765. \]
  4766. \end{minipage}
  4767. }
  4768. \caption{Syntax of $R_4$, extending $R_3$ with functions.}
  4769. \label{fig:r4-syntax}
  4770. \end{figure}
  4771. The program in Figure~\ref{fig:r4-function-example} is a
  4772. representative example of defining and using functions in $R_4$. We
  4773. define a function \code{map-vec} that applies some other function
  4774. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4775. vector containing the results. We also define a function \code{add1}
  4776. that does what its name suggests. The program then applies
  4777. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4778. \code{(vector 1 42)}, from which we return the \code{42}.
  4779. \begin{figure}[tbp]
  4780. \begin{lstlisting}
  4781. (program
  4782. (define (map-vec [f : (Integer -> Integer)]
  4783. [v : (Vector Integer Integer)])
  4784. : (Vector Integer Integer)
  4785. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4786. (define (add1 [x : Integer]) : Integer
  4787. (+ x 1))
  4788. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4789. )
  4790. \end{lstlisting}
  4791. \caption{Example of using functions in $R_4$.}
  4792. \label{fig:r4-function-example}
  4793. \end{figure}
  4794. The definitional interpreter for $R_4$ is in
  4795. Figure~\ref{fig:interp-R4}.
  4796. \begin{figure}[tp]
  4797. \begin{lstlisting}
  4798. (define (interp-exp env)
  4799. (lambda (e)
  4800. (define recur (interp-exp env))
  4801. (match e
  4802. ...
  4803. [`(,fun ,args ...)
  4804. (define arg-vals (map recur args))
  4805. (define fun-val (recur fun))
  4806. (match fun-val
  4807. [`(lambda (,xs ...) ,body ,fun-env)
  4808. (define new-env (append (map cons xs arg-vals) fun-env))
  4809. ((interp-exp new-env) body)]
  4810. [else (error "interp-exp, expected function, not" fun-val)])]
  4811. [else (error 'interp-exp "unrecognized expression")]
  4812. )))
  4813. (define (interp-def d)
  4814. (match d
  4815. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4816. (mcons f `(lambda ,xs ,body ()))]
  4817. ))
  4818. (define (interp-R4 p)
  4819. (match p
  4820. [`(program ,ds ... ,body)
  4821. (let ([top-level (map interp-def ds)])
  4822. (for/list ([b top-level])
  4823. (set-mcdr! b
  4824. (match (mcdr b)
  4825. [`(lambda ,xs ,body ())
  4826. `(lambda ,xs ,body ,top-level)])))
  4827. ((interp-exp top-level) body))]
  4828. ))
  4829. \end{lstlisting}
  4830. \caption{Interpreter for the $R_4$ language.}
  4831. \label{fig:interp-R4}
  4832. \end{figure}
  4833. \section{Functions in x86}
  4834. \label{sec:fun-x86}
  4835. \margincomment{\tiny Make sure callee-saved registers are discussed
  4836. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  4837. \margincomment{\tiny Talk about the return address on the
  4838. stack and what callq and retq does.\\ --Jeremy }
  4839. The x86 architecture provides a few features to support the
  4840. implementation of functions. We have already seen that x86 provides
  4841. labels so that one can refer to the location of an instruction, as is
  4842. needed for jump instructions. Labels can also be used to mark the
  4843. beginning of the instructions for a function. Going further, we can
  4844. obtain the address of a label by using the \key{leaq} instruction and
  4845. \key{rip}-relative addressing. For example, the following puts the
  4846. address of the \code{add1} label into the \code{rbx} register.
  4847. \begin{lstlisting}
  4848. leaq add1(%rip), %rbx
  4849. \end{lstlisting}
  4850. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4851. the \code{callq} instruction for jumping to a function as specified by
  4852. a label. The use of the instruction changes slightly if the function
  4853. is specified by an address in a register, that is, an \emph{indirect
  4854. function call}. The x86 syntax is to give the register name prefixed
  4855. with an asterisk.
  4856. \begin{lstlisting}
  4857. callq *%rbx
  4858. \end{lstlisting}
  4859. Because the x86 architecture does not have any direct support for
  4860. passing arguments to functions, compiler implementers typically adopt
  4861. a \emph{convention} to follow for how arguments are passed to
  4862. functions. The convention for C compilers such as \code{gcc} (as
  4863. described in \cite{Matz:2013aa}), uses a combination of registers and
  4864. stack locations for passing arguments. Up to six arguments may be
  4865. passed in registers, using the registers \code{rdi}, \code{rsi},
  4866. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4867. there are more than six arguments, then the rest are placed on the
  4868. stack. The register \code{rax} is for the return value of the
  4869. function.
  4870. We will be using a modification of this convention. For reasons that
  4871. will be explained in subsequent paragraphs, we will not make use of
  4872. the stack for passing arguments, and instead use the heap when there
  4873. are more than six arguments. In particular, functions of more than six
  4874. arguments will be transformed to pass the additional arguments in a
  4875. vector.
  4876. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  4877. %% local variables and for storing the values of callee-saved registers
  4878. %% (we shall refer to all of these collectively as ``locals''), and that
  4879. %% at the beginning of a function we move the stack pointer \code{rsp}
  4880. %% down to make room for them.
  4881. %% We recommend storing the local variables
  4882. %% first and then the callee-saved registers, so that the local variables
  4883. %% can be accessed using \code{rbp} the same as before the addition of
  4884. %% functions.
  4885. %% To make additional room for passing arguments, we shall
  4886. %% move the stack pointer even further down. We count how many stack
  4887. %% arguments are needed for each function call that occurs inside the
  4888. %% body of the function and find their maximum. Adding this number to the
  4889. %% number of locals gives us how much the \code{rsp} should be moved at
  4890. %% the beginning of the function. In preparation for a function call, we
  4891. %% offset from \code{rsp} to set up the stack arguments. We put the first
  4892. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4893. %% so on.
  4894. %% Upon calling the function, the stack arguments are retrieved by the
  4895. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4896. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  4897. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4898. %% the layout of the caller and callee frames. Notice how important it is
  4899. %% that we correctly compute the maximum number of arguments needed for
  4900. %% function calls; if that number is too small then the arguments and
  4901. %% local variables will smash into each other!
  4902. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4903. is responsible for following conventions regarding the use of
  4904. registers: the caller should assume that all the caller-saved
  4905. registers get overwritten with arbitrary values by the callee. Thus,
  4906. the caller should either 1) not put values that are live across a call
  4907. in caller-saved registers, or 2) save and restore values that are live
  4908. across calls. We shall recommend option 1). On the flip side, if the
  4909. callee wants to use a callee-saved register, the callee must arrange
  4910. to put the original value back in the register prior to returning to
  4911. the caller.
  4912. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  4913. frames. If we were to use stack arguments, they would be between the
  4914. caller locals and the callee return address. A function call will
  4915. place a new frame onto the stack, growing downward. There are cases,
  4916. however, where we can \emph{replace} the current frame on the stack in
  4917. a function call, rather than add a new frame.
  4918. If a call is the last action in a function body, then that call is
  4919. said to be a \emph{tail call}. In the case of a tail call, whatever
  4920. the callee returns will be immediately returned by the caller, so the
  4921. call can be optimized into a \code{jmp} instruction---the caller will
  4922. jump to the new function, maintaining the same frame and return
  4923. address. Like the indirect function call, we write an indirect
  4924. jump with a register prefixed with an asterisk.
  4925. \begin{lstlisting}
  4926. jmp *%rax
  4927. \end{lstlisting}
  4928. A common use case for this optimization is \emph{tail recursion}: a
  4929. function that calls itself in the tail position is essentially a loop,
  4930. and if it does not grow the stack on each call it can act like
  4931. one. Functional languages like Racket and Scheme typically rely
  4932. heavily on function calls, and so they typically guarantee that
  4933. \emph{all} tail calls will be optimized in this way, not just
  4934. functions that call themselves.
  4935. \margincomment{\scriptsize To do: better motivate guaranteed tail calls? -mv}
  4936. If we were to stick to the calling convention used by C compilers like
  4937. \code{gcc}, it would be awkward to optimize tail calls that require
  4938. stack arguments, so we simplify the process by imposing an invariant
  4939. that no function passes arguments that way. With this invariant,
  4940. space-efficient tail calls are straightforward to implement.
  4941. \begin{figure}[tbp]
  4942. \centering
  4943. \begin{tabular}{r|r|l|l} \hline
  4944. Caller View & Callee View & Contents & Frame \\ \hline
  4945. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4946. 0(\key{\%rbp}) & & old \key{rbp} \\
  4947. -8(\key{\%rbp}) & & local $1$ \\
  4948. \ldots & & \ldots \\
  4949. $-8k$(\key{\%rbp}) & & local $k$ \\
  4950. %% & & \\
  4951. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4952. %% & \ldots & \ldots \\
  4953. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  4954. \hline
  4955. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4956. & 0(\key{\%rbp}) & old \key{rbp} \\
  4957. & -8(\key{\%rbp}) & local $1$ \\
  4958. & \ldots & \ldots \\
  4959. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4960. \end{tabular}
  4961. \caption{Memory layout of caller and callee frames.}
  4962. \label{fig:call-frames}
  4963. \end{figure}
  4964. \section{The compilation of functions}
  4965. \margincomment{\scriptsize To do: discuss the need to push and
  4966. pop call-live pointers (vectors and functions)
  4967. to the root stack \\ --Jeremy}
  4968. Now that we have a good understanding of functions as they appear in
  4969. $R_4$ and the support for functions in x86, we need to plan the
  4970. changes to our compiler, that is, do we need any new passes and/or do
  4971. we need to change any existing passes? Also, do we need to add new
  4972. kinds of AST nodes to any of the intermediate languages?
  4973. First, we need to transform functions to operate on at most five
  4974. arguments. There are a total of six registers for passing arguments
  4975. used in the convention previously mentioned, and we will reserve one
  4976. for future use with higher-order functions (as explained in
  4977. Chapter~\ref{ch:lambdas}). A simple strategy for imposing an argument
  4978. limit of length $n$ is to take all arguments $i$ where $i \geq n$ and
  4979. pack them into a vector, making that subsequent vector the $n$th
  4980. argument.
  4981. \begin{tabular}{lll}
  4982. \begin{minipage}{0.2\textwidth}
  4983. \begin{lstlisting}
  4984. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  4985. \end{lstlisting}
  4986. \end{minipage}
  4987. &
  4988. $\Rightarrow$
  4989. &
  4990. \begin{minipage}{0.4\textwidth}
  4991. \begin{lstlisting}
  4992. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  4993. \end{lstlisting}
  4994. \end{minipage}
  4995. \end{tabular}
  4996. Additionally, all occurrances of the $i$th argument (where $i>5$) in
  4997. the body must be replaced with a projection from the vector. A pass
  4998. that limits function arguments like this (which we will name
  4999. \code{limit-functions}), can operate directly on $R_4$.
  5000. \begin{figure}[tp]
  5001. \centering
  5002. \fbox{
  5003. \begin{minipage}{0.96\textwidth}
  5004. \[
  5005. \begin{array}{lcl}
  5006. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5007. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5008. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5009. &\mid& (\key{function-ref}\, \itm{label})
  5010. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5011. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5012. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5013. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5014. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5015. (\key{vector-ref}\;\Exp\;\Int)} \\
  5016. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5017. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \mid (\key{tailcall}\, \Exp \; \Exp^{*}) \\
  5018. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5019. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  5020. \end{array}
  5021. \]
  5022. \end{minipage}
  5023. }
  5024. \caption{The $F_1$ language, an extension of $R_3$
  5025. (Figure~\ref{fig:r3-syntax}).}
  5026. \label{fig:f1-syntax}
  5027. \end{figure}
  5028. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5029. compilation because it conflates the use of function names and local
  5030. variables and it conflates the application of primitive operations and
  5031. the application of functions. This is a problem because we need to
  5032. compile the use of a function name differently than the use of a local
  5033. variable; we need to use \code{leaq} to move the function name to a
  5034. register. Similarly, the application of a function is going to require
  5035. a complex sequence of instructions, unlike the primitive
  5036. operations. Thus, it is a good idea to create a new pass that changes
  5037. function references from just a symbol $f$ to \code{(function-ref
  5038. $f$)} and that changes function application from \code{($e_0$ $e_1$
  5039. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  5040. $\ldots$ $e_n$)} or \code{(tailcall $e_0$ $e_1$ $\ldots$ $e_n$)}. A
  5041. good name for this pass is \code{reveal-functions} and the output
  5042. language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  5043. Distinguishing between calls in tail position and non-tail position
  5044. requires the pass to have some notion of context. We recommend the
  5045. function take an additional boolean argument which represents whether
  5046. the expression it is considering is in tail position. For example,
  5047. when handling a conditional expression \code{(if $e_1$ $e_2$ $e_3$)}
  5048. in tail position, both $e_2$ and $e_3$ are also in tail position,
  5049. while $e_1$ is not.
  5050. Placing this pass after \code{uniquify} is a good idea, because it
  5051. will make sure that there are no local variables and functions that
  5052. share the same name. On the other hand, \code{reveal-functions} needs
  5053. to come before the \code{flatten} pass because \code{flatten} will
  5054. help us compile \code{function-ref}. Figure~\ref{fig:c3-syntax}
  5055. defines the syntax for $C_3$, the output of \key{flatten}.
  5056. \begin{figure}[tp]
  5057. \fbox{
  5058. \begin{minipage}{0.96\textwidth}
  5059. \[
  5060. \begin{array}{lcl}
  5061. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5062. \mid (\key{function-ref}\,\itm{label})\\
  5063. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5064. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5065. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5066. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  5067. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5068. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  5069. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  5070. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  5071. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  5072. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  5073. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  5074. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  5075. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  5076. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  5077. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5078. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  5079. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  5080. \end{array}
  5081. \]
  5082. \end{minipage}
  5083. }
  5084. \caption{The $C_3$ language, extending $C_2$ with functions.}
  5085. \label{fig:c3-syntax}
  5086. \end{figure}
  5087. Because each \code{function-ref} needs to eventually become an
  5088. \code{leaq} instruction, it first needs to become an assignment
  5089. statement so there is a left-hand side in which to put the
  5090. result. This can be handled easily in the \code{flatten} pass by
  5091. categorizing \code{function-ref} as a complex expression. Then, in
  5092. the \code{select-instructions} pass, an assignment of
  5093. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  5094. \begin{tabular}{lll}
  5095. \begin{minipage}{0.45\textwidth}
  5096. \begin{lstlisting}
  5097. (assign |$\itm{lhs}$| (function-ref |$f$|))
  5098. \end{lstlisting}
  5099. \end{minipage}
  5100. &
  5101. $\Rightarrow$
  5102. &
  5103. \begin{minipage}{0.4\textwidth}
  5104. \begin{lstlisting}
  5105. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  5106. \end{lstlisting}
  5107. \end{minipage}
  5108. \end{tabular} \\
  5109. %
  5110. Note that in the syntax for $C_3$, tail calls are statements, not
  5111. expressions. Once we perform a tail call, we do not ever expect it to
  5112. return a value to us, and \code{flatten} therefore should handle
  5113. \code{app} and \code{tailcall} forms differently.
  5114. The output of select instructions is a program in the x86$_3$
  5115. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5116. \begin{figure}[tp]
  5117. \fbox{
  5118. \begin{minipage}{0.96\textwidth}
  5119. \[
  5120. \begin{array}{lcl}
  5121. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5122. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5123. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5124. \mid (\key{global-value}\; \itm{name}) } \\
  5125. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5126. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5127. (\key{subq} \; \Arg\; \Arg) \mid
  5128. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5129. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5130. (\key{pushq}\;\Arg) \mid
  5131. (\key{popq}\;\Arg) \mid
  5132. (\key{retq}) } \\
  5133. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5134. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5135. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5136. \mid (\key{jmp} \; \itm{label})
  5137. \mid (\key{j}\itm{cc} \; \itm{label})
  5138. \mid (\key{label} \; \itm{label}) } \\
  5139. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{indirect-jmp}\;\Arg) \\
  5140. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5141. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Instr^{+})\\
  5142. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  5143. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  5144. \end{array}
  5145. \]
  5146. \end{minipage}
  5147. }
  5148. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5149. \label{fig:x86-3}
  5150. \end{figure}
  5151. Next we consider compiling function definitions. The \code{flatten}
  5152. pass should handle function definitions a lot like a \code{program}
  5153. node; after all, the \code{program} node represents the \code{main}
  5154. function. So the \code{flatten} pass, in addition to flattening the
  5155. body of the function into a sequence of statements, should record the
  5156. local variables in the $\Var^{*}$ field as shown below.
  5157. \begin{lstlisting}
  5158. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  5159. \end{lstlisting}
  5160. In the \code{select-instructions} pass, we need to encode the
  5161. parameter passing in terms of the conventions discussed in
  5162. Section~\ref{sec:fun-x86}: a \code{movq} instruction for each
  5163. parameter should be generated, to move the parameter value from the
  5164. appropriate register to the appropriate variable from \itm{xs}.
  5165. %% I recommend generating \code{movq} instructions to
  5166. %% move the parameters from their registers and stack locations into the
  5167. %% variables \itm{xs}, then let register allocation handle the assignment
  5168. %% of those variables to homes.
  5169. %% After this pass, the \itm{xs} can be
  5170. %% added to the list of local variables. As mentioned in
  5171. %% Section~\ref{sec:fun-x86}, we need to find out how far to move the
  5172. %% stack pointer to ensure we have enough space for stack arguments in
  5173. %% all the calls inside the body of this function. This pass is a good
  5174. %% place to do this and store the result in the \itm{maxStack} field of
  5175. %% the output \code{define} shown below.
  5176. %% \begin{lstlisting}
  5177. %% (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  5178. %% \end{lstlisting}
  5179. Next, consider the compilation of non-tail function applications, which have
  5180. the following form at the start of \code{select-instructions}.
  5181. \begin{lstlisting}
  5182. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  5183. \end{lstlisting}
  5184. In the mirror image of handling the parameters of function
  5185. definitions, the arguments \itm{args} need to be moved to the
  5186. argument passing registers, as discussed in
  5187. Section~\ref{sec:fun-x86}.
  5188. %% and the rest should be moved to the
  5189. %% appropriate stack locations,
  5190. %% You might want to introduce a new kind of AST node for stack
  5191. %% arguments, \code{(stack-arg $i$)} where $i$ is the index of this
  5192. %% argument with respect to the other stack arguments.
  5193. %% As you're generating the code for parameter passing, take note of how
  5194. %% many stack arguments are needed for purposes of computing the
  5195. %% \itm{maxStack} discussed above.
  5196. Once the instructions for parameter passing have been generated, the
  5197. function call itself can be performed with an indirect function call,
  5198. for which I recommend creating the new instruction
  5199. \code{indirect-callq}. Of course, the return value from the function
  5200. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5201. \begin{lstlisting}
  5202. (indirect-callq |\itm{fun}|)
  5203. (movq (reg rax) |\itm{lhs}|)
  5204. \end{lstlisting}
  5205. Handling function applications in tail positions is only slightly
  5206. different. The parameter passing is the same as non-tail calls,
  5207. but the tail call itself cannot use the \code{indirect-callq} form.
  5208. Generating, instead, an \code{indirect-jmp} form in \code{select-instructions}
  5209. accounts for the fact that we intend to eventually use a \code{jmp}
  5210. rather than a \code{callq} for the tail call. Of course, the
  5211. \code{movq} from \code{rax} is not necessary after a tail call.
  5212. The rest of the passes need only minor modifications to handle the new
  5213. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  5214. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  5215. (written variables) for an \code{indirect-callq} instruction, I
  5216. recommend including all the caller-saved registers, which will have
  5217. the affect of making sure that no caller-saved register actually needs
  5218. to be saved. In \code{patch-instructions}, you should deal with the
  5219. x86 idiosyncrasy that the destination argument of \code{leaq} must be
  5220. a register. Additionally, \code{patch-instructions} should ensure that
  5221. the \code{indirect-jmp} argument is \itm{rax}, our reserved
  5222. register---this is to make code generation more convenient, because
  5223. we will be trampling many registers before the tail call (as explained
  5224. below).
  5225. For the \code{print-x86} pass, we recommend the following translations:
  5226. \begin{lstlisting}
  5227. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5228. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5229. \end{lstlisting}
  5230. Handling \code{indirect-jmp} requires a bit more care. A
  5231. straightforward translation of \code{indirect-jmp} would be \code{jmp
  5232. *$\itm{arg}$}, which is what we will want to do, but \emph{before}
  5233. this jump we need to pop the saved registers and reset the frame
  5234. pointer. Basically, we want to restore the state of the registers to
  5235. the point they were at when the current function was called, since we
  5236. are about to jump to the beginning of a \emph{new} function.
  5237. This is why it was convenient to ensure the \code{jmp} argument was
  5238. \itm{rax}. A sufficiently clever compiler could determine that a
  5239. function body always ends in a tail call, and thus avoid generating
  5240. code to restore registers and return via \code{ret}, but for
  5241. simplicity we do not need to do this.
  5242. \margincomment{\footnotesize The reason we can't easily optimize
  5243. this is because the details of function prologue and epilogue
  5244. are not exposed in the AST, and just emitted as strings in
  5245. \code{print-x86}.}
  5246. As this implies, your \code{print-x86} pass needs to add
  5247. the code for saving and restoring callee-saved registers, if
  5248. you have not already implemented that. This is necessary when
  5249. generating code for function definitions.
  5250. %% For function definitions, the \code{print-x86} pass should add the
  5251. %% code for saving and restoring the callee-saved registers, if you
  5252. %% haven't already done that.
  5253. \section{An Example Translation}
  5254. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5255. function in $R_4$ to x86. The figure includes the results of the
  5256. \code{flatten} and \code{select-instructions} passes. Can you see any
  5257. ways to improve the translation?
  5258. \begin{figure}[tbp]
  5259. \begin{tabular}{lll}
  5260. \begin{minipage}{0.5\textwidth}
  5261. \begin{lstlisting}
  5262. (program
  5263. (define (add [x : Integer]
  5264. [y : Integer])
  5265. : Integer (+ x y))
  5266. (add 40 2))
  5267. \end{lstlisting}
  5268. $\Downarrow$
  5269. \begin{lstlisting}
  5270. (program (t.1 t.2)
  5271. (defines
  5272. (define (add.1 [x.1 : Integer]
  5273. [y.1 : Integer])
  5274. : Integer (t.3)
  5275. (assign t.3 (+ x.1 y.1))
  5276. (return t.3)))
  5277. (assign t.1 (function-ref add.1))
  5278. (assign t.2 (app t.1 40 2))
  5279. (return t.2))
  5280. \end{lstlisting}
  5281. $\Downarrow$
  5282. \begin{lstlisting}
  5283. (program ((rs.1 t.1 t.2) 0)
  5284. (type Integer)
  5285. (defines
  5286. (define (add28545) 3
  5287. ((rs.2 x.2 y.3 t.4) 0)
  5288. (movq (reg rdi) (var rs.2))
  5289. (movq (reg rsi) (var x.2))
  5290. (movq (reg rdx) (var y.3))
  5291. (movq (var x.2) (var t.4))
  5292. (addq (var y.3) (var t.4))
  5293. (movq (var t.4) (reg rax))))
  5294. (movq (int 16384) (reg rdi))
  5295. (movq (int 16) (reg rsi))
  5296. (callq initialize)
  5297. (movq (global-value rootstack_begin)
  5298. (var rs.1))
  5299. (leaq (function-ref add28545) (var t.1))
  5300. (movq (var rs.1) (reg rdi))
  5301. (movq (int 40) (reg rsi))
  5302. (movq (int 2) (reg rdx))
  5303. (indirect-callq (var t.1))
  5304. (movq (reg rax) (var t.2))
  5305. (movq (var t.2) (reg rax)))
  5306. \end{lstlisting}
  5307. \end{minipage}
  5308. &
  5309. \begin{minipage}{0.4\textwidth}
  5310. $\Downarrow$
  5311. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5312. .globl add28545
  5313. add28545:
  5314. pushq %rbp
  5315. movq %rsp, %rbp
  5316. pushq %r15
  5317. pushq %r14
  5318. pushq %r13
  5319. pushq %r12
  5320. pushq %rbx
  5321. subq $8, %rsp
  5322. movq %rdi, %rbx
  5323. movq %rsi, %rbx
  5324. movq %rdx, %rcx
  5325. addq %rcx, %rbx
  5326. movq %rbx, %rax
  5327. addq $8, %rsp
  5328. popq %rbx
  5329. popq %r12
  5330. popq %r13
  5331. popq %r14
  5332. popq %r15
  5333. popq %rbp
  5334. retq
  5335. .globl _main
  5336. _main:
  5337. pushq %rbp
  5338. movq %rsp, %rbp
  5339. pushq %r15
  5340. pushq %r14
  5341. pushq %r13
  5342. pushq %r12
  5343. pushq %rbx
  5344. subq $8, %rsp
  5345. movq $16384, %rdi
  5346. movq $16, %rsi
  5347. callq _initialize
  5348. movq _rootstack_begin(%rip), %rcx
  5349. leaq add28545(%rip), %rbx
  5350. movq %rcx, %rdi
  5351. movq $40, %rsi
  5352. movq $2, %rdx
  5353. callq *%rbx
  5354. movq %rax, %rbx
  5355. movq %rbx, %rax
  5356. movq %rax, %rdi
  5357. callq _print_int
  5358. movq $0, %rax
  5359. addq $8, %rsp
  5360. popq %rbx
  5361. popq %r12
  5362. popq %r13
  5363. popq %r14
  5364. popq %r15
  5365. popq %rbp
  5366. retq
  5367. \end{lstlisting}
  5368. \end{minipage}
  5369. \end{tabular}
  5370. \caption{Example compilation of a simple function to x86.}
  5371. \label{fig:add-fun}
  5372. \end{figure}
  5373. \begin{exercise}\normalfont
  5374. Expand your compiler to handle $R_4$ as outlined in this section.
  5375. Create 5 new programs that use functions, including examples that pass
  5376. functions and return functions from other functions, and test your
  5377. compiler on these new programs and all of your previously created test
  5378. programs.
  5379. \end{exercise}
  5380. \begin{figure}[p]
  5381. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5382. \node (R4) at (0,2) {\large $R_4$};
  5383. \node (R4-2) at (3,2) {\large $R_4$};
  5384. \node (R4-3) at (6,2) {\large $R_4$};
  5385. \node (F1-1) at (6,0) {\large $F_1$};
  5386. \node (F1-2) at (3,0) {\large $F_1$};
  5387. \node (C3-3) at (3,-2) {\large $C_3$};
  5388. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5389. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5390. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5391. \node (x86-5) at (12,-4) {\large $\text{x86}_3$};
  5392. \node (x86-6) at (12,-6) {\large $\text{x86}^{\dagger}_3$};
  5393. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5394. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5395. \path[->,bend left=15] (R4) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5396. \path[->,bend left=15] (R4-2) edge [above] node {\ttfamily\footnotesize uniquify} (R4-3);
  5397. \path[->,bend left=15] (R4-3) edge [right] node {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5398. \path[->,bend left=15] (F1-1) edge [below] node {\ttfamily\footnotesize expose-alloc.} (F1-2);
  5399. \path[->,bend left=15] (F1-2) edge [left] node {\ttfamily\footnotesize flatten} (C3-3);
  5400. \path[->,bend right=15] (C3-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5401. \path[->,bend left=15] (x86-2) edge [left] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5402. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5403. \path[->,bend right=15] (x86-2-2) edge [left] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5404. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  5405. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  5406. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-6);
  5407. \end{tikzpicture}
  5408. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5409. \label{fig:R4-passes}
  5410. \end{figure}
  5411. Figure~\ref{fig:R4-passes} gives an overview of all the passes needed
  5412. for the compilation of $R_4$.
  5413. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5414. \chapter{Lexically Scoped Functions}
  5415. \label{ch:lambdas}
  5416. This chapter studies lexically scoped functions as they appear in
  5417. functional languages such as Racket. By lexical scoping we mean that a
  5418. function's body may refer to variables whose binding site is outside
  5419. of the function, in an enclosing scope.
  5420. %
  5421. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5422. anonymous function defined using the \key{lambda} form. The body of
  5423. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5424. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5425. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5426. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5427. returned from the function \code{f}. Below the definition of \code{f},
  5428. we have two calls to \code{f} with different arguments for \code{x},
  5429. first \code{5} then \code{3}. The functions returned from \code{f} are
  5430. bound to variables \code{g} and \code{h}. Even though these two
  5431. functions were created by the same \code{lambda}, they are really
  5432. different functions because they use different values for
  5433. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5434. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5435. the result of this program is \code{42}.
  5436. \begin{figure}[btp]
  5437. \begin{lstlisting}
  5438. (define (f [x : Integer]) : (Integer -> Integer)
  5439. (let ([y 4])
  5440. (lambda: ([z : Integer]) : Integer
  5441. (+ x (+ y z)))))
  5442. (let ([g (f 5)])
  5443. (let ([h (f 3)])
  5444. (+ (g 11) (h 15))))
  5445. \end{lstlisting}
  5446. \caption{Example of a lexically scoped function.}
  5447. \label{fig:lexical-scoping}
  5448. \end{figure}
  5449. \section{The $R_5$ Language}
  5450. The syntax for this language with anonymous functions and lexical
  5451. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5452. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5453. for function application. In this chapter we shall descibe how to
  5454. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5455. into a combination of functions (as in $R_4$) and tuples (as in
  5456. $R_3$).
  5457. \begin{figure}[tp]
  5458. \centering
  5459. \fbox{
  5460. \begin{minipage}{0.96\textwidth}
  5461. \[
  5462. \begin{array}{lcl}
  5463. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5464. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5465. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5466. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5467. \mid (\key{+} \; \Exp\;\Exp)} \\
  5468. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  5469. \mid \key{\#t} \mid \key{\#f} \mid
  5470. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5471. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5472. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5473. (\key{vector-ref}\;\Exp\;\Int)} \\
  5474. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5475. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5476. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5477. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5478. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5479. \end{array}
  5480. \]
  5481. \end{minipage}
  5482. }
  5483. \caption{Syntax of $R_5$, extending $R_4$ with \key{lambda}.}
  5484. \label{fig:r5-syntax}
  5485. \end{figure}
  5486. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  5487. functions with top-level function definitions. However, our compiler
  5488. must provide special treatment to variable occurences such as \code{x}
  5489. and \code{y} in the body of the \code{lambda} of
  5490. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  5491. refer to variables defined outside the function. To identify such
  5492. variable occurences, we review the standard notion of free variable.
  5493. \begin{definition}
  5494. A variable is \emph{free with respect to an expression} $e$ if the
  5495. variable occurs inside $e$ but does not have an enclosing binding in
  5496. $e$.
  5497. \end{definition}
  5498. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5499. free with respect to the expression \code{(+ x (+ y z))}. On the
  5500. other hand, only \code{x} and \code{y} are free with respect to the
  5501. following expression becuase \code{z} is bound by the \code{lambda}.
  5502. \begin{lstlisting}
  5503. (lambda: ([z : Integer]) : Integer
  5504. (+ x (+ y z)))
  5505. \end{lstlisting}
  5506. Once we have identified the free variables of a \code{lambda}, we need
  5507. to arrange for some way to transport, at runtime, the values of those
  5508. variables from the point where the \code{lambda} was created to the
  5509. point where the \code{lambda} is applied. Referring again to
  5510. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5511. needs to be used in the application of \code{g} to \code{11}, but the
  5512. binding of \code{x} to \code{3} needs to be used in the application of
  5513. \code{h} to \code{15}. The solution is to bundle the values of the
  5514. free variables together with the function pointer for the lambda's
  5515. code into a data structure called a \emph{closure}. Fortunately, we
  5516. already have the appropriate ingredients to make closures,
  5517. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5518. gave us function pointers. The function pointer shall reside at index
  5519. $0$ and the values for free variables will fill in the rest of the
  5520. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5521. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5522. Because the two closures came from the same \key{lambda}, they share
  5523. the same code but differ in the values for free variable \code{x}.
  5524. \begin{figure}[tbp]
  5525. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5526. \caption{Example closure representation for the \key{lambda}'s
  5527. in Figure~\ref{fig:lexical-scoping}.}
  5528. \label{fig:closures}
  5529. \end{figure}
  5530. \section{Interpreting $R_5$}
  5531. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5532. $R_5$. There are several things to worth noting. First, and most
  5533. importantly, the match clause for \key{lambda} saves the current
  5534. environment inside the returned \key{lambda}. Then the clause for
  5535. \key{app} uses the environment from the \key{lambda}, the
  5536. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  5537. course, the \code{lam-env} environment is extending with the mapping
  5538. parameters to argument values. To enable mutual recursion and allow a
  5539. unified handling of functions created with \key{lambda} and with
  5540. \key{define}, the match clause for \key{program} includes a second
  5541. pass over the top-level functions to set their environments to be the
  5542. top-level environment.
  5543. \begin{figure}[tbp]
  5544. \begin{lstlisting}
  5545. (define (interp-exp env)
  5546. (lambda (e)
  5547. (define recur (interp-exp env))
  5548. (match e
  5549. ...
  5550. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5551. `(lambda ,xs ,body ,env)]
  5552. [else (error 'interp-exp "unrecognized expression")]
  5553. )))
  5554. (define (interp-def env)
  5555. (lambda (d)
  5556. (match d
  5557. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5558. (mcons f `(lambda ,xs ,body))]
  5559. )))
  5560. (define (interp-R5 env)
  5561. (lambda (p)
  5562. (match p
  5563. [`(program ,defs ... ,body)
  5564. (let ([top-level (map (interp-def '()) defs)])
  5565. (for/list ([b top-level])
  5566. (set-mcdr! b (match (mcdr b)
  5567. [`(lambda ,xs ,body)
  5568. `(lambda ,xs ,body ,top-level)])))
  5569. ((interp-exp top-level) body))]
  5570. )))
  5571. \end{lstlisting}
  5572. \caption{Interpreter for $R_5$.}
  5573. \label{fig:interp-R5}
  5574. \end{figure}
  5575. \section{Type Checking $R_5$}
  5576. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5577. \key{lambda} form. The body of the \key{lambda} is checked in an
  5578. environment that includes the current environment (because it is
  5579. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5580. require the body's type to match the declared return type.
  5581. \begin{figure}[tbp]
  5582. \begin{lstlisting}
  5583. (define (typecheck-R5 env)
  5584. (lambda (e)
  5585. (match e
  5586. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5587. (define new-env (append (map cons xs Ts) env))
  5588. (define bodyT ((typecheck-R5 new-env) body))
  5589. (cond [(equal? rT bodyT)
  5590. `(,@Ts -> ,rT)]
  5591. [else
  5592. (error "mismatch in return type" bodyT rT)])]
  5593. ...
  5594. )))
  5595. \end{lstlisting}
  5596. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5597. \label{fig:typecheck-R5}
  5598. \end{figure}
  5599. \section{Closure Conversion}
  5600. The compiling of lexically-scoped functions into C-style functions is
  5601. accomplished in the pass \code{convert-to-closures} that comes after
  5602. \code{reveal-functions} and before flatten. This pass needs to treat
  5603. regular function calls differently from applying primitive operators,
  5604. and \code{reveal-functions} differentiates those two cases for us.
  5605. As usual, we shall implement the pass as a recursive function over the
  5606. AST. All of the action is in the clauses for \key{lambda} and
  5607. \key{app} (function application). We transform a \key{lambda}
  5608. expression into an expression that creates a closure, that is, creates
  5609. a vector whose first element is a function pointer and the rest of the
  5610. elements are the free variables of the \key{lambda}. The \itm{name}
  5611. is a unique symbol generated to identify the function.
  5612. \begin{tabular}{lll}
  5613. \begin{minipage}{0.4\textwidth}
  5614. \begin{lstlisting}
  5615. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5616. \end{lstlisting}
  5617. \end{minipage}
  5618. &
  5619. $\Rightarrow$
  5620. &
  5621. \begin{minipage}{0.4\textwidth}
  5622. \begin{lstlisting}
  5623. (vector |\itm{name}| |\itm{fvs}| ...)
  5624. \end{lstlisting}
  5625. \end{minipage}
  5626. \end{tabular} \\
  5627. %
  5628. In addition to transforming each \key{lambda} into a \key{vector}, we
  5629. must create a top-level function definition for each \key{lambda}, as
  5630. shown below.
  5631. \begin{lstlisting}
  5632. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  5633. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5634. ...
  5635. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5636. |\itm{body'}|)...))
  5637. \end{lstlisting}
  5638. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  5639. the normal parameters of the \key{lambda}. The sequence of \key{let}
  5640. forms being the free variables to their values obtained from the
  5641. closure.
  5642. We transform function application into code that retreives the
  5643. function pointer from the closure and then calls the function, passing
  5644. in the closure as the first argument. We bind $e'$ to a temporary
  5645. variable to avoid code duplication.
  5646. \begin{tabular}{lll}
  5647. \begin{minipage}{0.3\textwidth}
  5648. \begin{lstlisting}
  5649. (app |$e$| |\itm{es}| ...)
  5650. \end{lstlisting}
  5651. \end{minipage}
  5652. &
  5653. $\Rightarrow$
  5654. &
  5655. \begin{minipage}{0.5\textwidth}
  5656. \begin{lstlisting}
  5657. (let ([|\itm{tmp}| |$e'$|])
  5658. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5659. \end{lstlisting}
  5660. \end{minipage}
  5661. \end{tabular} \\
  5662. There is also the question of what to do with top-level function
  5663. definitions. To maintain a uniform translation of function
  5664. application, we turn function references into closures.
  5665. \begin{tabular}{lll}
  5666. \begin{minipage}{0.3\textwidth}
  5667. \begin{lstlisting}
  5668. (function-ref |$f$|)
  5669. \end{lstlisting}
  5670. \end{minipage}
  5671. &
  5672. $\Rightarrow$
  5673. &
  5674. \begin{minipage}{0.5\textwidth}
  5675. \begin{lstlisting}
  5676. (vector (function-ref |$f$|))
  5677. \end{lstlisting}
  5678. \end{minipage}
  5679. \end{tabular} \\
  5680. %
  5681. The top-level function definitions need to be updated as well to take
  5682. an extra closure parameter.
  5683. \section{An Example Translation}
  5684. \label{sec:example-lambda}
  5685. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5686. conversion for the example program demonstrating lexical scoping that
  5687. we discussed at the beginning of this chapter.
  5688. \begin{figure}[h]
  5689. \begin{minipage}{0.8\textwidth}
  5690. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5691. (program
  5692. (define (f [x : Integer]) : (Integer -> Integer)
  5693. (let ([y 4])
  5694. (lambda: ([z : Integer]) : Integer
  5695. (+ x (+ y z)))))
  5696. (let ([g (f 5)])
  5697. (let ([h (f 3)])
  5698. (+ (g 11) (h 15)))))
  5699. \end{lstlisting}
  5700. $\Downarrow$
  5701. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5702. (program (type Integer)
  5703. (define (f (x : Integer)) : (Integer -> Integer)
  5704. (let ((y 4))
  5705. (lambda: ((z : Integer)) : Integer
  5706. (+ x (+ y z)))))
  5707. (let ((g (app (function-ref f) 5)))
  5708. (let ((h (app (function-ref f) 3)))
  5709. (+ (app g 11) (app h 15)))))
  5710. \end{lstlisting}
  5711. $\Downarrow$
  5712. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5713. (program (type Integer)
  5714. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5715. (let ((y 4))
  5716. (vector (function-ref lam.1) x y)))
  5717. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5718. (let ((x (vector-ref clos.2 1)))
  5719. (let ((y (vector-ref clos.2 2)))
  5720. (+ x (+ y z)))))
  5721. (let ((g (let ((t.1 (vector (function-ref f))))
  5722. (app (vector-ref t.1 0) t.1 5))))
  5723. (let ((h (let ((t.2 (vector (function-ref f))))
  5724. (app (vector-ref t.2 0) t.2 3))))
  5725. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5726. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5727. \end{lstlisting}
  5728. \end{minipage}
  5729. \caption{Example of closure conversion.}
  5730. \label{fig:lexical-functions-example}
  5731. \end{figure}
  5732. \begin{figure}[p]
  5733. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5734. \node (R5) at (0,2) {\large $R_5$};
  5735. \node (R5-2) at (3,2) {\large $R_5$};
  5736. \node (R5-3) at (6,2) {\large $R_5$};
  5737. \node (F2) at (6,0) {\large $F_2$};
  5738. \node (F1-1) at (3,0) {\large $F_1$};
  5739. \node (F1-2) at (0,0) {\large $F_1$};
  5740. \node (C2-3) at (3,-2) {\large $C_2$};
  5741. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5742. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5743. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5744. \node (x86-5) at (12,-4) {\large $\text{x86}_3$};
  5745. \node (x86-6) at (12,-6) {\large $\text{x86}^{\dagger}_3$};
  5746. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5747. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5748. \path[->,bend left=15] (R5) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R5-2);
  5749. \path[->,bend left=15] (R5-2) edge [above] node {\ttfamily\footnotesize uniquify} (R5-3);
  5750. \path[->,bend left=15] (R5-3) edge [right] node {\ttfamily\footnotesize reveal-functions} (F2);
  5751. \path[->,bend left=15] (F2) edge [below] node {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-1);
  5752. \path[->,bend right=15] (F1-1) edge [above] node {\ttfamily\footnotesize expose-alloc.} (F1-2);
  5753. \path[->,bend right=15] (F1-2) edge [left] node {\ttfamily\footnotesize flatten} (C2-3);
  5754. \path[->,bend right=15] (C2-3) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  5755. \path[->,bend left=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5756. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5757. \path[->,bend right=15] (x86-2-2) edge [left] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5758. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  5759. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  5760. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  5761. \end{tikzpicture}
  5762. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  5763. functions.}
  5764. \label{fig:R5-passes}
  5765. \end{figure}
  5766. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  5767. for the compilation of $R_5$.
  5768. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5769. \chapter{Dynamic Typing}
  5770. \label{ch:type-dynamic}
  5771. In this chapter we discuss the compilation of a dynamically typed
  5772. language, named $R_7$, that is a subset of the Racket language. (In
  5773. the previous chapters we have studied subsets of the \emph{Typed}
  5774. Racket language.) In dynamically typed languages, an expression may
  5775. produce values of differing type. Consider the following example with
  5776. a conditional expression that may return a Boolean or an integer
  5777. depending on the input to the program.
  5778. \begin{lstlisting}
  5779. (not (if (eq? (read) 1) #f 0))
  5780. \end{lstlisting}
  5781. Languages that allow expressions to produce different kinds of values
  5782. are called \emph{polymorphic}, and there are many kinds of
  5783. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5784. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5785. Another characteristic of dynamically typed languages is that
  5786. primitive operations, such as \code{not}, are often defined to operate
  5787. on many different types of values. In fact, in Racket, the \code{not}
  5788. operator produces a result for any kind of value: given \code{\#f} it
  5789. returns \code{\#t} and given anything else it returns \code{\#f}.
  5790. Furthermore, even when primitive operations restrict their inputs to
  5791. values of a certain type, this restriction is enforced at runtime
  5792. instead of during compilation. For example, the following vector
  5793. reference results in a run-time contract violation.
  5794. \begin{lstlisting}
  5795. (vector-ref (vector 42) #t)
  5796. \end{lstlisting}
  5797. Let us consider how we might compile untyped Racket to x86, thinking
  5798. about the first example above. Our bit-level representation of the
  5799. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5800. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5801. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5802. \code{not}, in general, cannot be determined at compile time, but
  5803. depends on the runtime type of its input, as in the example above that
  5804. depends on the result of \code{(read)}.
  5805. The way around this problem is to include information about a value's
  5806. runtime type in the value itself, so that this information can be
  5807. inspected by operators such as \code{not}. In particular, we shall
  5808. steal the 3 right-most bits from our 64-bit values to encode the
  5809. runtime type. We shall use $001$ to identify integers, $100$ for
  5810. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  5811. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5812. define the following auxilliary function.
  5813. \begin{align*}
  5814. \itm{tagof}(\key{Integer}) &= 001 \\
  5815. \itm{tagof}(\key{Boolean}) &= 100 \\
  5816. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5817. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5818. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5819. \itm{tagof}(\key{Void}) &= 101
  5820. \end{align*}
  5821. (We shall say more about the new \key{Vectorof} type shortly.)
  5822. This stealing of 3 bits comes at some
  5823. price: our integers are reduced to ranging from $-2^{60}$ to
  5824. $2^{60}$. The stealing does not adversely affect vectors and
  5825. procedures because those values are addresses, and our addresses are
  5826. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5827. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5828. bits with the tag and we can simply zero-out the tag to recover the
  5829. original address.
  5830. In some sense, these tagged values are a new kind of value. Indeed,
  5831. we can extend our \emph{typed} language with tagged values by adding a
  5832. new type to classify them, called \key{Any}, and with operations for
  5833. creating and using tagged values, creating the $R_6$ language defined
  5834. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5835. support for polymorphism and runtime types that we need to support
  5836. dynamic typing.
  5837. We shall implement our untyped language $R_7$ by compiling it to
  5838. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5839. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5840. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5841. \label{sec:r6-lang}
  5842. \begin{figure}[tp]
  5843. \centering
  5844. \fbox{
  5845. \begin{minipage}{0.97\textwidth}
  5846. \[
  5847. \begin{array}{lcl}
  5848. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5849. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5850. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5851. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5852. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5853. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5854. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5855. \mid (\key{+} \; \Exp\;\Exp)} \\
  5856. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5857. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5858. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5859. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5860. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5861. (\key{vector-ref}\;\Exp\;\Int)} \\
  5862. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5863. &\mid& \gray{(\Exp \; \Exp^{*})
  5864. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5865. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5866. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5867. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  5868. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5869. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5870. \end{array}
  5871. \]
  5872. \end{minipage}
  5873. }
  5874. \caption{Syntax of $R_6$, extending $R_5$ with \key{Any}.}
  5875. \label{fig:r6-syntax}
  5876. \end{figure}
  5877. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5878. $(\key{inject}\; e\; T)$ form converts the value produced by
  5879. expression $e$ of type $T$ into a tagged value. The
  5880. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5881. expression $e$ into a value of type $T$ or else halts the program if
  5882. the type tag does not match $T$. Note that in both \key{inject} and
  5883. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5884. which simplifies the implementation and corresponds with what is
  5885. needed for compiling untyped Racket. The type predicates,
  5886. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5887. if the tag corresponds to the predicate, and return \key{\#t}
  5888. otherwise.
  5889. %
  5890. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5891. \begin{figure}[tbp]
  5892. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5893. (define type-predicates
  5894. (set 'boolean? 'integer? 'vector? 'procedure?))
  5895. (define (typecheck-R6 env)
  5896. (lambda (e)
  5897. (define recur (typecheck-R6 env))
  5898. (match e
  5899. [`(inject ,(app recur new-e e-ty) ,ty)
  5900. (cond
  5901. [(equal? e-ty ty)
  5902. (values `(inject ,new-e ,ty) 'Any)]
  5903. [else
  5904. (error "inject expected ~a to have type ~a" e ty)])]
  5905. [`(project ,(app recur new-e e-ty) ,ty)
  5906. (cond
  5907. [(equal? e-ty 'Any)
  5908. (values `(project ,new-e ,ty) ty)]
  5909. [else
  5910. (error "project expected ~a to have type Any" e)])]
  5911. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5912. (define-values (new-e e-ty) (recur e))
  5913. (cond
  5914. [(equal? e-ty 'Any)
  5915. (values `(,pred ,new-e) 'Boolean)]
  5916. [else
  5917. (error "predicate expected arg of type Any, not" e-ty)])]
  5918. [`(vector-ref ,(app recur e t) ,i)
  5919. (match t
  5920. [`(Vector ,ts ...) ...]
  5921. [`(Vectorof ,t)
  5922. (unless (exact-nonnegative-integer? i)
  5923. (error 'type-check "invalid index ~a" i))
  5924. (values `(vector-ref ,e ,i) t)]
  5925. [else (error "expected a vector in vector-ref, not" t)])]
  5926. [`(vector-set! ,(app recur e-vec t-vec) ,i
  5927. ,(app recur e-arg t-arg))
  5928. (match t-vec
  5929. [`(Vector ,ts ...) ...]
  5930. [`(Vectorof ,t)
  5931. (unless (exact-nonnegative-integer? i)
  5932. (error 'type-check "invalid index ~a" i))
  5933. (unless (equal? t t-arg)
  5934. (error 'type-check "type mismatch in vector-set! ~a ~a"
  5935. t t-arg))
  5936. (values `(vector-set! ,e-vec ,i ,e-arg) 'Void)]
  5937. [else (error 'type-check
  5938. "expected a vector in vector-set!, not ~a"
  5939. t-vec)])]
  5940. ...
  5941. )))
  5942. \end{lstlisting}
  5943. \caption{Type checker for the $R_6$ language.}
  5944. \label{fig:typecheck-R6}
  5945. \end{figure}
  5946. % to do: add rules for vector-ref, etc. for Vectorof
  5947. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5948. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5949. for $R_6$.
  5950. \begin{figure}[tbp]
  5951. \begin{lstlisting}
  5952. (define primitives (set 'boolean? ...))
  5953. (define (interp-op op)
  5954. (match op
  5955. ['boolean? (lambda (v)
  5956. (match v
  5957. [`(tagged ,v1 Boolean) #t]
  5958. [else #f]))]
  5959. ...))
  5960. (define (interp-R6 env)
  5961. (lambda (ast)
  5962. (match ast
  5963. [`(inject ,e ,t)
  5964. `(tagged ,((interp-R6 env) e) ,t)]
  5965. [`(project ,e ,t2)
  5966. (define v ((interp-R6 env) e))
  5967. (match v
  5968. [`(tagged ,v1 ,t1)
  5969. (cond [(equal? t1 t2)
  5970. v1]
  5971. [else
  5972. (error "in project, type mismatch" t1 t2)])]
  5973. [else
  5974. (error "in project, expected tagged value" v)])]
  5975. ...)))
  5976. \end{lstlisting}
  5977. \caption{Interpreter for $R_6$.}
  5978. \label{fig:interp-R6}
  5979. \end{figure}
  5980. \section{The $R_7$ Language: Untyped Racket}
  5981. \label{sec:r7-lang}
  5982. \begin{figure}[tp]
  5983. \centering
  5984. \fbox{
  5985. \begin{minipage}{0.97\textwidth}
  5986. \[
  5987. \begin{array}{rcl}
  5988. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5989. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5990. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5991. &\mid& \key{\#t} \mid \key{\#f} \mid
  5992. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5993. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5994. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5995. (\key{vector-ref}\;\Exp\;\Exp) \\
  5996. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5997. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5998. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5999. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6000. \end{array}
  6001. \]
  6002. \end{minipage}
  6003. }
  6004. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6005. \label{fig:r7-syntax}
  6006. \end{figure}
  6007. The syntax of $R_7$, our subset of Racket, is defined in
  6008. Figure~\ref{fig:r7-syntax}.
  6009. %
  6010. The definitional interpreter for $R_7$ is given in
  6011. Figure~\ref{fig:interp-R7}.
  6012. \begin{figure}[tbp]
  6013. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6014. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6015. (define (valid-op? op) (member op '(+ - and or not)))
  6016. (define (interp-r7 env)
  6017. (lambda (ast)
  6018. (define recur (interp-r7 env))
  6019. (match ast
  6020. [(? symbol?) (lookup ast env)]
  6021. [(? integer?) `(inject ,ast Integer)]
  6022. [#t `(inject #t Boolean)]
  6023. [#f `(inject #f Boolean)]
  6024. [`(read) `(inject ,(read-fixnum) Integer)]
  6025. [`(lambda (,xs ...) ,body)
  6026. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6027. [`(define (,f ,xs ...) ,body)
  6028. (mcons f `(lambda ,xs ,body))]
  6029. [`(program ,ds ... ,body)
  6030. (let ([top-level (map (interp-r7 '()) ds)])
  6031. (for/list ([b top-level])
  6032. (set-mcdr! b (match (mcdr b)
  6033. [`(lambda ,xs ,body)
  6034. `(inject (lambda ,xs ,body ,top-level)
  6035. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6036. ((interp-r7 top-level) body))]
  6037. [`(vector ,(app recur elts) ...)
  6038. (define tys (map get-tagged-type elts))
  6039. `(inject ,(apply vector elts) (Vector ,@tys))]
  6040. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6041. (match v1
  6042. [`(inject ,vec ,ty)
  6043. (vector-set! vec n v2)
  6044. `(inject (void) Void)])]
  6045. [`(vector-ref ,(app recur v) ,n)
  6046. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6047. [`(let ([,x ,(app recur v)]) ,body)
  6048. ((interp-r7 (cons (cons x v) env)) body)]
  6049. [`(,op ,es ...) #:when (valid-op? op)
  6050. (interp-r7-op op (map recur es))]
  6051. [`(eq? ,(app recur l) ,(app recur r))
  6052. `(inject ,(equal? l r) Boolean)]
  6053. [`(if ,(app recur q) ,t ,f)
  6054. (match q
  6055. [`(inject #f Boolean) (recur f)]
  6056. [else (recur t)])]
  6057. [`(,(app recur f-val) ,(app recur vs) ...)
  6058. (match f-val
  6059. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6060. (define new-env (append (map cons xs vs) lam-env))
  6061. ((interp-r7 new-env) body)]
  6062. [else (error "interp-r7, expected function, not" f-val)])])))
  6063. \end{lstlisting}
  6064. \caption{Interpreter for the $R_7$ language.}
  6065. \label{fig:interp-R7}
  6066. \end{figure}
  6067. \section{Compiling $R_6$}
  6068. \label{sec:compile-r6}
  6069. Most of the compiler passes only require straightforward changes. The
  6070. interesting part is in instruction selection.
  6071. \paragraph{Inject}
  6072. We recommend compiling an \key{inject} as follows if the type is
  6073. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6074. destination to the left by the number of bits specified by the source
  6075. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  6076. instruction to combine the tag and the value to form the tagged value.
  6077. \\
  6078. \begin{tabular}{lll}
  6079. \begin{minipage}{0.4\textwidth}
  6080. \begin{lstlisting}
  6081. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6082. \end{lstlisting}
  6083. \end{minipage}
  6084. &
  6085. $\Rightarrow$
  6086. &
  6087. \begin{minipage}{0.5\textwidth}
  6088. \begin{lstlisting}
  6089. (movq |$e'$| |\itm{lhs}'|)
  6090. (salq (int 2) |\itm{lhs}'|)
  6091. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6092. \end{lstlisting}
  6093. \end{minipage}
  6094. \end{tabular} \\
  6095. The instruction selection for vectors and procedures is different
  6096. because their is no need to shift them to the left. The rightmost 3
  6097. bits are already zeros as described above. So we combine the value and
  6098. the tag using
  6099. \key{orq}. \\
  6100. \begin{tabular}{lll}
  6101. \begin{minipage}{0.4\textwidth}
  6102. \begin{lstlisting}
  6103. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6104. \end{lstlisting}
  6105. \end{minipage}
  6106. &
  6107. $\Rightarrow$
  6108. &
  6109. \begin{minipage}{0.5\textwidth}
  6110. \begin{lstlisting}
  6111. (movq |$e'$| |\itm{lhs}'|)
  6112. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6113. \end{lstlisting}
  6114. \end{minipage}
  6115. \end{tabular} \\
  6116. \paragraph{Project}
  6117. The instruction selection for \key{project} is a bit more involved.
  6118. Like \key{inject}, the instructions are different depending on whether
  6119. the type $T$ is a pointer (vector or procedure) or not (Integer or
  6120. Boolean). The following shows the instruction selection for Integer
  6121. and Boolean. We first check to see if the tag on the tagged value
  6122. matches the tag of the target type $T$. If not, we halt the program by
  6123. calling the \code{exit} function. If we have a match, we need to
  6124. produce an untagged value by shifting it to the right by 2 bits.
  6125. %
  6126. \\
  6127. \begin{tabular}{lll}
  6128. \begin{minipage}{0.4\textwidth}
  6129. \begin{lstlisting}
  6130. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6131. \end{lstlisting}
  6132. \end{minipage}
  6133. &
  6134. $\Rightarrow$
  6135. &
  6136. \begin{minipage}{0.5\textwidth}
  6137. \begin{lstlisting}
  6138. (movq |$e'$| |\itm{lhs}'|)
  6139. (andq (int 3) |\itm{lhs}'|)
  6140. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  6141. ((movq |$e'$| |\itm{lhs}'|)
  6142. (sarq (int 2) |\itm{lhs}'|))
  6143. ((callq exit)))
  6144. \end{lstlisting}
  6145. \end{minipage}
  6146. \end{tabular} \\
  6147. %
  6148. The case for vectors and procedures begins in a similar way, checking
  6149. that the runtime tag matches the target type $T$ and exiting if there
  6150. is a mismatch. However, the way in which we convert the tagged value
  6151. to a value is different, as there is no need to shift. Instead we need
  6152. to zero-out the rightmost 2 bits. We accomplish this by creating the
  6153. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  6154. 1100$, and then applying \code{andq} with the tagged value get the
  6155. desired result. \\
  6156. %
  6157. \begin{tabular}{lll}
  6158. \begin{minipage}{0.4\textwidth}
  6159. \begin{lstlisting}
  6160. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6161. \end{lstlisting}
  6162. \end{minipage}
  6163. &
  6164. $\Rightarrow$
  6165. &
  6166. \begin{minipage}{0.5\textwidth}
  6167. \begin{lstlisting}
  6168. (movq |$e'$| |\itm{lhs}'|)
  6169. (andq (int 3) |\itm{lhs}'|)
  6170. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  6171. ((movq (int 3) |\itm{lhs}'|)
  6172. (notq |\itm{lhs}'|)
  6173. (andq |$e'$| |\itm{lhs}'|))
  6174. ((callq exit)))
  6175. \end{lstlisting}
  6176. \end{minipage}
  6177. \end{tabular} \\
  6178. \paragraph{Type Predicates} We leave it to the reader to
  6179. devise a sequence of instructions to implement the type predicates
  6180. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6181. \section{Compiling $R_7$ to $R_6$}
  6182. \label{sec:compile-r7}
  6183. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6184. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6185. given a subexpression $e$ of $R_7$, the pass will produce an
  6186. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6187. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6188. the Boolean \code{\#t}, which must be injected to produce an
  6189. expression of type \key{Any}.
  6190. %
  6191. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6192. addition, is representative of compilation for many operations: the
  6193. arguments have type \key{Any} and must be projected to \key{Integer}
  6194. before the addition can be performed.
  6195. %
  6196. The compilation of \key{lambda} (third row of
  6197. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6198. produce type annotations, we simply use \key{Any}.
  6199. %
  6200. The compilation of \code{if}, \code{eq?}, and \code{and} all
  6201. demonstrate how this pass has to account for some differences in
  6202. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  6203. permissive than $R_6$ regarding what kind of values can be used in
  6204. various places. For example, the condition of an \key{if} does not
  6205. have to be a Boolean. Similarly, the arguments of \key{and} do not
  6206. need to be Boolean. For \key{eq?}, the arguments need not be of the
  6207. same type.
  6208. \begin{figure}[tbp]
  6209. \centering
  6210. \begin{tabular}{|lll|} \hline
  6211. \begin{minipage}{0.25\textwidth}
  6212. \begin{lstlisting}
  6213. #t
  6214. \end{lstlisting}
  6215. \end{minipage}
  6216. &
  6217. $\Rightarrow$
  6218. &
  6219. \begin{minipage}{0.6\textwidth}
  6220. \begin{lstlisting}
  6221. (inject #t Boolean)
  6222. \end{lstlisting}
  6223. \end{minipage}
  6224. \\[2ex]\hline
  6225. \begin{minipage}{0.25\textwidth}
  6226. \begin{lstlisting}
  6227. (+ |$e_1$| |$e_2$|)
  6228. \end{lstlisting}
  6229. \end{minipage}
  6230. &
  6231. $\Rightarrow$
  6232. &
  6233. \begin{minipage}{0.6\textwidth}
  6234. \begin{lstlisting}
  6235. (inject
  6236. (+ (project |$e'_1$| Integer)
  6237. (project |$e'_2$| Integer))
  6238. Integer)
  6239. \end{lstlisting}
  6240. \end{minipage}
  6241. \\[2ex]\hline
  6242. \begin{minipage}{0.25\textwidth}
  6243. \begin{lstlisting}
  6244. (lambda (|$x_1 \ldots$|) |$e$|)
  6245. \end{lstlisting}
  6246. \end{minipage}
  6247. &
  6248. $\Rightarrow$
  6249. &
  6250. \begin{minipage}{0.6\textwidth}
  6251. \begin{lstlisting}
  6252. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6253. (Any|$\ldots$|Any -> Any))
  6254. \end{lstlisting}
  6255. \end{minipage}
  6256. \\[2ex]\hline
  6257. \begin{minipage}{0.25\textwidth}
  6258. \begin{lstlisting}
  6259. (app |$e_0$| |$e_1 \ldots e_n$|)
  6260. \end{lstlisting}
  6261. \end{minipage}
  6262. &
  6263. $\Rightarrow$
  6264. &
  6265. \begin{minipage}{0.6\textwidth}
  6266. \begin{lstlisting}
  6267. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6268. |$e'_1 \ldots e'_n$|)
  6269. \end{lstlisting}
  6270. \end{minipage}
  6271. \\[2ex]\hline
  6272. \begin{minipage}{0.25\textwidth}
  6273. \begin{lstlisting}
  6274. (vector-ref |$e_1$| |$e_2$|)
  6275. \end{lstlisting}
  6276. \end{minipage}
  6277. &
  6278. $\Rightarrow$
  6279. &
  6280. \begin{minipage}{0.6\textwidth}
  6281. \begin{lstlisting}
  6282. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6283. (let ([tmp2 (project |$e'_2$| Integer)])
  6284. (vector-ref tmp1 tmp2)))
  6285. \end{lstlisting}
  6286. \end{minipage}
  6287. \\[2ex]\hline
  6288. \begin{minipage}{0.25\textwidth}
  6289. \begin{lstlisting}
  6290. (if |$e_1$| |$e_2$| |$e_3$|)
  6291. \end{lstlisting}
  6292. \end{minipage}
  6293. &
  6294. $\Rightarrow$
  6295. &
  6296. \begin{minipage}{0.6\textwidth}
  6297. \begin{lstlisting}
  6298. (if (eq? |$e'_1$| (inject #f Boolean))
  6299. |$e'_3$|
  6300. |$e'_2$|)
  6301. \end{lstlisting}
  6302. \end{minipage}
  6303. \\[2ex]\hline
  6304. \begin{minipage}{0.25\textwidth}
  6305. \begin{lstlisting}
  6306. (eq? |$e_1$| |$e_2$|)
  6307. \end{lstlisting}
  6308. \end{minipage}
  6309. &
  6310. $\Rightarrow$
  6311. &
  6312. \begin{minipage}{0.6\textwidth}
  6313. \begin{lstlisting}
  6314. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6315. \end{lstlisting}
  6316. \end{minipage}
  6317. \\[2ex]\hline
  6318. \begin{minipage}{0.25\textwidth}
  6319. \begin{lstlisting}
  6320. (and |$e_1$| |$e_2$|)
  6321. \end{lstlisting}
  6322. \end{minipage}
  6323. &
  6324. $\Rightarrow$
  6325. &
  6326. \begin{minipage}{0.6\textwidth}
  6327. \begin{lstlisting}
  6328. (let ([tmp |$e'_1$|])
  6329. (if (eq? tmp (inject #f Boolean))
  6330. tmp
  6331. |$e'_2$|))
  6332. \end{lstlisting}
  6333. \end{minipage} \\\hline
  6334. \end{tabular} \\
  6335. \caption{Compiling $R_7$ to $R_6$.}
  6336. \label{fig:compile-r7-r6}
  6337. \end{figure}
  6338. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6339. \chapter{Gradual Typing}
  6340. \label{ch:gradual-typing}
  6341. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6342. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6343. \chapter{Parametric Polymorphism}
  6344. \label{ch:parametric-polymorphism}
  6345. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6346. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6347. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6348. \chapter{High-level Optimization}
  6349. \label{ch:high-level-optimization}
  6350. This chapter will present a procedure inlining pass based on the
  6351. algorithm of \citet{Waddell:1997fk}.
  6352. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6353. \chapter{Appendix}
  6354. \section{Interpreters}
  6355. \label{appendix:interp}
  6356. We provide several interpreters in the \key{interp.rkt} file. The
  6357. \key{interp-scheme} function takes an AST in one of the Racket-like
  6358. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6359. the program, returning the result value. The \key{interp-C} function
  6360. interprets an AST for a program in one of the C-like languages ($C_0,
  6361. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6362. for an x86 program.
  6363. \section{Utility Functions}
  6364. \label{appendix:utilities}
  6365. The utility function described in this section can be found in the
  6366. \key{utilities.rkt} file.
  6367. The \key{read-program} function takes a file path and parses that file
  6368. (it must be a Racket program) into an abstract syntax tree (as an
  6369. S-expression) with a \key{program} AST at the top.
  6370. The \key{assert} function displays the error message \key{msg} if the
  6371. Boolean \key{bool} is false.
  6372. \begin{lstlisting}
  6373. (define (assert msg bool) ...)
  6374. \end{lstlisting}
  6375. The \key{lookup} function takes a key and an association list (a list
  6376. of key-value pairs), and returns the first value that is associated
  6377. with the given key, if there is one. If not, an error is triggered.
  6378. The association list may contain both immutable pairs (built with
  6379. \key{cons}) and mutable mapirs (built with \key{mcons}).
  6380. The \key{map2} function ...
  6381. \subsection{Graphs}
  6382. \begin{itemize}
  6383. \item The \code{make-graph} function takes a list of vertices
  6384. (symbols) and returns a graph.
  6385. \item The \code{add-edge} function takes a graph and two vertices and
  6386. adds an edge to the graph that connects the two vertices. The graph
  6387. is updated in-place. There is no return value for this function.
  6388. \item The \code{adjacent} function takes a graph and a vertex and
  6389. returns the set of vertices that are adjacent to the given
  6390. vertex. The return value is a Racket \code{hash-set} so it can be
  6391. used with functions from the \code{racket/set} module.
  6392. \item The \code{vertices} function takes a graph and returns the list
  6393. of vertices in the graph.
  6394. \end{itemize}
  6395. \subsection{Testing}
  6396. The \key{interp-tests} function takes a compiler name (a string), a
  6397. description of the passes, an interpreter for the source language, a
  6398. test family name (a string), and a list of test numbers, and runs the
  6399. compiler passes and the interpreters to check whether the passes
  6400. correct. The description of the passes is a list with one entry per
  6401. pass. An entry is a list with three things: a string giving the name
  6402. of the pass, the function that implements the pass (a translator from
  6403. AST to AST), and a function that implements the interpreter (a
  6404. function from AST to result value) for the language of the output of
  6405. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6406. good choice. The \key{interp-tests} function assumes that the
  6407. subdirectory \key{tests} has a bunch of Scheme programs whose names
  6408. all start with the family name, followed by an underscore and then the
  6409. test number, ending in \key{.scm}. Also, for each Scheme program there
  6410. is a file with the same number except that it ends with \key{.in} that
  6411. provides the input for the Scheme program.
  6412. \begin{lstlisting}
  6413. (define (interp-tests name passes test-family test-nums) ...
  6414. \end{lstlisting}
  6415. The compiler-tests function takes a compiler name (a string) a
  6416. description of the passes (see the comment for \key{interp-tests}) a
  6417. test family name (a string), and a list of test numbers (see the
  6418. comment for interp-tests), and runs the compiler to generate x86 (a
  6419. \key{.s} file) and then runs gcc to generate machine code. It runs
  6420. the machine code and checks that the output is 42.
  6421. \begin{lstlisting}
  6422. (define (compiler-tests name passes test-family test-nums) ...)
  6423. \end{lstlisting}
  6424. The compile-file function takes a description of the compiler passes
  6425. (see the comment for \key{interp-tests}) and returns a function that,
  6426. given a program file name (a string ending in \key{.scm}), applies all
  6427. of the passes and writes the output to a file whose name is the same
  6428. as the program file name but with \key{.scm} replaced with \key{.s}.
  6429. \begin{lstlisting}
  6430. (define (compile-file passes)
  6431. (lambda (prog-file-name) ...))
  6432. \end{lstlisting}
  6433. \section{x86 Instruction Set Quick-Reference}
  6434. \label{sec:x86-quick-reference}
  6435. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6436. do. We write $A \to B$ to mean that the value of $A$ is written into
  6437. location $B$. Address offsets are given in bytes. The instruction
  6438. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6439. registers (such as $\%rax$), or memory references (such as
  6440. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6441. reference per instruction. Other operands must be immediates or
  6442. registers.
  6443. \begin{table}[tbp]
  6444. \centering
  6445. \begin{tabular}{l|l}
  6446. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6447. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6448. \texttt{negq} $A$ & $- A \to A$ \\
  6449. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6450. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6451. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6452. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6453. \texttt{retq} & Pops the return address and jumps to it \\
  6454. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6455. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6456. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6457. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6458. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6459. matches the condition code of the instruction, otherwise go to the
  6460. next instructions. The condition codes are \key{e} for ``equal'',
  6461. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6462. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6463. \texttt{jl} $L$ & \\
  6464. \texttt{jle} $L$ & \\
  6465. \texttt{jg} $L$ & \\
  6466. \texttt{jge} $L$ & \\
  6467. \texttt{jmp} $L$ & Jump to label $L$ \\
  6468. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6469. \texttt{movzbq} $A$, $B$ &
  6470. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6471. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6472. and the extra bytes of $B$ are set to zero.} \\
  6473. & \\
  6474. & \\
  6475. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6476. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6477. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6478. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6479. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6480. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6481. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6482. description of the condition codes. $A$ must be a single byte register
  6483. (e.g., \texttt{al} or \texttt{cl}).} \\
  6484. \texttt{setl} $A$ & \\
  6485. \texttt{setle} $A$ & \\
  6486. \texttt{setg} $A$ & \\
  6487. \texttt{setge} $A$ &
  6488. \end{tabular}
  6489. \vspace{5pt}
  6490. \caption{Quick-reference for the x86 instructions used in this book.}
  6491. \label{tab:x86-instr}
  6492. \end{table}
  6493. \bibliographystyle{plainnat}
  6494. \bibliography{all}
  6495. \end{document}
  6496. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6497. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6498. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6499. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6500. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6501. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6502. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6503. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6504. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6505. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6506. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6507. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6508. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6509. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6510. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6511. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6512. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6513. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6514. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6515. %% LocalWords: len prev rootlen heaplen setl lt