book.tex 221 KB

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