book.tex 271 KB

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