book.tex 316 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \definecolor{lightgray}{gray}{1}
  53. \newcommand{\black}[1]{{\color{black} #1}}
  54. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  55. \newcommand{\gray}[1]{{\color{gray} #1}}
  56. %% For pictures
  57. \usepackage{tikz}
  58. \usetikzlibrary{arrows.meta}
  59. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  60. % Computer Modern is already the default. -Jeremy
  61. %\renewcommand{\ttdefault}{cmtt}
  62. \definecolor{comment-red}{rgb}{0.8,0,0}
  63. \if{0}
  64. % Peanut gallery comments:
  65. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  66. \newcommand{\margincomment}[1]{\marginpar{#1}}
  67. \else
  68. \newcommand{\rn}[1]{}
  69. \newcommand{\margincomment}[1]{}
  70. \fi
  71. \lstset{%
  72. language=Lisp,
  73. basicstyle=\ttfamily\small,
  74. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  75. deletekeywords={read},
  76. escapechar=|,
  77. columns=flexible,
  78. moredelim=[is][\color{red}]{~}{~}
  79. }
  80. \newtheorem{theorem}{Theorem}
  81. \newtheorem{lemma}[theorem]{Lemma}
  82. \newtheorem{corollary}[theorem]{Corollary}
  83. \newtheorem{proposition}[theorem]{Proposition}
  84. \newtheorem{constraint}[theorem]{Constraint}
  85. \newtheorem{definition}[theorem]{Definition}
  86. \newtheorem{exercise}[theorem]{Exercise}
  87. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  88. % 'dedication' environment: To add a dedication paragraph at the start of book %
  89. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  90. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  91. \newenvironment{dedication}
  92. {
  93. \cleardoublepage
  94. \thispagestyle{empty}
  95. \vspace*{\stretch{1}}
  96. \hfill\begin{minipage}[t]{0.66\textwidth}
  97. \raggedright
  98. }
  99. {
  100. \end{minipage}
  101. \vspace*{\stretch{3}}
  102. \clearpage
  103. }
  104. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  105. % Chapter quote at the start of chapter %
  106. % Source: http://tex.stackexchange.com/a/53380 %
  107. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  108. \makeatletter
  109. \renewcommand{\@chapapp}{}% Not necessary...
  110. \newenvironment{chapquote}[2][2em]
  111. {\setlength{\@tempdima}{#1}%
  112. \def\chapquote@author{#2}%
  113. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  114. \itshape}
  115. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  116. \makeatother
  117. \input{defs}
  118. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  119. \title{\Huge \textbf{Essentials of Compilation} \\
  120. \huge An Incremental Approach}
  121. \author{\textsc{Jeremy G. Siek} \\
  122. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  123. Indiana University \\
  124. \\
  125. with contributions from: \\
  126. Carl Factora \\
  127. Andre Kuhlenschmidt \\
  128. Ryan R. Newton \\
  129. Ryan Scott \\
  130. Cameron Swords \\
  131. Michael M. Vitousek \\
  132. Michael Vollmer
  133. }
  134. \begin{document}
  135. \frontmatter
  136. \maketitle
  137. \begin{dedication}
  138. This book is dedicated to the programming language wonks at Indiana
  139. University.
  140. \end{dedication}
  141. \tableofcontents
  142. \listoffigures
  143. %\listoftables
  144. \mainmatter
  145. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  146. \chapter*{Preface}
  147. The tradition of compiler writing at Indiana University goes back to
  148. research and courses about programming languages by Daniel Friedman in
  149. the 1970's and 1980's. Dan conducted research on lazy
  150. evaluation~\citep{Friedman:1976aa} in the context of
  151. Lisp~\citep{McCarthy:1960dz} and then studied
  152. continuations~\citep{Felleisen:kx} and
  153. macros~\citep{Kohlbecker:1986dk} in the context of the
  154. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  155. of those courses, Kent Dybvig, went on to build Chez
  156. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  157. compiler for Scheme. After completing his Ph.D. at the University of
  158. North Carolina, Kent returned to teach at Indiana University.
  159. Throughout the 1990's and 2000's, Kent continued development of Chez
  160. Scheme and taught the compiler course.
  161. The compiler course evolved to incorporate novel pedagogical ideas
  162. while also including elements of effective real-world compilers. One
  163. of Dan's ideas was to split the compiler into many small ``passes'' so
  164. that the code for each pass would be easy to understood in isolation.
  165. (In contrast, most compilers of the time were organized into only a
  166. few monolithic passes for reasons of compile-time efficiency.) Kent,
  167. with later help from his students Dipanwita Sarkar and Andrew Keep,
  168. developed infrastructure to support this approach and evolved the
  169. course, first to use micro-sized passes and then into even smaller
  170. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  171. student in this compiler course in the early 2000's, as part of his
  172. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  173. the course immensely!
  174. During that time, another student named Abdulaziz Ghuloum observed
  175. that the front-to-back organization of the course made it difficult
  176. for students to understand the rationale for the compiler
  177. design. Abdulaziz proposed an incremental approach in which the
  178. students build the compiler in stages; they start by implementing a
  179. complete compiler for a very small subset of the input language and in
  180. each subsequent stage they add a language feature and add or modify
  181. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  182. the students see how the language features motivate aspects of the
  183. compiler design.
  184. After graduating from Indiana University in 2005, Jeremy went on to
  185. teach at the University of Colorado. He adapted the nano pass and
  186. incremental approaches to compiling a subset of the Python
  187. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  188. on the surface but there is a large overlap in the compiler techniques
  189. required for the two languages. Thus, Jeremy was able to teach much of
  190. the same content from the Indiana compiler course. He very much
  191. enjoyed teaching the course organized in this way, and even better,
  192. many of the students learned a lot and got excited about compilers.
  193. Jeremy returned to teach at Indiana University in 2013. In his
  194. absence the compiler course had switched from the front-to-back
  195. organization to a back-to-front organization. Seeing how well the
  196. incremental approach worked at Colorado, he started porting and
  197. adapting the structure of the Colorado course back into the land of
  198. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  199. the course is now about compiling a subset of Racket (and Typed
  200. Racket) to the x86 assembly language. The compiler is implemented in
  201. Racket 7.1~\citep{plt-tr}.
  202. This is the textbook for the incremental version of the compiler
  203. course at Indiana University (Spring 2016 - present) and it is the
  204. first open textbook for an Indiana compiler course. With this book we
  205. hope to make the Indiana compiler course available to people that have
  206. not had the chance to study in Bloomington in person. Many of the
  207. compiler design decisions in this book are drawn from the assignment
  208. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  209. are the most important topics from \cite{Dybvig:2010aa} but we have
  210. omitted topics that we think are less interesting conceptually and we
  211. have made simplifications to reduce complexity. In this way, this
  212. book leans more towards pedagogy than towards the efficiency of the
  213. generated code. Also, the book differs in places where we saw the
  214. opportunity to make the topics more fun, such as in relating register
  215. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  216. \section*{Prerequisites}
  217. The material in this book is challenging but rewarding. It is meant to
  218. prepare students for a lifelong career in programming languages.
  219. The book uses the Racket language both for the implementation of the
  220. compiler and for the language that is compiled, so a student should be
  221. proficient with Racket (or Scheme) prior to reading this book. There
  222. are many excellent resources for learning Scheme and
  223. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  224. is helpful but not necessary for the student to have prior exposure to
  225. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  226. obtain from a computer systems
  227. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  228. parts of x86-64 assembly language that are needed.
  229. %\section*{Structure of book}
  230. % You might want to add short description about each chapter in this book.
  231. %\section*{About the companion website}
  232. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  233. %\begin{itemize}
  234. % \item A link to (freely downlodable) latest version of this document.
  235. % \item Link to download LaTeX source for this document.
  236. % \item Miscellaneous material (e.g. suggested readings etc).
  237. %\end{itemize}
  238. \section*{Acknowledgments}
  239. Many people have contributed to the ideas, techniques, organization,
  240. and teaching of the materials in this book. We especially thank the
  241. following people.
  242. \begin{itemize}
  243. \item Bor-Yuh Evan Chang
  244. \item Kent Dybvig
  245. \item Daniel P. Friedman
  246. \item Ronald Garcia
  247. \item Abdulaziz Ghuloum
  248. \item Jay McCarthy
  249. \item Dipanwita Sarkar
  250. \item Andrew Keep
  251. \item Oscar Waddell
  252. \item Michael Wollowski
  253. \end{itemize}
  254. \mbox{}\\
  255. \noindent Jeremy G. Siek \\
  256. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  257. %\noindent Spring 2016
  258. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  259. \chapter{Preliminaries}
  260. \label{ch:trees-recur}
  261. In this chapter we review the basic tools that are needed to implement
  262. a compiler. Programs are typically input by a programmer as text,
  263. i.e., a sequence of characters. The program-as-text representation is
  264. called \emph{concrete syntax}. We use concrete syntax to concisely
  265. write down and talk about programs. Inside the compiler, we use
  266. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  267. that efficiently supports the operations that the compiler needs to
  268. perform.
  269. %
  270. The translation from concrete syntax to abstract syntax is a process
  271. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  272. and implementation of parsing in this book. A parser is provided in
  273. the supporting materials for translating from concrete syntax to
  274. abstract syntax for the languages used in this book.
  275. ASTs can be represented in many different ways inside the compiler,
  276. depending on the programming language used to write the compiler.
  277. %
  278. We use Racket's \code{struct} feature to represent ASTs
  279. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  280. of programming languages (Section~\ref{sec:grammar}) and pattern
  281. matching to inspect individual nodes in an AST
  282. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  283. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  284. chapter provides an brief introduction to these ideas.
  285. \section{Abstract Syntax Trees and Racket Structures}
  286. \label{sec:ast}
  287. Compilers use abstract syntax trees to represent programs because
  288. compilers often need to ask questions like: for a given part of a
  289. program, what kind of language feature is it? What are the sub-parts
  290. of this part of the program? Consider the program on the left and its
  291. AST on the right. This program is an addition and it has two
  292. sub-parts, a read operation and a negation. The negation has another
  293. sub-part, the integer constant \code{8}. By using a tree to represent
  294. the program, we can easily follow the links to go from one part of a
  295. program to its sub-parts.
  296. \begin{center}
  297. \begin{minipage}{0.4\textwidth}
  298. \begin{lstlisting}
  299. (+ (read) (- 8))
  300. \end{lstlisting}
  301. \end{minipage}
  302. \begin{minipage}{0.4\textwidth}
  303. \begin{equation}
  304. \begin{tikzpicture}
  305. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  306. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  307. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  308. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  309. \draw[->] (plus) to (read);
  310. \draw[->] (plus) to (minus);
  311. \draw[->] (minus) to (8);
  312. \end{tikzpicture}
  313. \label{eq:arith-prog}
  314. \end{equation}
  315. \end{minipage}
  316. \end{center}
  317. We use the standard terminology for trees to describe ASTs: each
  318. circle above is called a \emph{node}. The arrows connect a node to its
  319. \emph{children} (which are also nodes). The top-most node is the
  320. \emph{root}. Every node except for the root has a \emph{parent} (the
  321. node it is the child of). If a node has no children, it is a
  322. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  323. %% Recall that an \emph{symbolic expression} (S-expression) is either
  324. %% \begin{enumerate}
  325. %% \item an atom, or
  326. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  327. %% where $e_1$ and $e_2$ are each an S-expression.
  328. %% \end{enumerate}
  329. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  330. %% null value \code{'()}, etc. We can create an S-expression in Racket
  331. %% simply by writing a backquote (called a quasi-quote in Racket)
  332. %% followed by the textual representation of the S-expression. It is
  333. %% quite common to use S-expressions to represent a list, such as $a, b
  334. %% ,c$ in the following way:
  335. %% \begin{lstlisting}
  336. %% `(a . (b . (c . ())))
  337. %% \end{lstlisting}
  338. %% Each element of the list is in the first slot of a pair, and the
  339. %% second slot is either the rest of the list or the null value, to mark
  340. %% the end of the list. Such lists are so common that Racket provides
  341. %% special notation for them that removes the need for the periods
  342. %% and so many parenthesis:
  343. %% \begin{lstlisting}
  344. %% `(a b c)
  345. %% \end{lstlisting}
  346. %% The following expression creates an S-expression that represents AST
  347. %% \eqref{eq:arith-prog}.
  348. %% \begin{lstlisting}
  349. %% `(+ (read) (- 8))
  350. %% \end{lstlisting}
  351. %% When using S-expressions to represent ASTs, the convention is to
  352. %% represent each AST node as a list and to put the operation symbol at
  353. %% the front of the list. The rest of the list contains the children. So
  354. %% in the above case, the root AST node has operation \code{`+} and its
  355. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  356. %% diagram \eqref{eq:arith-prog}.
  357. %% To build larger S-expressions one often needs to splice together
  358. %% several smaller S-expressions. Racket provides the comma operator to
  359. %% splice an S-expression into a larger one. For example, instead of
  360. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  361. %% we could have first created an S-expression for AST
  362. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  363. %% S-expression.
  364. %% \begin{lstlisting}
  365. %% (define ast1.4 `(- 8))
  366. %% (define ast1.1 `(+ (read) ,ast1.4))
  367. %% \end{lstlisting}
  368. %% In general, the Racket expression that follows the comma (splice)
  369. %% can be any expression that produces an S-expression.
  370. We define a Racket \code{struct} for each kind of node. For this
  371. chapter we require just two kinds of nodes: one for integer constants
  372. and one for primitive operations. The following is the \code{struct}
  373. definition for integer constants.
  374. \begin{lstlisting}
  375. (struct Int (value))
  376. \end{lstlisting}
  377. An integer node includes just one thing: the integer value.
  378. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  379. \begin{lstlisting}
  380. (define eight (Int 8))
  381. \end{lstlisting}
  382. We say that the value created by \code{(Int 8)} is an
  383. \emph{instance} of the \code{Int} structure.
  384. The following is the \code{struct} definition for primitives operations.
  385. \begin{lstlisting}
  386. (struct Prim (op arg*))
  387. \end{lstlisting}
  388. A primitive operation node includes an operator symbol \code{op}
  389. and a list of children \code{arg*}. For example, to create
  390. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  391. \begin{lstlisting}
  392. (define neg-eight (Prim '- (list eight)))
  393. \end{lstlisting}
  394. Primitive operations may have zero or more children. The \code{read}
  395. operator has zero children:
  396. \begin{lstlisting}
  397. (define rd (Prim 'read '()))
  398. \end{lstlisting}
  399. whereas the addition operator has two children:
  400. \begin{lstlisting}
  401. (define ast1.1 (Prim '+ (list rd neg-eight)))
  402. \end{lstlisting}
  403. We have made a design choice regarding the \code{Prim} structure.
  404. Instead of using one structure for many different operations
  405. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  406. structure for each operation, as follows.
  407. \begin{lstlisting}
  408. (struct Read ())
  409. (struct Add (left right))
  410. (struct Neg (value))
  411. \end{lstlisting}
  412. The reason we choose to use just one structure is that in many parts
  413. of the compiler the code for the different primitive operators is the
  414. same, so we might as well just write that code once, which is enabled
  415. by using a single structure.
  416. When compiling a program such as \eqref{eq:arith-prog}, we need to
  417. know that the operation associated with the root node is addition and
  418. we need to be able to access its two children. Racket provides pattern
  419. matching over structures to support these kinds of queries, as we
  420. shall see in Section~\ref{sec:pattern-matching}.
  421. In this book, we often write down the concrete syntax of a program
  422. even when we really have in mind the AST because the concrete syntax
  423. is more concise. We recommend that, in your mind, you always think of
  424. programs as abstract syntax trees.
  425. \section{Grammars}
  426. \label{sec:grammar}
  427. A programming language can be thought of as a \emph{set} of programs.
  428. The set is typically infinite (one can always create larger and larger
  429. programs), so one cannot simply describe a language by listing all of
  430. the programs in the language. Instead we write down a set of rules, a
  431. \emph{grammar}, for building programs. Grammars are often used to
  432. define the concrete syntax of a language, but they can also be used to
  433. describe the abstract syntax. We shall write our rules in a variant of
  434. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  435. example, we describe a small language, named $R_0$, that consists of
  436. integers and arithmetic operations.
  437. The first grammar rule for the abstract syntax of $R_0$ says that an
  438. instance of the \code{Int} structure is an expression:
  439. \begin{equation}
  440. \Exp ::= \INT{\Int} \label{eq:arith-int}
  441. \end{equation}
  442. %
  443. Each rule has a left-hand-side and a right-hand-side. The way to read
  444. a rule is that if you have all the program parts on the
  445. right-hand-side, then you can create an AST node and categorize it
  446. according to the left-hand-side.
  447. %
  448. A name such as $\Exp$ that is
  449. defined by the grammar rules is a \emph{non-terminal}.
  450. %
  451. The name $\Int$ is a also a non-terminal, but instead of defining it
  452. with a grammar rule, we define it with the following explanation. We
  453. make the simplifying design decision that all of the languages in this
  454. book only handle machine-representable integers. On most modern
  455. machines this corresponds to integers represented with 64-bits, i.e.,
  456. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  457. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  458. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  459. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  460. that the sequence of decimals represent an integer in range $-2^{62}$
  461. to $2^{62}-1$.
  462. The second grammar rule is the \texttt{read} operation that receives
  463. an input integer from the user of the program.
  464. \begin{equation}
  465. \Exp ::= \READ{} \label{eq:arith-read}
  466. \end{equation}
  467. The third rule says that, given an $\Exp$ node, you can build another
  468. $\Exp$ node by negating it.
  469. \begin{equation}
  470. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  471. \end{equation}
  472. Symbols in typewriter font such as \key{-} and \key{read} are
  473. \emph{terminal} symbols and must literally appear in the program for
  474. the rule to be applicable.
  475. We can apply the rules to build ASTs in the $R_0$
  476. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  477. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  478. an $\Exp$.
  479. \begin{center}
  480. \begin{minipage}{0.4\textwidth}
  481. \begin{lstlisting}
  482. (Prim '- (list (Int 8)))
  483. \end{lstlisting}
  484. \end{minipage}
  485. \begin{minipage}{0.25\textwidth}
  486. \begin{equation}
  487. \begin{tikzpicture}
  488. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  489. \node[draw, circle] (8) at (0, -1.2) {$8$};
  490. \draw[->] (minus) to (8);
  491. \end{tikzpicture}
  492. \label{eq:arith-neg8}
  493. \end{equation}
  494. \end{minipage}
  495. \end{center}
  496. The next grammar rule defines addition expressions:
  497. \begin{equation}
  498. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  499. \end{equation}
  500. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  501. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  502. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  503. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  504. to show that
  505. \begin{lstlisting}
  506. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  507. \end{lstlisting}
  508. is an $\Exp$ in the $R_0$ language.
  509. If you have an AST for which the above rules do not apply, then the
  510. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  511. is not in $R_0$ because there are no rules for \code{+} with only one
  512. argument, nor for \key{-} with two arguments. Whenever we define a
  513. language with a grammar, the language only includes those programs
  514. that are justified by the rules.
  515. The last grammar rule for $R_0$ states that there is a \code{Program}
  516. node to mark the top of the whole program:
  517. \[
  518. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  519. \]
  520. The \code{Program} structure is defined as follows
  521. \begin{lstlisting}
  522. (struct Program (info body))
  523. \end{lstlisting}
  524. where \code{body} is an expression. In later chapters, the \code{info}
  525. part will be used to store auxiliary information but for now it is
  526. just the empty list.
  527. It is common to have many grammar rules with the same left-hand side
  528. but different right-hand sides, such as the rules for $\Exp$ in the
  529. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  530. combine several right-hand-sides into a single rule.
  531. We collect all of the grammar rules for the abstract syntax of $R_0$
  532. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  533. defined in Figure~\ref{fig:r0-concrete-syntax}.
  534. The \code{read-program} function provided in \code{utilities.rkt} of
  535. the support materials reads a program in from a file (the sequence of
  536. characters in the concrete syntax of Racket) and parses it into an
  537. abstract syntax tree. See the description of \code{read-program} in
  538. Appendix~\ref{appendix:utilities} for more details.
  539. \begin{figure}[tp]
  540. \fbox{
  541. \begin{minipage}{0.96\textwidth}
  542. \[
  543. \begin{array}{rcl}
  544. \begin{array}{rcl}
  545. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  546. R_0 &::=& \Exp
  547. \end{array}
  548. \end{array}
  549. \]
  550. \end{minipage}
  551. }
  552. \caption{The concrete syntax of $R_0$.}
  553. \label{fig:r0-concrete-syntax}
  554. \end{figure}
  555. \begin{figure}[tp]
  556. \fbox{
  557. \begin{minipage}{0.96\textwidth}
  558. \[
  559. \begin{array}{rcl}
  560. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  561. &\mid& \ADD{\Exp}{\Exp} \\
  562. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  563. \end{array}
  564. \]
  565. \end{minipage}
  566. }
  567. \caption{The abstract syntax of $R_0$.}
  568. \label{fig:r0-syntax}
  569. \end{figure}
  570. \section{Pattern Matching}
  571. \label{sec:pattern-matching}
  572. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  573. the parts of an AST node. Racket provides the \texttt{match} form to
  574. access the parts of a structure. Consider the following example and
  575. the output on the right.
  576. \begin{center}
  577. \begin{minipage}{0.5\textwidth}
  578. \begin{lstlisting}
  579. (match ast1.1
  580. [(Prim op (list child1 child2))
  581. (print op)])
  582. \end{lstlisting}
  583. \end{minipage}
  584. \vrule
  585. \begin{minipage}{0.25\textwidth}
  586. \begin{lstlisting}
  587. '+
  588. \end{lstlisting}
  589. \end{minipage}
  590. \end{center}
  591. In the above example, the \texttt{match} form takes the AST
  592. \eqref{eq:arith-prog} and binds its parts to the three pattern
  593. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  594. general, a match clause consists of a \emph{pattern} and a
  595. \emph{body}. Patterns are recursively defined to be either a pattern
  596. variable, a structure name followed by a pattern for each of the
  597. structure's arguments, or an S-expression (symbols, lists, etc.).
  598. (See Chapter 12 of The Racket
  599. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  600. and Chapter 9 of The Racket
  601. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  602. for a complete description of \code{match}.)
  603. %
  604. The body of a match clause may contain arbitrary Racket code. The
  605. pattern variables can be used in the scope of the body.
  606. A \code{match} form may contain several clauses, as in the following
  607. function \code{leaf?} that recognizes when an $R_0$ node is
  608. a leaf. The \code{match} proceeds through the clauses in order,
  609. checking whether the pattern can match the input AST. The
  610. body of the first clause that matches is executed. The output of
  611. \code{leaf?} for several ASTs is shown on the right.
  612. \begin{center}
  613. \begin{minipage}{0.6\textwidth}
  614. \begin{lstlisting}
  615. (define (leaf? arith)
  616. (match arith
  617. [(Int n) #t]
  618. [(Prim 'read '()) #t]
  619. [(Prim '- (list c1)) #f]
  620. [(Prim '+ (list c1 c2)) #f]))
  621. (leaf? (Prim 'read '()))
  622. (leaf? (Prim '- (list (Int 8))))
  623. (leaf? (Int 8))
  624. \end{lstlisting}
  625. \end{minipage}
  626. \vrule
  627. \begin{minipage}{0.25\textwidth}
  628. \begin{lstlisting}
  629. #t
  630. #f
  631. #t
  632. \end{lstlisting}
  633. \end{minipage}
  634. \end{center}
  635. When writing a \code{match}, we refer to the grammar definition to
  636. identify which non-terminal we are expecting to match against, then we
  637. make sure that 1) we have one clause for each alternative of that
  638. non-terminal and 2) that the pattern in each clause corresponds to the
  639. corresponding right-hand side of a grammar rule. For the \code{match}
  640. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  641. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  642. alternatives, so the \code{match} has 4 clauses. The pattern in each
  643. clause corresponds to the right-hand side of a grammar rule. For
  644. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  645. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  646. patterns, replace non-terminals such as $\Exp$ with pattern variables
  647. of your choice (e.g. \code{c1} and \code{c2}).
  648. \section{Recursion}
  649. \label{sec:recursion}
  650. Programs are inherently recursive. For example, an $R_0$ expression is
  651. often made of smaller expressions. Thus, the natural way to process an
  652. entire program is with a recursive function. As a first example of
  653. such a recursive function, we define \texttt{exp?} below, which takes
  654. an arbitrary value and determines whether or not it is an $R_0$
  655. expression.
  656. %
  657. When a recursive function is defined using a sequence of match clauses
  658. that correspond to a grammar, and the body of each clause makes a
  659. recursive call on each child node, then we say the function is defined
  660. by \emph{structural recursion}\footnote{This principle of structuring
  661. code according to the data definition is advocated in the book
  662. \emph{How to Design Programs}
  663. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  664. define a second function, named \code{R0?}, that determines whether a
  665. value is an $R_0$ program. In general we can expect to write one
  666. recursive function to handle each non-terminal in a grammar.
  667. %
  668. \begin{center}
  669. \begin{minipage}{0.7\textwidth}
  670. \begin{lstlisting}
  671. (define (exp? ast)
  672. (match ast
  673. [(Int n) #t]
  674. [(Prim 'read '()) #t]
  675. [(Prim '- (list e)) (exp? e)]
  676. [(Prim '+ (list e1 e2))
  677. (and (exp? e1) (exp? e2))]
  678. [else #f]))
  679. (define (R0? ast)
  680. (match ast
  681. [(Program '() e) (exp? e)]
  682. [else #f]))
  683. (R0? (Program '() ast1.1)
  684. (R0? (Program '()
  685. (Prim '- (list (Prim 'read '())
  686. (Prim '+ (list (Num 8)))))))
  687. \end{lstlisting}
  688. \end{minipage}
  689. \vrule
  690. \begin{minipage}{0.25\textwidth}
  691. \begin{lstlisting}
  692. #t
  693. #f
  694. \end{lstlisting}
  695. \end{minipage}
  696. \end{center}
  697. You may be tempted to merge the two functions into one, like this:
  698. \begin{center}
  699. \begin{minipage}{0.5\textwidth}
  700. \begin{lstlisting}
  701. (define (R0? ast)
  702. (match ast
  703. [(Int n) #t]
  704. [(Prim 'read '()) #t]
  705. [(Prim '- (list e)) (R0? e)]
  706. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  707. [(Program '() e) (R0? e)]
  708. [else #f]))
  709. \end{lstlisting}
  710. \end{minipage}
  711. \end{center}
  712. %
  713. Sometimes such a trick will save a few lines of code, especially when
  714. it comes to the \code{Program} wrapper. Yet this style is generally
  715. \emph{not} recommended because it can get you into trouble.
  716. %
  717. For example, the above function is subtly wrong:
  718. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  719. will return true, when it should return false.
  720. %% NOTE FIXME - must check for consistency on this issue throughout.
  721. \section{Interpreters}
  722. \label{sec:interp-R0}
  723. The meaning, or semantics, of a program is typically defined in the
  724. specification of the language. For example, the Scheme language is
  725. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  726. defined in its reference manual~\citep{plt-tr}. In this book we use an
  727. interpreter to define the meaning of each language that we consider,
  728. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  729. interpreter that is designated (by some people) as the definition of a
  730. language is called a \emph{definitional interpreter}. We warm up by
  731. creating a definitional interpreter for the $R_0$ language, which
  732. serves as a second example of structural recursion. The
  733. \texttt{interp-R0} function is defined in
  734. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  735. input program followed by a call to the \lstinline{interp-exp} helper
  736. function, which in turn has one match clause per grammar rule for
  737. $R_0$ expressions.
  738. \begin{figure}[tp]
  739. \begin{lstlisting}
  740. (define (interp-exp e)
  741. (match e
  742. [(Int n) n]
  743. [(Prim 'read '())
  744. (define r (read))
  745. (cond [(fixnum? r) r]
  746. [else (error 'interp-R1 "expected an integer" r)])]
  747. [(Prim '- (list e))
  748. (define v (interp-exp e))
  749. (fx- 0 v)]
  750. [(Prim '+ (list e1 e2))
  751. (define v1 (interp-exp e1))
  752. (define v2 (interp-exp e2))
  753. (fx+ v1 v2)]
  754. ))
  755. (define (interp-R0 p)
  756. (match p
  757. [(Program '() e) (interp-exp e)]
  758. ))
  759. \end{lstlisting}
  760. \caption{Interpreter for the $R_0$ language.}
  761. \label{fig:interp-R0}
  762. \end{figure}
  763. Let us consider the result of interpreting a few $R_0$ programs. The
  764. following program adds two integers.
  765. \begin{lstlisting}
  766. (+ 10 32)
  767. \end{lstlisting}
  768. The result is \key{42}. We wrote the above program in concrete syntax,
  769. whereas the parsed abstract syntax is:
  770. \begin{lstlisting}
  771. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  772. \end{lstlisting}
  773. The next example demonstrates that expressions may be nested within
  774. each other, in this case nesting several additions and negations.
  775. \begin{lstlisting}
  776. (+ 10 (- (+ 12 20)))
  777. \end{lstlisting}
  778. What is the result of the above program?
  779. As mentioned previously, the $R_0$ language does not support
  780. arbitrarily-large integers, but only $63$-bit integers, so we
  781. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  782. in Racket.
  783. Suppose
  784. \[
  785. n = 999999999999999999
  786. \]
  787. which indeed fits in $63$-bits. What happens when we run the
  788. following program in our interpreter?
  789. \begin{lstlisting}
  790. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  791. \end{lstlisting}
  792. It produces an error:
  793. \begin{lstlisting}
  794. fx+: result is not a fixnum
  795. \end{lstlisting}
  796. We establish the convention that if running the definitional
  797. interpreter on a program produces an error, then the meaning of that
  798. program is \emph{unspecified}. That means a compiler for the language
  799. is under no obligations regarding that program; it may or may not
  800. produce an executable, and if it does, that executable can do
  801. anything. This convention applies to the languages defined in this
  802. book, as a way to simplify the student's task of implementing them,
  803. but this convention is not applicable to all programming languages.
  804. Moving on to the last feature of the $R_0$ language, the \key{read}
  805. operation prompts the user of the program for an integer. Recall that
  806. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  807. \code{8}. So if we run
  808. \begin{lstlisting}
  809. (interp-R0 ast1.1)
  810. \end{lstlisting}
  811. and if the input is \code{50}, then we get the answer to life, the
  812. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  813. Guide to the Galaxy} by Douglas Adams.}
  814. We include the \key{read} operation in $R_0$ so a clever student
  815. cannot implement a compiler for $R_0$ that simply runs the interpreter
  816. during compilation to obtain the output and then generates the trivial
  817. code to produce the output. (Yes, a clever student did this in the
  818. first instance of this course.)
  819. The job of a compiler is to translate a program in one language into a
  820. program in another language so that the output program behaves the
  821. same way as the input program does according to its definitional
  822. interpreter. This idea is depicted in the following diagram. Suppose
  823. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  824. interpreter for each language. Suppose that the compiler translates
  825. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  826. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  827. respective interpreters with input $i$ should yield the same output
  828. $o$.
  829. \begin{equation} \label{eq:compile-correct}
  830. \begin{tikzpicture}[baseline=(current bounding box.center)]
  831. \node (p1) at (0, 0) {$P_1$};
  832. \node (p2) at (3, 0) {$P_2$};
  833. \node (o) at (3, -2.5) {$o$};
  834. \path[->] (p1) edge [above] node {compile} (p2);
  835. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  836. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  837. \end{tikzpicture}
  838. \end{equation}
  839. In the next section we see our first example of a compiler.
  840. \section{Example Compiler: a Partial Evaluator}
  841. \label{sec:partial-evaluation}
  842. In this section we consider a compiler that translates $R_0$ programs
  843. into $R_0$ programs that may be more efficient, that is, this compiler
  844. is an optimizer. This optimizer eagerly computes the parts of the
  845. program that do not depend on any inputs, a process known as
  846. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  847. following program
  848. \begin{lstlisting}
  849. (+ (read) (- (+ 5 3)))
  850. \end{lstlisting}
  851. our compiler will translate it into the program
  852. \begin{lstlisting}
  853. (+ (read) -8)
  854. \end{lstlisting}
  855. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  856. evaluator for the $R_0$ language. The output of the partial evaluator
  857. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  858. recursion over $\Exp$ is captured in the \code{pe-exp} function
  859. whereas the code for partially evaluating the negation and addition
  860. operations is factored into two separate helper functions:
  861. \code{pe-neg} and \code{pe-add}. The input to these helper
  862. functions is the output of partially evaluating the children.
  863. \begin{figure}[tp]
  864. \begin{lstlisting}
  865. (define (pe-neg r)
  866. (match r
  867. [(Int n) (Int (fx- 0 n))]
  868. [else (Prim '- (list r))]))
  869. (define (pe-add r1 r2)
  870. (match* (r1 r2)
  871. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  872. [(_ _) (Prim '+ (list r1 r2))]))
  873. (define (pe-exp e)
  874. (match e
  875. [(Int n) (Int n)]
  876. [(Prim 'read '()) (Prim 'read '())]
  877. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  878. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  879. ))
  880. (define (pe-R0 p)
  881. (match p
  882. [(Program info e) (Program info (pe-exp e))]
  883. ))
  884. \end{lstlisting}
  885. \caption{A partial evaluator for $R_0$ expressions.}
  886. \label{fig:pe-arith}
  887. \end{figure}
  888. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  889. arguments are integers and if they are, perform the appropriate
  890. arithmetic. Otherwise, they create an AST node for the operation
  891. (either negation or addition).
  892. To gain some confidence that the partial evaluator is correct, we can
  893. test whether it produces programs that get the same result as the
  894. input programs. That is, we can test whether it satisfies Diagram
  895. \eqref{eq:compile-correct}. The following code runs the partial
  896. evaluator on several examples and tests the output program. The
  897. \texttt{parse-program} and \texttt{assert} functions are defined in
  898. Appendix~\ref{appendix:utilities}.\\
  899. \begin{minipage}{1.0\textwidth}
  900. \begin{lstlisting}
  901. (define (test-pe p)
  902. (assert "testing pe-R0"
  903. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  904. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  905. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  906. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  907. \end{lstlisting}
  908. \end{minipage}
  909. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  910. \chapter{Integers and Variables}
  911. \label{ch:int-exp}
  912. This chapter is about compiling the subset of Racket that includes
  913. integer arithmetic and local variable binding, which we name $R_1$, to
  914. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  915. to x86-64 simply as x86. The chapter begins with a description of the
  916. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  917. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  918. discuss only what is needed for compiling $R_1$. We introduce more of
  919. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  920. reflect on their differences and come up with a plan to break down the
  921. translation from $R_1$ to x86 into a handful of steps
  922. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  923. chapter give detailed hints regarding each step
  924. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  925. to give enough hints that the well-prepared reader, together with a
  926. few friends, can implement a compiler from $R_1$ to x86 in a couple
  927. weeks while at the same time leaving room for some fun and creativity.
  928. To give the reader a feeling for the scale of this first compiler, the
  929. instructor solution for the $R_1$ compiler is less than 500 lines of
  930. code.
  931. \section{The $R_1$ Language}
  932. \label{sec:s0}
  933. The $R_1$ language extends the $R_0$ language with variable
  934. definitions. The concrete syntax of the $R_1$ language is defined by
  935. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  936. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  937. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  938. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  939. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  940. \key{Program} struct to mark the top of the program.
  941. %% The $\itm{info}$
  942. %% field of the \key{Program} structure contains an \emph{association
  943. %% list} (a list of key-value pairs) that is used to communicate
  944. %% auxiliary data from one compiler pass the next.
  945. Despite the simplicity of the $R_1$ language, it is rich enough to
  946. exhibit several compilation techniques.
  947. \begin{figure}[tp]
  948. \centering
  949. \fbox{
  950. \begin{minipage}{0.96\textwidth}
  951. \[
  952. \begin{array}{rcl}
  953. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  954. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  955. R_1 &::=& \Exp
  956. \end{array}
  957. \]
  958. \end{minipage}
  959. }
  960. \caption{The concrete syntax of $R_1$.}
  961. \label{fig:r1-concrete-syntax}
  962. \end{figure}
  963. \begin{figure}[tp]
  964. \centering
  965. \fbox{
  966. \begin{minipage}{0.96\textwidth}
  967. \[
  968. \begin{array}{rcl}
  969. \Exp &::=& \INT{\Int} \mid \READ{} \\
  970. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  971. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  972. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  973. \end{array}
  974. \]
  975. \end{minipage}
  976. }
  977. \caption{The abstract syntax of $R_1$.}
  978. \label{fig:r1-syntax}
  979. \end{figure}
  980. Let us dive further into the syntax and semantics of the $R_1$
  981. language. The \key{Let} feature defines a variable for use within its
  982. body and initializes the variable with the value of an expression.
  983. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  984. The concrete syntax for \key{Let} is
  985. \begin{lstlisting}
  986. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  987. \end{lstlisting}
  988. For example, the following program initializes \code{x} to $32$ and then
  989. evaluates the body \code{(+ 10 x)}, producing $42$.
  990. \begin{lstlisting}
  991. (let ([x (+ 12 20)]) (+ 10 x))
  992. \end{lstlisting}
  993. When there are multiple \key{let}'s for the same variable, the closest
  994. enclosing \key{let} is used. That is, variable definitions overshadow
  995. prior definitions. Consider the following program with two \key{let}'s
  996. that define variables named \code{x}. Can you figure out the result?
  997. \begin{lstlisting}
  998. (let ([x 32]) (+ (let ([x 10]) x) x))
  999. \end{lstlisting}
  1000. For the purposes of depicting which variable uses correspond to which
  1001. definitions, the following shows the \code{x}'s annotated with
  1002. subscripts to distinguish them. Double check that your answer for the
  1003. above is the same as your answer for this annotated version of the
  1004. program.
  1005. \begin{lstlisting}
  1006. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1007. \end{lstlisting}
  1008. The initializing expression is always evaluated before the body of the
  1009. \key{let}, so in the following, the \key{read} for \code{x} is
  1010. performed before the \key{read} for \code{y}. Given the input
  1011. $52$ then $10$, the following produces $42$ (not $-42$).
  1012. \begin{lstlisting}
  1013. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1014. \end{lstlisting}
  1015. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1016. \small
  1017. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1018. An \emph{association list} (alist) is a list of key-value pairs.
  1019. For example, we can map people to their ages with an alist.
  1020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1021. (define ages
  1022. '((jane . 25) (sam . 24) (kate . 45)))
  1023. \end{lstlisting}
  1024. The \emph{dictionary} interface is for mapping keys to values.
  1025. Every alist implements this interface. The package
  1026. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1027. provides many functions for working with dictionaries. Here
  1028. are a few of them:
  1029. \begin{description}
  1030. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1031. returns the value associated with the given $\itm{key}$.
  1032. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1033. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1034. but otherwise is the same as $\itm{dict}$.
  1035. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1036. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1037. of keys and values in $\itm{dict}$. For example, the following
  1038. creates a new alist in which the ages are incremented.
  1039. \end{description}
  1040. \vspace{-10pt}
  1041. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1042. (for/list ([(k v) (in-dict ages)])
  1043. (cons k (add1 v)))
  1044. \end{lstlisting}
  1045. \end{tcolorbox}
  1046. \end{wrapfigure}
  1047. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1048. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1049. \key{match} clauses for variables and for \key{let}. For \key{let},
  1050. we need a way to communicate the value of a variable to all the uses
  1051. of a variable. To accomplish this, we maintain a mapping from
  1052. variables to values. Throughout the compiler we often need to map
  1053. variables to information about them. We refer to these mappings as
  1054. \emph{environments}
  1055. \footnote{Another common term for environment in the compiler
  1056. literature is \emph{symbol table}.}. For simplicity, we use an
  1057. association list (alist) to represent the environment. The sidebar to
  1058. the right gives a brief introduction to alists and the
  1059. \code{racket/dict} package. The \code{interp-R1} function takes the
  1060. current environment, \code{env}, as an extra parameter. When the
  1061. interpreter encounters a variable, it finds the corresponding value
  1062. using the \code{dict-ref} function. When the interpreter encounters a
  1063. \key{Let}, it evaluates the initializing expression, extends the
  1064. environment with the result value bound to the variable, using
  1065. \code{dict-set}, then evaluates the body of the \key{Let}.
  1066. \begin{figure}[tp]
  1067. \begin{lstlisting}
  1068. (define (interp-exp env)
  1069. (lambda (e)
  1070. (match e
  1071. [(Int n) n]
  1072. [(Prim 'read '())
  1073. (define r (read))
  1074. (cond [(fixnum? r) r]
  1075. [else (error 'interp-R1 "expected an integer" r)])]
  1076. [(Prim '- (list e))
  1077. (define v ((interp-exp env) e))
  1078. (fx- 0 v)]
  1079. [(Prim '+ (list e1 e2))
  1080. (define v1 ((interp-exp env) e1))
  1081. (define v2 ((interp-exp env) e2))
  1082. (fx+ v1 v2)]
  1083. [(Var x) (dict-ref env x)]
  1084. [(Let x e body)
  1085. (define new-env (dict-set env x ((interp-exp env) e)))
  1086. ((interp-exp new-env) body)]
  1087. )))
  1088. (define (interp-R1 p)
  1089. (match p
  1090. [(Program info e) ((interp-exp '()) e)]
  1091. ))
  1092. \end{lstlisting}
  1093. \caption{Interpreter for the $R_1$ language.}
  1094. \label{fig:interp-R1}
  1095. \end{figure}
  1096. The goal for this chapter is to implement a compiler that translates
  1097. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1098. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1099. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1100. is, they both output the same integer $n$. We depict this correctness
  1101. criteria in the following diagram.
  1102. \[
  1103. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1104. \node (p1) at (0, 0) {$P_1$};
  1105. \node (p2) at (4, 0) {$P_2$};
  1106. \node (o) at (4, -2) {$n$};
  1107. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1108. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1109. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1110. \end{tikzpicture}
  1111. \]
  1112. In the next section we introduce enough of the x86 assembly
  1113. language to compile $R_1$.
  1114. \section{The x86 Assembly Language}
  1115. \label{sec:x86}
  1116. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1117. the x86 assembly language needed for this chapter.
  1118. %
  1119. An x86 program begins with a \code{main} label followed by a sequence
  1120. of instructions. In the grammar, the superscript $+$ is used to
  1121. indicate a sequence of one or more items, e.g., $\Instr^{+}$ is a
  1122. sequence of instructions.
  1123. %
  1124. An x86 program is stored in the computer's memory and the computer has
  1125. a \emph{program counter} that points to the address of the next
  1126. instruction to be executed. For most instructions, once the
  1127. instruction is executed, the program counter is incremented to point
  1128. to the immediately following instruction in memory. Most x86
  1129. instructions take two operands, where each operand is either an
  1130. integer constant (called \emph{immediate value}), a \emph{register},
  1131. or a memory location. A register is a special kind of variable. Each
  1132. one holds a 64-bit value; there are 16 registers in the computer and
  1133. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1134. as a mapping of 64-bit addresses to 64-bit values%
  1135. \footnote{This simple story suffices for describing how sequential
  1136. programs access memory but is not sufficient for multi-threaded
  1137. programs. However, multi-threaded execution is beyond the scope of
  1138. this book.}.
  1139. %
  1140. We use the AT\&T syntax expected by the GNU assembler, which comes
  1141. with the \key{gcc} compiler that we use for compiling assembly code to
  1142. machine code.
  1143. %
  1144. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1145. the x86 instructions used in this book.
  1146. % to do: finish treatment of imulq
  1147. % it's needed for vector's in R6/R7
  1148. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1149. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1150. && \key{r8} \mid \key{r9} \mid \key{r10}
  1151. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1152. \mid \key{r14} \mid \key{r15}}
  1153. \begin{figure}[tp]
  1154. \fbox{
  1155. \begin{minipage}{0.96\textwidth}
  1156. \[
  1157. \begin{array}{lcl}
  1158. \Reg &::=& \allregisters{} \\
  1159. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1160. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1161. \key{subq} \; \Arg\key{,} \Arg \mid
  1162. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1163. && \key{callq} \; \mathit{label} \mid
  1164. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1165. && \itm{label}\key{:}\; \Instr \\
  1166. \Prog &::= & \key{.globl main}\\
  1167. & & \key{main:} \; \Instr^{+}
  1168. \end{array}
  1169. \]
  1170. \end{minipage}
  1171. }
  1172. \caption{The concrete syntax of the $x86_0$ assembly language (AT\&T syntax).}
  1173. \label{fig:x86-0-concrete}
  1174. \end{figure}
  1175. An immediate value is written using the notation \key{\$}$n$ where $n$
  1176. is an integer.
  1177. %
  1178. A register is written with a \key{\%} followed by the register name,
  1179. such as \key{\%rax}.
  1180. %
  1181. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1182. which obtains the address stored in register $r$ and then adds $n$
  1183. bytes to the address. The resulting address is used to either load or
  1184. store to memory depending on whether it occurs as a source or
  1185. destination argument of an instruction.
  1186. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1187. source $s$ and destination $d$, applies the arithmetic operation, then
  1188. writes the result back to the destination $d$.
  1189. %
  1190. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1191. stores the result in $d$.
  1192. %
  1193. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1194. specified by the label and $\key{retq}$ returns from a procedure to
  1195. its caller. We discuss procedure calls in more detail later in this
  1196. chapter and in Chapter~\ref{ch:functions}. The
  1197. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1198. the address of the instruction after the specified label.
  1199. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1200. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1201. \key{main} procedure is externally visible, which is necessary so
  1202. that the operating system can call it. The label \key{main:}
  1203. indicates the beginning of the \key{main} procedure which is where
  1204. the operating system starts executing this program. The instruction
  1205. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1206. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1207. $10$ in \key{rax} and puts the result, $42$, back into
  1208. \key{rax}.
  1209. %
  1210. The last instruction, \key{retq}, finishes the \key{main} function by
  1211. returning the integer in \key{rax} to the operating system. The
  1212. operating system interprets this integer as the program's exit
  1213. code. By convention, an exit code of 0 indicates that a program
  1214. completed successfully, and all other exit codes indicate various
  1215. errors. Nevertheless, we return the result of the program as the exit
  1216. code.
  1217. %\begin{wrapfigure}{r}{2.25in}
  1218. \begin{figure}[tbp]
  1219. \begin{lstlisting}
  1220. .globl main
  1221. main:
  1222. movq $10, %rax
  1223. addq $32, %rax
  1224. retq
  1225. \end{lstlisting}
  1226. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1227. \label{fig:p0-x86}
  1228. %\end{wrapfigure}
  1229. \end{figure}
  1230. Unfortunately, x86 varies in a couple ways depending on what operating
  1231. system it is assembled in. The code examples shown here are correct on
  1232. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1233. labels like \key{main} must be prefixed with an underscore, as in
  1234. \key{\_main}.
  1235. We exhibit the use of memory for storing intermediate results in the
  1236. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1237. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1238. memory called the \emph{procedure call stack} (or \emph{stack} for
  1239. short). The stack consists of a separate \emph{frame} for each
  1240. procedure call. The memory layout for an individual frame is shown in
  1241. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1242. \emph{stack pointer} and points to the item at the top of the
  1243. stack. The stack grows downward in memory, so we increase the size of
  1244. the stack by subtracting from the stack pointer. In the context of a
  1245. procedure call, the \emph{return address} is the next instruction
  1246. after the call instruction on the caller side. During a function call,
  1247. the return address is pushed onto the stack. The register \key{rbp}
  1248. is the \emph{base pointer} and is used to access variables associated
  1249. with the current procedure call. The base pointer of the caller is
  1250. pushed onto the stack after the return address. We number the
  1251. variables from $1$ to $n$. Variable $1$ is stored at address
  1252. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1253. \begin{figure}[tbp]
  1254. \begin{lstlisting}
  1255. start:
  1256. movq $10, -8(%rbp)
  1257. negq -8(%rbp)
  1258. movq -8(%rbp), %rax
  1259. addq $52, %rax
  1260. jmp conclusion
  1261. .globl main
  1262. main:
  1263. pushq %rbp
  1264. movq %rsp, %rbp
  1265. subq $16, %rsp
  1266. jmp start
  1267. conclusion:
  1268. addq $16, %rsp
  1269. popq %rbp
  1270. retq
  1271. \end{lstlisting}
  1272. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1273. \label{fig:p1-x86}
  1274. \end{figure}
  1275. \begin{figure}[tbp]
  1276. \centering
  1277. \begin{tabular}{|r|l|} \hline
  1278. Position & Contents \\ \hline
  1279. 8(\key{\%rbp}) & return address \\
  1280. 0(\key{\%rbp}) & old \key{rbp} \\
  1281. -8(\key{\%rbp}) & variable $1$ \\
  1282. -16(\key{\%rbp}) & variable $2$ \\
  1283. \ldots & \ldots \\
  1284. 0(\key{\%rsp}) & variable $n$\\ \hline
  1285. \end{tabular}
  1286. \caption{Memory layout of a frame.}
  1287. \label{fig:frame}
  1288. \end{figure}
  1289. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1290. control is transfered from the operating system to the \code{main}
  1291. function. The operating system issues a \code{callq main} instruction
  1292. which pushes its return address on the stack and then jumps to
  1293. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1294. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1295. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1296. alignment (because the \code{callq} pushed the return address). The
  1297. first three instructions are the typical \emph{prelude} for a
  1298. procedure. The instruction \code{pushq \%rbp} saves the base pointer
  1299. for the caller onto the stack and subtracts $8$ from the stack
  1300. pointer. At this point the stack pointer is back to being 16-byte
  1301. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1302. base pointer so that it points the location of the old base
  1303. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1304. pointer down to make enough room for storing variables. This program
  1305. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1306. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1307. we are ready to make calls to other functions. The last instruction of
  1308. the prelude is \code{jmp start}, which transfers control to the
  1309. instructions that were generated from the Racket expression \code{(+
  1310. 10 32)}.
  1311. The four instructions under the label \code{start} carry out the work
  1312. of computing \code{(+ 52 (- 10)))}. The first instruction
  1313. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1314. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1315. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1316. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1317. \code{rax}, at which point \code{rax} contains $42$.
  1318. The three instructions under the label \code{conclusion} are the
  1319. typical \emph{conclusion} of a procedure. The first two instructions
  1320. are necessary to get the state of the machine back to where it was at
  1321. the beginning of the procedure. The instruction \key{addq \$16,
  1322. \%rsp} moves the stack pointer back to point at the old base
  1323. pointer. The amount added here needs to match the amount that was
  1324. subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1325. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1326. pointer. The last instruction, \key{retq}, jumps back to the
  1327. procedure that called this one and adds 8 to the stack pointer, which
  1328. returns the stack pointer to where it was prior to the procedure call.
  1329. The compiler needs a convenient representation for manipulating x86
  1330. programs, so we define an abstract syntax for x86 in
  1331. Figure~\ref{fig:x86-0-ast}. We refer to this language as $x86_0$ with
  1332. a subscript $0$ because later we introduce extended versions of this
  1333. assembly language. The main difference compared to the concrete syntax
  1334. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow labeled
  1335. instructions to appear anywhere, but instead organizes instructions
  1336. into groups called \emph{blocks} and associates a label with every
  1337. block, which is why the \key{CFG} struct (for control-flow graph)
  1338. includes an alist mapping labels to blocks. The reason for this
  1339. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1340. introduce conditional branching. The \code{Block} structure includes
  1341. an $\itm{info}$ field that is not needed for this chapter, but will
  1342. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1343. the $\itm{info}$ field should just contain an empty list.
  1344. \begin{figure}[tp]
  1345. \fbox{
  1346. \begin{minipage}{0.96\textwidth}
  1347. \small
  1348. \[
  1349. \begin{array}{lcl}
  1350. \Reg &::=& \allregisters{} \\
  1351. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1352. \mid \DEREF{\Reg}{\Int} \\
  1353. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1354. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1355. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1356. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1357. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1358. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1359. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1360. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1361. \end{array}
  1362. \]
  1363. \end{minipage}
  1364. }
  1365. \caption{The abstract syntax of $x86_0$ assembly.}
  1366. \label{fig:x86-0-ast}
  1367. \end{figure}
  1368. \section{Planning the trip to x86 via the $C_0$ language}
  1369. \label{sec:plan-s0-x86}
  1370. To compile one language to another it helps to focus on the
  1371. differences between the two languages because the compiler will need
  1372. to bridge those differences. What are the differences between $R_1$
  1373. and x86 assembly? Here are some of the most important ones:
  1374. \begin{enumerate}
  1375. \item[(a)] x86 arithmetic instructions typically have two arguments
  1376. and update the second argument in place. In contrast, $R_1$
  1377. arithmetic operations take two arguments and produce a new value.
  1378. An x86 instruction may have at most one memory-accessing argument.
  1379. Furthermore, some instructions place special restrictions on their
  1380. arguments.
  1381. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1382. whereas x86 instructions restrict their arguments to be integers
  1383. constants, registers, and memory locations.
  1384. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1385. sequence of instructions and jumps to labeled positions, whereas in
  1386. $R_1$ the order of evaluation is a left-to-right depth-first
  1387. traversal of the abstract syntax tree.
  1388. \item[(d)] An $R_1$ program can have any number of variables whereas
  1389. x86 has 16 registers and the procedure calls stack.
  1390. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1391. same name. The registers and memory locations of x86 all have unique
  1392. names or addresses.
  1393. \end{enumerate}
  1394. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1395. the problem into several steps, dealing with the above differences one
  1396. at a time. Each of these steps is called a \emph{pass} of the
  1397. compiler.
  1398. %
  1399. This terminology comes from each step traverses (i.e. passes over) the
  1400. AST of the program.
  1401. %
  1402. We begin by sketching how we might implement each pass, and give them
  1403. names. We then figure out an ordering of the passes and the
  1404. input/output language for each pass. The very first pass has $R_1$ as
  1405. its input language and the last pass has x86 as its output
  1406. language. In between we can choose whichever language is most
  1407. convenient for expressing the output of each pass, whether that be
  1408. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1409. Finally, to implement each pass we write one recursive function per
  1410. non-terminal in the grammar of the input language of the pass.
  1411. \begin{description}
  1412. \item[Pass \key{select-instructions}] To handle the difference between
  1413. $R_1$ operations and x86 instructions we convert each $R_1$
  1414. operation to a short sequence of instructions that accomplishes the
  1415. same task.
  1416. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1417. subexpression (i.e. operator and operand, and hence the name
  1418. \key{opera*}) is an \emph{atomic} expression (a variable or
  1419. integer), we introduce temporary variables to hold the results
  1420. of subexpressions.
  1421. \item[Pass \key{explicate-control}] To make the execution order of the
  1422. program explicit, we convert from the abstract syntax tree
  1423. representation into a \emph{control-flow graph} in which each node
  1424. contains a sequence of statements and the edges between nodes say
  1425. where to go at the end of the sequence.
  1426. \item[Pass \key{assign-homes}] To handle the difference between the
  1427. variables in $R_1$ versus the registers and stack locations in x86,
  1428. we assignment of each variable to a register or stack location.
  1429. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1430. by renaming every variable to a unique name, so that shadowing no
  1431. longer occurs.
  1432. \end{description}
  1433. The next question is: in what order should we apply these passes? This
  1434. question can be challenging because it is difficult to know ahead of
  1435. time which orders will be better (easier to implement, produce more
  1436. efficient code, etc.) so oftentimes trial-and-error is
  1437. involved. Nevertheless, we can try to plan ahead and make educated
  1438. choices regarding the ordering.
  1439. Let us consider the ordering of \key{uniquify} and
  1440. \key{remove-complex-opera*}. The assignment of subexpressions to
  1441. temporary variables involves introducing new variables and moving
  1442. subexpressions, which might change the shadowing of variables and
  1443. inadvertently change the behavior of the program. But if we apply
  1444. \key{uniquify} first, this will not be an issue. Of course, this means
  1445. that in \key{remove-complex-opera*}, we need to ensure that the
  1446. temporary variables that it creates are unique.
  1447. What should be the ordering of \key{explicate-control} with respect to
  1448. \key{uniquify}? The \key{uniquify} pass should come first because
  1449. \key{explicate-control} changes all the \key{let}-bound variables to
  1450. become local variables whose scope is the entire program, which would
  1451. confuse variables with the same name.
  1452. %
  1453. Likewise, we place \key{explicate-control} after
  1454. \key{remove-complex-opera*} because \key{explicate-control} removes
  1455. the \key{let} form, but it is convenient to use \key{let} in the
  1456. output of \key{remove-complex-opera*}.
  1457. %
  1458. Regarding \key{assign-homes}, it is helpful to place
  1459. \key{explicate-control} first because \key{explicate-control} changes
  1460. \key{let}-bound variables into program-scope variables. This means
  1461. that the \key{assign-homes} pass can read off the variables from the
  1462. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1463. entire program in search of \key{let}-bound variables.
  1464. Last, we need to decide on the ordering of \key{select-instructions}
  1465. and \key{assign-homes}. These two passes are intertwined, creating a
  1466. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1467. have already determined which instructions will be used, because x86
  1468. instructions have restrictions about which of their arguments can be
  1469. registers versus stack locations. One might want to give preferential
  1470. treatment to variables that occur in register-argument positions. On
  1471. the other hand, it may turn out to be impossible to make sure that all
  1472. such variables are assigned to registers, and then one must redo the
  1473. selection of instructions. Some compilers handle this problem by
  1474. iteratively repeating these two passes until a good solution is found.
  1475. We shall use a simpler approach in which \key{select-instructions}
  1476. comes first, followed by the \key{assign-homes}, then a third
  1477. pass named \key{patch-instructions} that uses a reserved register to
  1478. patch-up outstanding problems regarding instructions with too many
  1479. memory accesses. The disadvantage of this approach is some programs
  1480. may not execute as efficiently as they would if we used the iterative
  1481. approach and used all of the registers for variables.
  1482. \begin{figure}[tbp]
  1483. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1484. \node (R1) at (0,2) {\large $R_1$};
  1485. \node (R1-2) at (3,2) {\large $R_1$};
  1486. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1487. %\node (C0-1) at (6,0) {\large $C_0$};
  1488. \node (C0-2) at (3,0) {\large $C_0$};
  1489. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1490. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1491. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1492. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1493. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1494. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1495. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1496. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1497. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1498. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1499. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1500. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1501. \end{tikzpicture}
  1502. \caption{Overview of the passes for compiling $R_1$. }
  1503. \label{fig:R1-passes}
  1504. \end{figure}
  1505. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1506. passes in the form of a graph. Each pass is an edge and the
  1507. input/output language of each pass is a node in the graph. The output
  1508. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1509. are still in the $R_1$ language, but the output of the pass
  1510. \key{explicate-control} is in a different language $C_0$ that is
  1511. designed to make the order of evaluation explicit in its syntax, which
  1512. we introduce in the next section. The \key{select-instruction} pass
  1513. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1514. \key{patch-instructions} passes input and output variants of x86
  1515. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1516. \key{print-x86}, which converts from the abstract syntax of
  1517. $\text{x86}_0$ to the concrete syntax of x86.
  1518. In the next sections we discuss the $C_0$ language and the
  1519. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1520. remainder of this chapter gives hints regarding the implementation of
  1521. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1522. \subsection{The $C_0$ Intermediate Language}
  1523. The output of \key{explicate-control} is similar to the $C$
  1524. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1525. categories for expressions and statements, so we name it $C_0$. The
  1526. concrete syntax for $C_0$ is defined in
  1527. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1528. is defined in Figure~\ref{fig:c0-syntax}.
  1529. %
  1530. The $C_0$ language supports the same operators as $R_1$ but the
  1531. arguments of operators are restricted to atomic expressions (variables
  1532. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1533. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1534. executed in sequence using the \key{Seq} form. A sequence of
  1535. statements always ends with \key{Return}, a guarantee that is baked
  1536. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1537. this non-terminal comes from the term \emph{tail position}, which
  1538. refers to an expression that is the last one to execute within a
  1539. function. (A expression in tail position may contain subexpressions,
  1540. and those may or may not be in tail position depending on the kind of
  1541. expression.)
  1542. A $C_0$ program consists of a control-flow graph (represented as an
  1543. alist mapping labels to tails). This is more general than
  1544. necessary for the present chapter, as we do not yet need to introduce
  1545. \key{goto} for jumping to labels, but it saves us from having to
  1546. change the syntax of the program construct in
  1547. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1548. \key{start}, and the whole program is its tail.
  1549. %
  1550. The $\itm{info}$ field of the \key{Program} form, after the
  1551. \key{explicate-control} pass, contains a mapping from the symbol
  1552. \key{locals} to a list of variables, that is, a list of all the
  1553. variables used in the program. At the start of the program, these
  1554. variables are uninitialized; they become initialized on their first
  1555. assignment.
  1556. \begin{figure}[tbp]
  1557. \fbox{
  1558. \begin{minipage}{0.96\textwidth}
  1559. \[
  1560. \begin{array}{lcl}
  1561. \Atm &::=& \Int \mid \Var \\
  1562. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1563. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1564. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1565. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1566. \end{array}
  1567. \]
  1568. \end{minipage}
  1569. }
  1570. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1571. \label{fig:c0-concrete-syntax}
  1572. \end{figure}
  1573. \begin{figure}[tbp]
  1574. \fbox{
  1575. \begin{minipage}{0.96\textwidth}
  1576. \[
  1577. \begin{array}{lcl}
  1578. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1579. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1580. &\mid& \ADD{\Atm}{\Atm}\\
  1581. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1582. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1583. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1584. \end{array}
  1585. \]
  1586. \end{minipage}
  1587. }
  1588. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1589. \label{fig:c0-syntax}
  1590. \end{figure}
  1591. %% The \key{select-instructions} pass is optimistic in the sense that it
  1592. %% treats variables as if they were all mapped to registers. The
  1593. %% \key{select-instructions} pass generates a program that consists of
  1594. %% x86 instructions but that still uses variables, so it is an
  1595. %% intermediate language that is technically different than x86, which
  1596. %% explains the asterisks in the diagram above.
  1597. %% In this Chapter we shall take the easy road to implementing
  1598. %% \key{assign-homes} and simply map all variables to stack locations.
  1599. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1600. %% smarter approach in which we make a best-effort to map variables to
  1601. %% registers, resorting to the stack only when necessary.
  1602. %% Once variables have been assigned to their homes, we can finalize the
  1603. %% instruction selection by dealing with an idiosyncrasy of x86
  1604. %% assembly. Many x86 instructions have two arguments but only one of the
  1605. %% arguments may be a memory reference (and the stack is a part of
  1606. %% memory). Because some variables may get mapped to stack locations,
  1607. %% some of our generated instructions may violate this restriction. The
  1608. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1609. %% replacing every violating instruction with a short sequence of
  1610. %% instructions that use the \key{rax} register. Once we have implemented
  1611. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1612. %% need to patch instructions will be relatively rare.
  1613. \subsection{The dialects of x86}
  1614. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1615. the pass \key{select-instructions}. It extends $x86_0$ with an
  1616. unbounded number of program-scope variables and has looser rules
  1617. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1618. output of \key{print-x86}, is the concrete syntax for x86.
  1619. \section{Uniquify Variables}
  1620. \label{sec:uniquify-s0}
  1621. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1622. programs in which every \key{let} uses a unique variable name. For
  1623. example, the \code{uniquify} pass should translate the program on the
  1624. left into the program on the right. \\
  1625. \begin{tabular}{lll}
  1626. \begin{minipage}{0.4\textwidth}
  1627. \begin{lstlisting}
  1628. (let ([x 32])
  1629. (+ (let ([x 10]) x) x))
  1630. \end{lstlisting}
  1631. \end{minipage}
  1632. &
  1633. $\Rightarrow$
  1634. &
  1635. \begin{minipage}{0.4\textwidth}
  1636. \begin{lstlisting}
  1637. (let ([x.1 32])
  1638. (+ (let ([x.2 10]) x.2) x.1))
  1639. \end{lstlisting}
  1640. \end{minipage}
  1641. \end{tabular} \\
  1642. %
  1643. The following is another example translation, this time of a program
  1644. with a \key{let} nested inside the initializing expression of another
  1645. \key{let}.\\
  1646. \begin{tabular}{lll}
  1647. \begin{minipage}{0.4\textwidth}
  1648. \begin{lstlisting}
  1649. (let ([x (let ([x 4])
  1650. (+ x 1))])
  1651. (+ x 2))
  1652. \end{lstlisting}
  1653. \end{minipage}
  1654. &
  1655. $\Rightarrow$
  1656. &
  1657. \begin{minipage}{0.4\textwidth}
  1658. \begin{lstlisting}
  1659. (let ([x.2 (let ([x.1 4])
  1660. (+ x.1 1))])
  1661. (+ x.2 2))
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. \end{tabular}
  1665. We recommend implementing \code{uniquify} by creating a function named
  1666. \code{uniquify-exp} that is structurally recursive function and mostly
  1667. just copies the input program. However, when encountering a \key{let},
  1668. it should generate a unique name for the variable (the Racket function
  1669. \code{gensym} is handy for this) and associate the old name with the
  1670. new unique name in an alist. The \code{uniquify-exp}
  1671. function will need to access this alist when it gets to a
  1672. variable reference, so we add another parameter to \code{uniquify-exp}
  1673. for the alist.
  1674. The skeleton of the \code{uniquify-exp} function is shown in
  1675. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1676. convenient to partially apply it to a symbol table and then apply it
  1677. to different expressions, as in the last clause for primitive
  1678. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1679. is useful for applying a function to each element of a list to produce
  1680. a new list.
  1681. \begin{exercise}
  1682. \normalfont % I don't like the italics for exercises. -Jeremy
  1683. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1684. implement the clauses for variables and for the \key{let} form.
  1685. \end{exercise}
  1686. \begin{figure}[tbp]
  1687. \begin{lstlisting}
  1688. (define (uniquify-exp symtab)
  1689. (lambda (e)
  1690. (match e
  1691. [(Var x) ___]
  1692. [(Int n) (Int n)]
  1693. [(Let x e body) ___]
  1694. [(Prim op es)
  1695. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1696. )))
  1697. (define (uniquify p)
  1698. (match p
  1699. [(Program info e)
  1700. (Program info ((uniquify-exp '()) e))]
  1701. )))
  1702. \end{lstlisting}
  1703. \caption{Skeleton for the \key{uniquify} pass.}
  1704. \label{fig:uniquify-s0}
  1705. \end{figure}
  1706. \begin{exercise}
  1707. \normalfont % I don't like the italics for exercises. -Jeremy
  1708. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1709. and checking whether the output programs produce the same result as
  1710. the input programs. The $R_1$ programs should be designed to test the
  1711. most interesting parts of the \key{uniquify} pass, that is, the
  1712. programs should include \key{let} forms, variables, and variables
  1713. that overshadow each other. The five programs should be in a
  1714. subdirectory named \key{tests} and they should have the same file name
  1715. except for a different integer at the end of the name, followed by the
  1716. ending \key{.rkt}. Use the \key{interp-tests} function
  1717. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1718. your \key{uniquify} pass on the example programs. See the
  1719. \key{run-tests.rkt} script in the student support code for an example
  1720. of how to use \key{interp-tests}.
  1721. \end{exercise}
  1722. \section{Remove Complex Operands}
  1723. \label{sec:remove-complex-opera-r1}
  1724. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1725. $R_1$ programs in which the arguments of operations are atomic
  1726. expressions. Put another way, this pass removes complex operands,
  1727. such as the expression \code{(- 10)} in the program below. This is
  1728. accomplished by introducing a new \key{let}-bound variable, binding
  1729. the complex operand to the new variable, and then using the new
  1730. variable in place of the complex operand, as shown in the output of
  1731. \code{remove-complex-opera*} on the right.\\
  1732. \begin{tabular}{lll}
  1733. \begin{minipage}{0.4\textwidth}
  1734. % s0_19.rkt
  1735. \begin{lstlisting}
  1736. (+ 52 (- 10))
  1737. \end{lstlisting}
  1738. \end{minipage}
  1739. &
  1740. $\Rightarrow$
  1741. &
  1742. \begin{minipage}{0.4\textwidth}
  1743. \begin{lstlisting}
  1744. (let ([tmp.1 (- 10)])
  1745. (+ 52 tmp.1))
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. \end{tabular}
  1749. \begin{figure}[tp]
  1750. \centering
  1751. \fbox{
  1752. \begin{minipage}{0.96\textwidth}
  1753. \[
  1754. \begin{array}{rcl}
  1755. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1756. \Exp &::=& \Atm \mid \READ{} \\
  1757. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1758. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1759. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1760. \end{array}
  1761. \]
  1762. \end{minipage}
  1763. }
  1764. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1765. \label{fig:r1-anf-syntax}
  1766. \end{figure}
  1767. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1768. this pass, language $R_1^{\dagger}$. The main difference is that
  1769. operator arguments are required to be atomic expressions. In the
  1770. literature this is called \emph{administrative normal form}, or ANF
  1771. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1772. We recommend implementing this pass with two mutually recursive
  1773. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1774. \code{rco-atom} to subexpressions that are required to be atomic and
  1775. to apply \code{rco-exp} to subexpressions that can be atomic or
  1776. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1777. $R_1$ expression as input. The \code{rco-exp} function returns an
  1778. expression. The \code{rco-atom} function returns two things: an
  1779. atomic expression and alist mapping temporary variables to complex
  1780. subexpressions. You can return multiple things from a function using
  1781. Racket's \key{values} form and you can receive multiple things from a
  1782. function call using the \key{define-values} form. If you are not
  1783. familiar with these features, review the Racket documentation. Also,
  1784. the \key{for/lists} form is useful for applying a function to each
  1785. element of a list, in the case where the function returns multiple
  1786. values.
  1787. The following shows the output of \code{rco-atom} on the expression
  1788. \code{(- 10)} (using concrete syntax to be concise).
  1789. \begin{tabular}{lll}
  1790. \begin{minipage}{0.4\textwidth}
  1791. \begin{lstlisting}
  1792. (- 10)
  1793. \end{lstlisting}
  1794. \end{minipage}
  1795. &
  1796. $\Rightarrow$
  1797. &
  1798. \begin{minipage}{0.4\textwidth}
  1799. \begin{lstlisting}
  1800. tmp.1
  1801. ((tmp.1 . (- 10)))
  1802. \end{lstlisting}
  1803. \end{minipage}
  1804. \end{tabular}
  1805. Take special care of programs such as the next one that \key{let}-bind
  1806. variables with integers or other variables. You should leave them
  1807. unchanged, as shown in to the program on the right \\
  1808. \begin{tabular}{lll}
  1809. \begin{minipage}{0.4\textwidth}
  1810. % s0_20.rkt
  1811. \begin{lstlisting}
  1812. (let ([a 42])
  1813. (let ([b a])
  1814. b))
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. &
  1818. $\Rightarrow$
  1819. &
  1820. \begin{minipage}{0.4\textwidth}
  1821. \begin{lstlisting}
  1822. (let ([a 42])
  1823. (let ([b a])
  1824. b))
  1825. \end{lstlisting}
  1826. \end{minipage}
  1827. \end{tabular} \\
  1828. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1829. produce the following output.\\
  1830. \begin{minipage}{0.4\textwidth}
  1831. \begin{lstlisting}
  1832. (let ([tmp.1 42])
  1833. (let ([a tmp.1])
  1834. (let ([tmp.2 a])
  1835. (let ([b tmp.2])
  1836. b))))
  1837. \end{lstlisting}
  1838. \end{minipage}
  1839. \begin{exercise}
  1840. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1841. it on all of the example programs that you created to test the
  1842. \key{uniquify} pass and create three new example programs that are
  1843. designed to exercise the interesting code in the
  1844. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1845. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1846. your passes on the example programs.
  1847. \end{exercise}
  1848. \section{Explicate Control}
  1849. \label{sec:explicate-control-r1}
  1850. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1851. programs that make the order of execution explicit in their
  1852. syntax. For now this amounts to flattening \key{let} constructs into a
  1853. sequence of assignment statements. For example, consider the following
  1854. $R_1$ program.\\
  1855. % s0_11.rkt
  1856. \begin{minipage}{0.96\textwidth}
  1857. \begin{lstlisting}
  1858. (let ([y (let ([x 20])
  1859. (+ x (let ([x 22]) x)))])
  1860. y)
  1861. \end{lstlisting}
  1862. \end{minipage}\\
  1863. %
  1864. The output of the previous pass and of \code{explicate-control} is
  1865. shown below. Recall that the right-hand-side of a \key{let} executes
  1866. before its body, so the order of evaluation for this program is to
  1867. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1868. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1869. output of \code{explicate-control} makes this ordering explicit.\\
  1870. \begin{tabular}{lll}
  1871. \begin{minipage}{0.4\textwidth}
  1872. \begin{lstlisting}
  1873. (let ([y (let ([x.1 20])
  1874. (let ([x.2 22])
  1875. (+ x.1 x.2)))])
  1876. y)
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. &
  1880. $\Rightarrow$
  1881. &
  1882. \begin{minipage}{0.4\textwidth}
  1883. \begin{lstlisting}
  1884. locals: y x.1 x.2
  1885. start:
  1886. x.1 = 20;
  1887. x.2 = 22;
  1888. y = (+ x.1 x.2);
  1889. return y;
  1890. \end{lstlisting}
  1891. \end{minipage}
  1892. \end{tabular}
  1893. We recommend implementing \code{explicate-control} using two mutually
  1894. recursive functions: \code{explicate-tail} and
  1895. \code{explicate-assign}. The first function should be applied to
  1896. expressions in tail position whereas the second should be applied to
  1897. expressions that occur on the right-hand-side of a \key{let}. The
  1898. \code{explicate-tail} function takes an $R_1$ expression as input and
  1899. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1900. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1901. function takes an $R_1$ expression, the variable that it is to be
  1902. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1903. assignment (e.g., the code generated for the body of the \key{let}).
  1904. It returns a $\Tail$ and a list of variables. The top-level
  1905. \code{explicate-control} function should invoke \code{explicate-tail}
  1906. on the body of the \key{program} and then associate the \code{locals}
  1907. symbol with the resulting list of variables in the $\itm{info}$ field,
  1908. as in the above example.
  1909. \section{Select Instructions}
  1910. \label{sec:select-r1}
  1911. In the \code{select-instructions} pass we begin the work of
  1912. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1913. this pass is a variant of x86 that still uses variables, so we add an
  1914. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1915. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1916. \code{select-instructions} in terms of three auxiliary functions, one
  1917. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1918. The cases for $\Atm$ are straightforward, variables stay
  1919. the same and integer constants are changed to immediates:
  1920. $\INT{n}$ changes to $\IMM{n}$.
  1921. Next we consider the cases for $\Stmt$, starting with arithmetic
  1922. operations. For example, in $C_0$ an addition operation can take the
  1923. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1924. need to use the \key{addq} instruction which does an in-place
  1925. update. So we must first move \code{10} to \code{x}. \\
  1926. \begin{tabular}{lll}
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. x = (+ 10 32);
  1930. \end{lstlisting}
  1931. \end{minipage}
  1932. &
  1933. $\Rightarrow$
  1934. &
  1935. \begin{minipage}{0.4\textwidth}
  1936. \begin{lstlisting}
  1937. movq $10, x
  1938. addq $32, x
  1939. \end{lstlisting}
  1940. \end{minipage}
  1941. \end{tabular} \\
  1942. %
  1943. There are cases that require special care to avoid generating
  1944. needlessly complicated code. If one of the arguments of the addition
  1945. is the same as the left-hand side of the assignment, then there is no
  1946. need for the extra move instruction. For example, the following
  1947. assignment statement can be translated into a single \key{addq}
  1948. instruction.\\
  1949. \begin{tabular}{lll}
  1950. \begin{minipage}{0.4\textwidth}
  1951. \begin{lstlisting}
  1952. x = (+ 10 x);
  1953. \end{lstlisting}
  1954. \end{minipage}
  1955. &
  1956. $\Rightarrow$
  1957. &
  1958. \begin{minipage}{0.4\textwidth}
  1959. \begin{lstlisting}
  1960. addq $10, x
  1961. \end{lstlisting}
  1962. \end{minipage}
  1963. \end{tabular} \\
  1964. The \key{read} operation does not have a direct counterpart in x86
  1965. assembly, so we have instead implemented this functionality in the C
  1966. language, with the function \code{read\_int} in the file
  1967. \code{runtime.c}. In general, we refer to all of the functionality in
  1968. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1969. for short. When compiling your generated x86 assembly code, you need
  1970. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1971. using \code{gcc} option \code{-c}) and link it into the
  1972. executable. For our purposes of code generation, all you need to do is
  1973. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1974. (for left-hand side) into a call to the \code{read\_int} function
  1975. followed by a move from \code{rax} to the left-hand side. The move
  1976. from \code{rax} is needed because the return value from
  1977. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1978. \begin{tabular}{lll}
  1979. \begin{minipage}{0.3\textwidth}
  1980. \begin{lstlisting}
  1981. |$\itm{var}$| = (read);
  1982. \end{lstlisting}
  1983. \end{minipage}
  1984. &
  1985. $\Rightarrow$
  1986. &
  1987. \begin{minipage}{0.3\textwidth}
  1988. \begin{lstlisting}
  1989. callq read_int
  1990. movq %rax, |$\itm{var}$|
  1991. \end{lstlisting}
  1992. \end{minipage}
  1993. \end{tabular} \\
  1994. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1995. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1996. assignment to the \key{rax} register followed by a jump to the
  1997. conclusion of the program (so the conclusion needs to be labeled).
  1998. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1999. recursively and append the resulting instructions.
  2000. \begin{exercise}
  2001. \normalfont
  2002. Implement the \key{select-instructions} pass and test it on all of the
  2003. example programs that you created for the previous passes and create
  2004. three new example programs that are designed to exercise all of the
  2005. interesting code in this pass. Use the \key{interp-tests} function
  2006. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2007. your passes on the example programs.
  2008. \end{exercise}
  2009. \section{Assign Homes}
  2010. \label{sec:assign-r1}
  2011. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2012. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2013. Thus, the \key{assign-homes} pass is responsible for placing all of
  2014. the program variables in registers or on the stack. For runtime
  2015. efficiency, it is better to place variables in registers, but as there
  2016. are only 16 registers, some programs must necessarily resort to
  2017. placing some variables on the stack. In this chapter we focus on the
  2018. mechanics of placing variables on the stack. We study an algorithm for
  2019. placing variables in registers in
  2020. Chapter~\ref{ch:register-allocation-r1}.
  2021. Consider again the following $R_1$ program.
  2022. % s0_20.rkt
  2023. \begin{lstlisting}
  2024. (let ([a 42])
  2025. (let ([b a])
  2026. b))
  2027. \end{lstlisting}
  2028. For reference, we repeat the output of \code{select-instructions} on
  2029. the left and show the output of \code{assign-homes} on the right.
  2030. Recall that \key{explicate-control} associated the list of
  2031. variables with the \code{locals} symbol in the program's $\itm{info}$
  2032. field, so \code{assign-homes} has convenient access to the them. In
  2033. this example, we assign variable \code{a} to stack location
  2034. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2035. \begin{tabular}{l}
  2036. \begin{minipage}{0.4\textwidth}
  2037. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2038. locals: a b
  2039. start:
  2040. movq $42, a
  2041. movq a, b
  2042. movq b, %rax
  2043. jmp conclusion
  2044. \end{lstlisting}
  2045. \end{minipage}
  2046. {$\Rightarrow$}
  2047. \begin{minipage}{0.4\textwidth}
  2048. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2049. stack-space: 16
  2050. start:
  2051. movq $42, -8(%rbp)
  2052. movq -8(%rbp), -16(%rbp)
  2053. movq -16(%rbp), %rax
  2054. jmp conclusion
  2055. \end{lstlisting}
  2056. \end{minipage}
  2057. \end{tabular} \\
  2058. In the process of assigning variables to stack locations, it is
  2059. convenient to compute and store the size of the frame (in bytes) in
  2060. the $\itm{info}$ field of the \key{Program} node, with the key
  2061. \code{stack-space}, which will be needed later to generate the
  2062. procedure conclusion. Some operating systems place restrictions on
  2063. the frame size. For example, Mac OS X requires the frame size to be a
  2064. multiple of 16 bytes.
  2065. \begin{exercise}
  2066. \normalfont Implement the \key{assign-homes} pass and test it on all
  2067. of the example programs that you created for the previous passes pass.
  2068. We recommend that \key{assign-homes} take an extra parameter that is a
  2069. mapping of variable names to homes (stack locations for now). Use the
  2070. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2071. \key{utilities.rkt} to test your passes on the example programs.
  2072. \end{exercise}
  2073. \section{Patch Instructions}
  2074. \label{sec:patch-s0}
  2075. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2076. programs to $\text{x86}_0$ programs by making sure that each
  2077. instruction adheres to the restrictions of the x86 assembly language.
  2078. In particular, at most one argument of an instruction may be a memory
  2079. reference.
  2080. We return to the following running example.
  2081. % s0_20.rkt
  2082. \begin{lstlisting}
  2083. (let ([a 42])
  2084. (let ([b a])
  2085. b))
  2086. \end{lstlisting}
  2087. After the \key{assign-homes} pass, the above program has been translated to
  2088. the following. \\
  2089. \begin{minipage}{0.5\textwidth}
  2090. \begin{lstlisting}
  2091. stack-space: 16
  2092. start:
  2093. movq $42, -8(%rbp)
  2094. movq -8(%rbp), -16(%rbp)
  2095. movq -16(%rbp), %rax
  2096. jmp conclusion
  2097. \end{lstlisting}
  2098. \end{minipage}\\
  2099. The second \key{movq} instruction is problematic because both
  2100. arguments are stack locations. We suggest fixing this problem by
  2101. moving from the source location to the register \key{rax} and then
  2102. from \key{rax} to the destination location, as follows.
  2103. \begin{lstlisting}
  2104. movq -8(%rbp), %rax
  2105. movq %rax, -16(%rbp)
  2106. \end{lstlisting}
  2107. \begin{exercise}
  2108. \normalfont
  2109. Implement the \key{patch-instructions} pass and test it on all of the
  2110. example programs that you created for the previous passes and create
  2111. three new example programs that are designed to exercise all of the
  2112. interesting code in this pass. Use the \key{interp-tests} function
  2113. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2114. your passes on the example programs.
  2115. \end{exercise}
  2116. \section{Print x86}
  2117. \label{sec:print-x86}
  2118. The last step of the compiler from $R_1$ to x86 is to convert the
  2119. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2120. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2121. \key{format} and \key{string-append} functions are useful in this
  2122. regard. The main work that this step needs to perform is to create the
  2123. \key{main} function and the standard instructions for its prelude and
  2124. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2125. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2126. variables, so we suggest computing it in the \key{assign-homes} pass
  2127. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2128. of the \key{program} node.
  2129. %% Your compiled code should print the result of the program's execution
  2130. %% by using the \code{print\_int} function provided in
  2131. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2132. %% far, this final result should be stored in the \key{rax} register.
  2133. %% We'll talk more about how to perform function calls with arguments in
  2134. %% general later on, but for now, place the following after the compiled
  2135. %% code for the $R_1$ program but before the conclusion:
  2136. %% \begin{lstlisting}
  2137. %% movq %rax, %rdi
  2138. %% callq print_int
  2139. %% \end{lstlisting}
  2140. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2141. %% stores the first argument to be passed into \key{print\_int}.
  2142. If you want your program to run on Mac OS X, your code needs to
  2143. determine whether or not it is running on a Mac, and prefix
  2144. underscores to labels like \key{main}. You can determine the platform
  2145. with the Racket call \code{(system-type 'os)}, which returns
  2146. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2147. %% In addition to
  2148. %% placing underscores on \key{main}, you need to put them in front of
  2149. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2150. %% \_print\_int}).
  2151. \begin{exercise}
  2152. \normalfont Implement the \key{print-x86} pass and test it on all of
  2153. the example programs that you created for the previous passes. Use the
  2154. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2155. \key{utilities.rkt} to test your complete compiler on the example
  2156. programs. See the \key{run-tests.rkt} script in the student support
  2157. code for an example of how to use \key{compiler-tests}. Also, remember
  2158. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2159. \key{gcc}.
  2160. \end{exercise}
  2161. \section{Challenge: Partial Evaluator for $R_1$}
  2162. \label{sec:pe-R1}
  2163. This section describes optional challenge exercises that involve
  2164. adapting and improving the partial evaluator for $R_0$ that was
  2165. introduced in Section~\ref{sec:partial-evaluation}.
  2166. \begin{exercise}\label{ex:pe-R1}
  2167. \normalfont
  2168. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2169. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2170. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2171. and variables to the $R_0$ language, so you will need to add cases for
  2172. them in the \code{pe-exp} function. Also, note that the \key{program}
  2173. form changes slightly to include an $\itm{info}$ field. Once
  2174. complete, add the partial evaluation pass to the front of your
  2175. compiler and make sure that your compiler still passes all of the
  2176. tests.
  2177. \end{exercise}
  2178. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2179. \begin{exercise}
  2180. \normalfont
  2181. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2182. \code{pe-add} auxiliary functions with functions that know more about
  2183. arithmetic. For example, your partial evaluator should translate
  2184. \begin{lstlisting}
  2185. (+ 1 (+ (read) 1))
  2186. \end{lstlisting}
  2187. into
  2188. \begin{lstlisting}
  2189. (+ 2 (read))
  2190. \end{lstlisting}
  2191. To accomplish this, the \code{pe-exp} function should produce output
  2192. in the form of the $\itm{residual}$ non-terminal of the following
  2193. grammar.
  2194. \[
  2195. \begin{array}{lcl}
  2196. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2197. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2198. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2199. \end{array}
  2200. \]
  2201. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2202. that their inputs are $\itm{residual}$ expressions and they should
  2203. return $\itm{residual}$ expressions. Once the improvements are
  2204. complete, make sure that your compiler still passes all of the tests.
  2205. After all, fast code is useless if it produces incorrect results!
  2206. \end{exercise}
  2207. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2208. \chapter{Register Allocation}
  2209. \label{ch:register-allocation-r1}
  2210. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2211. make our life easier. However, we can improve the performance of the
  2212. generated code if we instead place some variables into registers. The
  2213. CPU can access a register in a single cycle, whereas accessing the
  2214. stack takes many cycles if the relevant data is in cache or many more
  2215. to access main memory if the data is not in cache.
  2216. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2217. serves as a running example. We show the source program and also the
  2218. output of instruction selection. At that point the program is almost
  2219. x86 assembly but not quite; it still contains variables instead of
  2220. stack locations or registers.
  2221. \begin{figure}
  2222. \begin{minipage}{0.45\textwidth}
  2223. Example $R_1$ program:
  2224. % s0_28.rkt
  2225. \begin{lstlisting}
  2226. (let ([v 1])
  2227. (let ([w 42])
  2228. (let ([x (+ v 7)])
  2229. (let ([y x])
  2230. (let ([z (+ x w)])
  2231. (+ z (- y)))))))
  2232. \end{lstlisting}
  2233. \end{minipage}
  2234. \begin{minipage}{0.45\textwidth}
  2235. After instruction selection:
  2236. \begin{lstlisting}
  2237. locals: (v w x y z t)
  2238. start:
  2239. movq $1, v
  2240. movq $42, w
  2241. movq v, x
  2242. addq $7, x
  2243. movq x, y
  2244. movq x, z
  2245. addq w, z
  2246. movq y, t
  2247. negq t
  2248. movq z, %rax
  2249. addq t, %rax
  2250. jmp conclusion
  2251. \end{lstlisting}
  2252. \end{minipage}
  2253. \caption{An example program for register allocation.}
  2254. \label{fig:reg-eg}
  2255. \end{figure}
  2256. The goal of register allocation is to fit as many variables into
  2257. registers as possible. A program sometimes has more variables than
  2258. registers, so we cannot map each variable to a different
  2259. register. Fortunately, it is common for different variables to be
  2260. needed during different periods of time during program execution, and
  2261. in such cases several variables can be mapped to the same register.
  2262. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2263. After the variable \code{x} is moved to \code{z} it is no longer
  2264. needed. Variable \code{y}, on the other hand, is used only after this
  2265. point, so \code{x} and \code{y} could share the same register. The
  2266. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2267. where a variable is needed. Once we have that information, we compute
  2268. which variables are needed at the same time, i.e., which ones
  2269. \emph{interfere} with each other, and represent this relation as an
  2270. undirected graph whose vertices are variables and edges indicate when
  2271. two variables interfere (Section~\ref{sec:build-interference}). We
  2272. then model register allocation as a graph coloring problem, which we
  2273. discuss in Section~\ref{sec:graph-coloring}.
  2274. In the event that we run out of registers despite these efforts, we
  2275. place the remaining variables on the stack, similar to what we did in
  2276. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2277. for assigning a variable to a stack location. The process of spilling
  2278. variables is handled as part of the graph coloring process described
  2279. in \ref{sec:graph-coloring}.
  2280. We make the simplifying assumption that each variable is assigned to
  2281. one location (a register or stack address). A more sophisticated
  2282. approach is to assign a variable to one or more locations in different
  2283. regions of the program. For example, if a variable is used many times
  2284. in short sequence and then only used again after many other
  2285. instructions, it could be more efficient to assign the variable to a
  2286. register during the intial sequence and then move it to the stack for
  2287. the rest of its lifetime. We refer the interested reader to
  2288. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2289. about this approach.
  2290. % discuss prioritizing variables based on how much they are used.
  2291. \section{Registers and Calling Conventions}
  2292. \label{sec:calling-conventions}
  2293. As we perform register allocation, we need to be aware of the
  2294. conventions that govern the way in which registers interact with
  2295. function calls, such as calls to the \code{read\_int} function in our
  2296. generated code and even the call that the operating system makes to
  2297. execute our \code{main} function. The convention for x86 is that the
  2298. caller is responsible for freeing up some registers, the
  2299. \emph{caller-saved registers}, prior to the function call, and the
  2300. callee is responsible for preserving the values in some other
  2301. registers, the \emph{callee-saved registers}. The caller-saved
  2302. registers are
  2303. \begin{lstlisting}
  2304. rax rcx rdx rsi rdi r8 r9 r10 r11
  2305. \end{lstlisting}
  2306. while the callee-saved registers are
  2307. \begin{lstlisting}
  2308. rsp rbp rbx r12 r13 r14 r15
  2309. \end{lstlisting}
  2310. We can think about this caller/callee convention from two points of
  2311. view, the caller view and the callee view:
  2312. \begin{itemize}
  2313. \item The caller should assume that all the caller-saved registers get
  2314. overwritten with arbitrary values by the callee. On the other hand,
  2315. the caller can safely assume that all the callee-saved registers
  2316. contain the same values after the call that they did before the
  2317. call.
  2318. \item The callee can freely use any of the caller-saved registers.
  2319. However, if the callee wants to use a callee-saved register, the
  2320. callee must arrange to put the original value back in the register
  2321. prior to returning to the caller, which is usually accomplished by
  2322. saving the value to the stack in the prelude of the function and
  2323. restoring the value in the conclusion of the function.
  2324. \end{itemize}
  2325. The next question is how these calling conventions impact register
  2326. allocation. Consider the $R_1$ program in
  2327. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2328. example from the caller point of view and then from the callee point
  2329. of view.
  2330. The program makes two calls to the \code{read} function. Also, the
  2331. variable \code{x} is in-use during the second call to \code{read}, so
  2332. we need to make sure that the value in \code{x} does not get
  2333. accidentally wiped out by the call to \code{read}. One obvious
  2334. approach is to save all the values in caller-saved registers to the
  2335. stack prior to each function call, and restore them after each
  2336. call. That way, if the register allocator chooses to assign \code{x}
  2337. to a caller-saved register, its value will be preserved accross the
  2338. call to \code{read}. However, the disadvantage of this approach is
  2339. that saving and restoring to the stack is relatively slow. If \code{x}
  2340. is not used many times, it may be better to assign \code{x} to a stack
  2341. location in the first place. Or better yet, if we can arrange for
  2342. \code{x} to be placed in a callee-saved register, then it won't need
  2343. to be saved and restored during function calls.
  2344. The approach that we recommend is to treat variables differently
  2345. depending on whether they are in-use during a function call. If a
  2346. variable is in-use during a function call, then we never assign it to
  2347. a caller-saved register: we either assign it to a callee-saved
  2348. register or we spill it to the stack. If a variable is not in-use
  2349. during any function call, then we try the following alternatives in
  2350. order 1) look for an available caller-saved register (to leave room
  2351. for other variables in the callee-saved register), 2) look for a
  2352. callee-saved register, and 3) spill the variable to the stack.
  2353. It is straightforward to implement this approach in a graph coloring
  2354. register allocator. First, we know which variables are in-use during
  2355. every function call because we compute that information for every
  2356. instruciton (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2357. build the interference graph (Section~\ref{sec:build-interference}),
  2358. we can place an edge between each of these variables and the
  2359. caller-saved registers in the interference graph. This will prevent
  2360. the graph coloring algorithm from assigning those variables to
  2361. caller-saved registers.
  2362. Returning to the example in
  2363. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2364. generated x86 code on the right-hand side, focusing on the
  2365. \code{start} block. Notice that variable \code{x} is assigned to
  2366. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2367. place during the second call to \code{read\_int}. Next, notice that
  2368. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2369. because there are no function calls in the remainder of the block.
  2370. Next we analyze the example from the callee point of view, focusing on
  2371. the prelude and conclusion of the \code{main} function. As usual the
  2372. prelude begins with saving the \code{rbp} register to the stack and
  2373. setting the \code{rbp} to the current stack pointer. We now know why
  2374. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2375. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2376. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2377. variable (\code{x}). There are several more callee-saved register that
  2378. are not saved in the prelude because they were not assigned to
  2379. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2380. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2381. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2382. from the stack with a \code{popq} instruction.
  2383. \begin{figure}[tp]
  2384. \begin{minipage}{0.45\textwidth}
  2385. Example $R_1$ program:
  2386. %s0_14.rkt
  2387. \begin{lstlisting}
  2388. (let ([x (read)])
  2389. (let ([y (read)])
  2390. (+ (+ x y) 42)))
  2391. \end{lstlisting}
  2392. \end{minipage}
  2393. \begin{minipage}{0.45\textwidth}
  2394. Generated x86 assembly:
  2395. \begin{lstlisting}
  2396. start:
  2397. callq read_int
  2398. movq %rax, %rbx
  2399. callq read_int
  2400. movq %rax, %rcx
  2401. addq %rcx, %rbx
  2402. movq %rbx, %rax
  2403. addq $42, %rax
  2404. jmp _conclusion
  2405. .globl main
  2406. main:
  2407. pushq %rbp
  2408. movq %rsp, %rbp
  2409. pushq %rbx
  2410. subq $8, %rsp
  2411. jmp start
  2412. conclusion:
  2413. addq $8, %rsp
  2414. popq %rbx
  2415. popq %rbp
  2416. retq
  2417. \end{lstlisting}
  2418. \end{minipage}
  2419. \caption{Example with function calls.}
  2420. \label{fig:example-calling-conventions}
  2421. \end{figure}
  2422. \section{Liveness Analysis}
  2423. \label{sec:liveness-analysis-r1}
  2424. A variable is \emph{live} if the variable is used at some later point
  2425. in the program and there is not an intervening assignment to the
  2426. variable.
  2427. %
  2428. To understand the latter condition, consider the following code
  2429. fragment in which there are two writes to \code{b}. Are \code{a} and
  2430. \code{b} both live at the same time?
  2431. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2432. movq $5, a
  2433. movq $30, b
  2434. movq a, c
  2435. movq $10, b
  2436. addq b, c
  2437. \end{lstlisting}
  2438. The answer is no because the integer \code{30} written to \code{b} on
  2439. line 2 is never used. The variable \code{b} is read on line 5 and
  2440. there is an intervening write to \code{b} on line 4, so the read on
  2441. line 5 receives the value written on line 4, not line 2.
  2442. The live variables can be computed by traversing the instruction
  2443. sequence back to front (i.e., backwards in execution order). Let
  2444. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2445. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2446. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2447. variables before instruction $I_k$. The live variables after an
  2448. instruction are always the same as the live variables before the next
  2449. instruction.
  2450. \begin{equation} \label{eq:live-after-before-next}
  2451. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2452. \end{equation}
  2453. To start things off, there are no live variables after the last
  2454. instruction, so
  2455. \begin{equation}\label{eq:live-last-empty}
  2456. L_{\mathsf{after}}(n) = \emptyset
  2457. \end{equation}
  2458. We then apply the following rule repeatedly, traversing the
  2459. instruction sequence back to front.
  2460. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2461. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2462. \end{equation}
  2463. where $W(k)$ are the variables written to by instruction $I_k$ and
  2464. $R(k)$ are the variables read by instruction $I_k$.
  2465. Let us walk through the above example, applying these formulas
  2466. starting with the instruction on line 5. We collect the answers in the
  2467. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2468. instruction is $\emptyset$ because it is the last instruction
  2469. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2470. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2471. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2472. is
  2473. \[
  2474. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2475. \]
  2476. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2477. the live-before set from line 5 to be the live-after set for this
  2478. instruction (formula~\ref{eq:live-after-before-next}).
  2479. \[
  2480. L_{\mathsf{after}}(4) = \{ b, c \}
  2481. \]
  2482. This move instruction writes to $b$ and does not read from any
  2483. variables, so we have the following live-before set
  2484. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2485. \[
  2486. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2487. \]
  2488. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2489. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2490. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2491. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2492. variable that is not live and does not read from a variable.
  2493. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2494. because it writes to variable $a$.
  2495. \begin{center}
  2496. \begin{minipage}{0.45\textwidth}
  2497. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2498. movq $5, a
  2499. movq $30, b
  2500. movq a, c
  2501. movq $10, b
  2502. addq b, c
  2503. \end{lstlisting}
  2504. \end{minipage}
  2505. \vrule\hspace{10pt}
  2506. \begin{minipage}{0.45\textwidth}
  2507. \begin{align*}
  2508. L_{\mathsf{before}}(1)= \emptyset,
  2509. L_{\mathsf{after}}(1)= \{a\}\\
  2510. L_{\mathsf{before}}(2)= \{a\},
  2511. L_{\mathsf{after}}(2)= \{a\}\\
  2512. L_{\mathsf{before}}(3)= \{a\},
  2513. L_{\mathsf{after}}(2)= \{c\}\\
  2514. L_{\mathsf{before}}(4)= \{c\},
  2515. L_{\mathsf{after}}(4)= \{b,c\}\\
  2516. L_{\mathsf{before}}(5)= \{b,c\},
  2517. L_{\mathsf{after}}(5)= \emptyset
  2518. \end{align*}
  2519. \end{minipage}
  2520. \end{center}
  2521. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2522. for the running example program, with the live-before and live-after
  2523. sets shown between each instruction to make the figure easy to read.
  2524. \begin{figure}[tp]
  2525. \hspace{20pt}
  2526. \begin{minipage}{0.45\textwidth}
  2527. \begin{lstlisting}
  2528. |$\{\}$|
  2529. movq $1, v
  2530. |$\{v\}$|
  2531. movq $42, w
  2532. |$\{v,w\}$|
  2533. movq v, x
  2534. |$\{w,x\}$|
  2535. addq $7, x
  2536. |$\{w,x\}$|
  2537. movq x, y
  2538. |$\{w,x,y\}$|
  2539. movq x, z
  2540. |$\{w,y,z\}$|
  2541. addq w, z
  2542. |$\{y,z\}$|
  2543. movq y, t
  2544. |$\{t,z\}$|
  2545. negq t
  2546. |$\{t,z\}$|
  2547. movq z, %rax
  2548. |$\{t\}$|
  2549. addq t, %rax
  2550. |$\{\}$|
  2551. jmp conclusion
  2552. |$\{\}$|
  2553. \end{lstlisting}
  2554. \end{minipage}
  2555. \caption{The running example annotated with live-after sets.}
  2556. \label{fig:live-eg}
  2557. \end{figure}
  2558. \begin{exercise}\normalfont
  2559. Implement the compiler pass named \code{uncover-live} that computes
  2560. the live-after sets. We recommend storing the live-after sets (a list
  2561. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2562. structure.
  2563. %
  2564. We recommend organizing your code to use a helper function that takes
  2565. a list of instructions and an initial live-after set (typically empty)
  2566. and returns the list of live-after sets.
  2567. %
  2568. We recommend creating helper functions to 1) compute the set of
  2569. variables that appear in an argument (of an instruction), 2) compute
  2570. the variables read by an instruction which corresponds to the $R$
  2571. function discussed above, and 3) the variables written by an
  2572. instruction which corresponds to $W$.
  2573. \end{exercise}
  2574. \section{Building the Interference Graph}
  2575. \label{sec:build-interference}
  2576. Based on the liveness analysis, we know where each variable is needed.
  2577. However, during register allocation, we need to answer questions of
  2578. the specific form: are variables $u$ and $v$ live at the same time?
  2579. (And therefore cannot be assigned to the same register.) To make this
  2580. question easier to answer, we create an explicit data structure, an
  2581. \emph{interference graph}. An interference graph is an undirected
  2582. graph that has an edge between two variables if they are live at the
  2583. same time, that is, if they interfere with each other.
  2584. The most obvious way to compute the interference graph is to look at
  2585. the set of live variables between each statement in the program and
  2586. add an edge to the graph for every pair of variables in the same set.
  2587. This approach is less than ideal for two reasons. First, it can be
  2588. expensive because it takes $O(n^2)$ time to look at every pair in a
  2589. set of $n$ live variables. Second, there is a special case in which
  2590. two variables that are live at the same time do not actually interfere
  2591. with each other: when they both contain the same value because we have
  2592. assigned one to the other.
  2593. A better way to compute the interference graph is to focus on the
  2594. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2595. instruction to overwrite something in a live variable. So for each
  2596. instruction, we create an edge between the variable being written to
  2597. and all the \emph{other} live variables. (One should not create self
  2598. edges.) For a \key{callq} instruction, think of all caller-saved
  2599. registers as being written to, so an edge must be added between every
  2600. live variable and every caller-saved register. For \key{movq}, we deal
  2601. with the above-mentioned special case by not adding an edge between a
  2602. live variable $v$ and destination $d$ if $v$ matches the source of the
  2603. move. So we have the following three rules.
  2604. \begin{enumerate}
  2605. \item If instruction $I_k$ is an arithmetic instruction such as
  2606. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2607. L_{\mathsf{after}}(k)$ unless $v = d$.
  2608. \item If instruction $I_k$ is of the form \key{callq}
  2609. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2610. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2611. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2612. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2613. d$ or $v = s$.
  2614. \end{enumerate}
  2615. Working from the top to bottom of Figure~\ref{fig:live-eg}, apply the
  2616. above rules to each instruction. We highlight a few of the
  2617. instructions and then refer the reader to
  2618. Figure~\ref{fig:interference-results} all the interference results.
  2619. The first instruction is \lstinline{movq $1, v}, so rule 3 applies,
  2620. and the live-after set is $\{v\}$. We do not add any interference
  2621. edges because the one live variable $v$ is also the destination of
  2622. this instruction.
  2623. %
  2624. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2625. again, and the live-after set is $\{v,w\}$. So the target $w$ of
  2626. \key{movq} interferes with $v$.
  2627. %
  2628. Next we skip forward to the instruction \lstinline{movq x, y}.
  2629. \begin{figure}[tbp]
  2630. \begin{quote}
  2631. \begin{tabular}{ll}
  2632. \lstinline{movq $1, v}& no interference by rule 3,\\
  2633. \lstinline{movq $42, w}& $w$ interferes with $v$ by rule 3,\\
  2634. \lstinline{movq v, x}& $x$ interferes with $w$ by rule 3,\\
  2635. \lstinline{addq $7, x}& $x$ interferes with $w$ by rule 1,\\
  2636. \lstinline{movq x, y}& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2637. \lstinline{movq x, z}& $z$ interferes with $w$ and $y$ by rule 3,\\
  2638. \lstinline{addq w, z}& $z$ interferes with $y$ by rule 1, \\
  2639. \lstinline{movq y, t}& $t$ interferes with $z$ by rule 3, \\
  2640. \lstinline{negq t}& $t$ interferes with $z$ by rule 1, \\
  2641. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2642. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2643. \lstinline{jmp conclusion}& no interference.
  2644. \end{tabular}
  2645. \end{quote}
  2646. \caption{Interference results for the running example.}
  2647. \label{fig:interference-results}
  2648. \end{figure}
  2649. The resulting interference graph is shown in
  2650. Figure~\ref{fig:interfere}.
  2651. \begin{figure}[tbp]
  2652. \large
  2653. \[
  2654. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2655. \node (t1) at (0,2) {$t$};
  2656. \node (z) at (3,2) {$z$};
  2657. \node (x) at (6,2) {$x$};
  2658. \node (y) at (3,0) {$y$};
  2659. \node (w) at (6,0) {$w$};
  2660. \node (v) at (9,0) {$v$};
  2661. \draw (t1) to (z);
  2662. \draw (z) to (y);
  2663. \draw (z) to (w);
  2664. \draw (x) to (w);
  2665. \draw (y) to (w);
  2666. \draw (v) to (w);
  2667. \end{tikzpicture}
  2668. \]
  2669. \caption{The interference graph of the example program.}
  2670. \label{fig:interfere}
  2671. \end{figure}
  2672. %% Our next concern is to choose a data structure for representing the
  2673. %% interference graph. There are many choices for how to represent a
  2674. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2675. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2676. %% data structure is to study the algorithm that uses the data structure,
  2677. %% determine what operations need to be performed, and then choose the
  2678. %% data structure that provide the most efficient implementations of
  2679. %% those operations. Often times the choice of data structure can have an
  2680. %% effect on the time complexity of the algorithm, as it does here. If
  2681. %% you skim the next section, you will see that the register allocation
  2682. %% algorithm needs to ask the graph for all of its vertices and, given a
  2683. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2684. %% correct choice of graph representation is that of an adjacency
  2685. %% list. There are helper functions in \code{utilities.rkt} for
  2686. %% representing graphs using the adjacency list representation:
  2687. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2688. %% (Appendix~\ref{appendix:utilities}).
  2689. %% %
  2690. %% \margincomment{\footnotesize To do: change to use the
  2691. %% Racket graph library. \\ --Jeremy}
  2692. %% %
  2693. %% In particular, those functions use a hash table to map each vertex to
  2694. %% the set of adjacent vertices, and the sets are represented using
  2695. %% Racket's \key{set}, which is also a hash table.
  2696. \begin{exercise}\normalfont
  2697. Implement the compiler pass named \code{build-interference} according
  2698. to the algorithm suggested above. We recommend using the Racket
  2699. \code{graph} package to create and inspect the interference graph.
  2700. The output graph of this pass should be stored in the $\itm{info}$
  2701. field of the program, under the key \code{conflicts}.
  2702. \end{exercise}
  2703. \section{Graph Coloring via Sudoku}
  2704. \label{sec:graph-coloring}
  2705. We come to the main event, mapping variables to registers (or to stack
  2706. locations in the event that we run out of registers). We need to make
  2707. sure that two variables do not get mapped to the same register if the
  2708. two variables interfere with each other. Thinking about the
  2709. interference graph, this means that adjacent vertices must be mapped
  2710. to different registers. If we think of registers as colors, the
  2711. register allocation problem becomes the widely-studied graph coloring
  2712. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2713. The reader may be more familiar with the graph coloring problem than he
  2714. or she realizes; the popular game of Sudoku is an instance of the
  2715. graph coloring problem. The following describes how to build a graph
  2716. out of an initial Sudoku board.
  2717. \begin{itemize}
  2718. \item There is one vertex in the graph for each Sudoku square.
  2719. \item There is an edge between two vertices if the corresponding squares
  2720. are in the same row, in the same column, or if the squares are in
  2721. the same $3\times 3$ region.
  2722. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2723. \item Based on the initial assignment of numbers to squares in the
  2724. Sudoku board, assign the corresponding colors to the corresponding
  2725. vertices in the graph.
  2726. \end{itemize}
  2727. If you can color the remaining vertices in the graph with the nine
  2728. colors, then you have also solved the corresponding game of Sudoku.
  2729. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2730. the corresponding graph with colored vertices. We map the Sudoku
  2731. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2732. sampling of the vertices (the colored ones) because showing edges for
  2733. all of the vertices would make the graph unreadable.
  2734. \begin{figure}[tbp]
  2735. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2736. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2737. \caption{A Sudoku game board and the corresponding colored graph.}
  2738. \label{fig:sudoku-graph}
  2739. \end{figure}
  2740. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2741. strategies to come up with an algorithm for allocating registers. For
  2742. example, one of the basic techniques for Sudoku is called Pencil
  2743. Marks. The idea is to use a process of elimination to determine what
  2744. numbers no longer make sense for a square and write down those
  2745. numbers in the square (writing very small). For example, if the number
  2746. $1$ is assigned to a square, then by process of elimination, you can
  2747. write the pencil mark $1$ in all the squares in the same row, column,
  2748. and region. Many Sudoku computer games provide automatic support for
  2749. Pencil Marks.
  2750. %
  2751. The Pencil Marks technique corresponds to the notion of
  2752. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2753. vertex, in Sudoku terms, is the set of numbers that are no longer
  2754. available. In graph terminology, we have the following definition:
  2755. \begin{equation*}
  2756. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2757. \text{ and } \mathrm{color}(v) = c \}
  2758. \end{equation*}
  2759. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2760. edge with $u$.
  2761. Using the Pencil Marks technique leads to a simple strategy for
  2762. filling in numbers: if there is a square with only one possible number
  2763. left, then choose that number! But what if there are no squares with
  2764. only one possibility left? One brute-force approach is to try them
  2765. all: choose the first and if it ultimately leads to a solution,
  2766. great. If not, backtrack and choose the next possibility. One good
  2767. thing about Pencil Marks is that it reduces the degree of branching in
  2768. the search tree. Nevertheless, backtracking can be horribly time
  2769. consuming. One way to reduce the amount of backtracking is to use the
  2770. most-constrained-first heuristic. That is, when choosing a square,
  2771. always choose one with the fewest possibilities left (the vertex with
  2772. the highest saturation). The idea is that choosing highly constrained
  2773. squares earlier rather than later is better because later on there may
  2774. not be any possibilities left for those squares.
  2775. However, register allocation is easier than Sudoku because the
  2776. register allocator can map variables to stack locations when the
  2777. registers run out. Thus, it makes sense to drop backtracking in favor
  2778. of greedy search, that is, make the best choice at the time and keep
  2779. going. We still wish to minimize the number of colors needed, so
  2780. keeping the most-constrained-first heuristic is a good idea.
  2781. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2782. algorithm for register allocation based on saturation and the
  2783. most-constrained-first heuristic. It is roughly equivalent to the
  2784. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2785. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2786. Sudoku, the algorithm represents colors with integers. The first $k$
  2787. colors corresponding to the $k$ registers in a given machine and the
  2788. rest of the integers corresponding to stack locations.
  2789. \begin{figure}[btp]
  2790. \centering
  2791. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2792. Algorithm: DSATUR
  2793. Input: a graph |$G$|
  2794. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2795. |$W \gets \mathit{vertices}(G)$|
  2796. while |$W \neq \emptyset$| do
  2797. pick a vertex |$u$| from |$W$| with the highest saturation,
  2798. breaking ties randomly
  2799. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2800. |$\mathrm{color}[u] \gets c$|
  2801. |$W \gets W - \{u\}$|
  2802. \end{lstlisting}
  2803. \caption{The saturation-based greedy graph coloring algorithm.}
  2804. \label{fig:satur-algo}
  2805. \end{figure}
  2806. With this algorithm in hand, let us return to the running example and
  2807. consider how to color the interference graph in
  2808. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2809. colored and they are unsaturated, so we annotate each of them with a
  2810. dash for their color and an empty set for the saturation.
  2811. \[
  2812. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2813. \node (t1) at (0,2) {$t:-,\{\}$};
  2814. \node (z) at (3,2) {$z:-,\{\}$};
  2815. \node (x) at (6,2) {$x:-,\{\}$};
  2816. \node (y) at (3,0) {$y:-,\{\}$};
  2817. \node (w) at (6,0) {$w:-,\{\}$};
  2818. \node (v) at (9,0) {$v:-,\{\}$};
  2819. \draw (t1) to (z);
  2820. \draw (z) to (y);
  2821. \draw (z) to (w);
  2822. \draw (x) to (w);
  2823. \draw (y) to (w);
  2824. \draw (v) to (w);
  2825. \end{tikzpicture}
  2826. \]
  2827. The algorithm says to select a maximally saturated vertex and color it
  2828. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2829. $t$. We then mark color $0$ as no longer available for $z$ because
  2830. it interferes with $t$.
  2831. \[
  2832. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2833. \node (t1) at (0,2) {$t:0,\{\}$};
  2834. \node (z) at (3,2) {$z:-,\{0\}$};
  2835. \node (x) at (6,2) {$x:-,\{\}$};
  2836. \node (y) at (3,0) {$y:-,\{\}$};
  2837. \node (w) at (6,0) {$w:-,\{\}$};
  2838. \node (v) at (9,0) {$v:-,\{\}$};
  2839. \draw (t1) to (z);
  2840. \draw (z) to (y);
  2841. \draw (z) to (w);
  2842. \draw (x) to (w);
  2843. \draw (y) to (w);
  2844. \draw (v) to (w);
  2845. \end{tikzpicture}
  2846. \]
  2847. Next we repeat the process, selecting another maximally saturated
  2848. vertex, which is $z$, and color it with the first available number,
  2849. which is $1$.
  2850. \[
  2851. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2852. \node (t1) at (0,2) {$t:0,\{1\}$};
  2853. \node (z) at (3,2) {$z:1,\{0\}$};
  2854. \node (x) at (6,2) {$x:-,\{\}$};
  2855. \node (y) at (3,0) {$y:-,\{1\}$};
  2856. \node (w) at (6,0) {$w:-,\{1\}$};
  2857. \node (v) at (9,0) {$v:-,\{\}$};
  2858. \draw (t1) to (z);
  2859. \draw (z) to (y);
  2860. \draw (z) to (w);
  2861. \draw (x) to (w);
  2862. \draw (y) to (w);
  2863. \draw (v) to (w);
  2864. \end{tikzpicture}
  2865. \]
  2866. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2867. first available color, which is $0$.
  2868. \[
  2869. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2870. \node (t1) at (0,2) {$t:0,\{1\}$};
  2871. \node (z) at (3,2) {$z:1,\{0\}$};
  2872. \node (x) at (6,2) {$x:-,\{0\}$};
  2873. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2874. \node (w) at (6,0) {$w:0,\{1\}$};
  2875. \node (v) at (9,0) {$v:-,\{0\}$};
  2876. \draw (t1) to (z);
  2877. \draw (z) to (y);
  2878. \draw (z) to (w);
  2879. \draw (x) to (w);
  2880. \draw (y) to (w);
  2881. \draw (v) to (w);
  2882. \end{tikzpicture}
  2883. \]
  2884. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2885. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  2886. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  2887. are $0$ and $1$ respectively.
  2888. \[
  2889. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2890. \node (t1) at (0,2) {$t:0,\{1\}$};
  2891. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2892. \node (x) at (6,2) {$x:-,\{0\}$};
  2893. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2894. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2895. \node (v) at (9,0) {$v:-,\{0\}$};
  2896. \draw (t1) to (z);
  2897. \draw (z) to (y);
  2898. \draw (z) to (w);
  2899. \draw (x) to (w);
  2900. \draw (y) to (w);
  2901. \draw (v) to (w);
  2902. \end{tikzpicture}
  2903. \]
  2904. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  2905. \[
  2906. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2907. \node (t1) at (0,2) {$t:0,\{1\}$};
  2908. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2909. \node (x) at (6,2) {$x:-,\{0\}$};
  2910. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2911. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2912. \node (v) at (9,0) {$v:1,\{0\}$};
  2913. \draw (t1) to (z);
  2914. \draw (z) to (y);
  2915. \draw (z) to (w);
  2916. \draw (x) to (w);
  2917. \draw (y) to (w);
  2918. \draw (v) to (w);
  2919. \end{tikzpicture}
  2920. \]
  2921. In the last step of the algorithm, we color $x$ with $1$.
  2922. \[
  2923. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2924. \node (t1) at (0,2) {$t:0,\{1,\}$};
  2925. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2926. \node (x) at (6,2) {$x:1,\{0\}$};
  2927. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2928. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2929. \node (v) at (9,0) {$v:1,\{0\}$};
  2930. \draw (t1) to (z);
  2931. \draw (z) to (y);
  2932. \draw (z) to (w);
  2933. \draw (x) to (w);
  2934. \draw (y) to (w);
  2935. \draw (v) to (w);
  2936. \end{tikzpicture}
  2937. \]
  2938. With the coloring complete, we finalize the assignment of variables to
  2939. registers and stack locations. Recall that if we have $k$ registers,
  2940. we map the first $k$ colors to registers and the rest to stack
  2941. locations. Suppose for the moment that we have just one register to
  2942. use for register allocation, \key{rcx}. Then the following is the
  2943. mapping of colors to registers and stack allocations.
  2944. \[
  2945. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2946. \]
  2947. Putting this mapping together with the above coloring of the
  2948. variables, we arrive at the following assignment of variables to
  2949. registers and stack locations.
  2950. \begin{gather*}
  2951. \{ v \mapsto \key{\%rcx}, \,
  2952. w \mapsto \key{\%rcx}, \,
  2953. x \mapsto \key{-8(\%rbp)}, \\
  2954. y \mapsto \key{-16(\%rbp)}, \,
  2955. z\mapsto \key{-8(\%rbp)},
  2956. t\mapsto \key{\%rcx} \}
  2957. \end{gather*}
  2958. Applying this assignment to our running example, on the left, yields
  2959. the program on the right.
  2960. % why frame size of 32? -JGS
  2961. \begin{center}
  2962. \begin{minipage}{0.3\textwidth}
  2963. \begin{lstlisting}
  2964. movq $1, v
  2965. movq $42, w
  2966. movq v, x
  2967. addq $7, x
  2968. movq x, y
  2969. movq x, z
  2970. addq w, z
  2971. movq y, t
  2972. negq t
  2973. movq z, %rax
  2974. addq t, %rax
  2975. jmp conclusion
  2976. \end{lstlisting}
  2977. \end{minipage}
  2978. $\Rightarrow\qquad$
  2979. \begin{minipage}{0.45\textwidth}
  2980. \begin{lstlisting}
  2981. movq $1, %rcx
  2982. movq $42, %rcx
  2983. movq %rcx, -8(%rbp)
  2984. addq $7, -8(%rbp)
  2985. movq -8(%rbp), -16(%rbp)
  2986. movq -8(%rbp), -8(%rbp)
  2987. addq %rcx, -8(%rbp)
  2988. movq -16(%rbp), %rcx
  2989. negq %rcx
  2990. movq -8(%rbp), %rax
  2991. addq %rcx, %rax
  2992. jmp conclusion
  2993. \end{lstlisting}
  2994. \end{minipage}
  2995. \end{center}
  2996. The resulting program is almost an x86 program. The remaining step is
  2997. the patch instructions pass. In this example, the trivial move of
  2998. \code{-8(\%rbp)} to itself is deleted and the addition of
  2999. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3000. \code{rax} as follows.
  3001. \begin{lstlisting}
  3002. movq -8(%rbp), %rax
  3003. addq %rax, -16(%rbp)
  3004. \end{lstlisting}
  3005. An overview of all of the passes involved in register allocation is
  3006. shown in Figure~\ref{fig:reg-alloc-passes}.
  3007. \begin{figure}[tbp]
  3008. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3009. \node (R1) at (0,2) {\large $R_1$};
  3010. \node (R1-2) at (3,2) {\large $R_1$};
  3011. \node (R1-3) at (6,2) {\large $R_1$};
  3012. \node (C0-1) at (6,0) {\large $C_0$};
  3013. \node (C0-2) at (3,0) {\large $C_0$};
  3014. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3015. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3016. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3017. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3018. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3019. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3020. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3021. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3022. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3023. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  3024. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3025. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3026. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3027. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3028. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3029. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  3030. \end{tikzpicture}
  3031. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3032. \label{fig:reg-alloc-passes}
  3033. \end{figure}
  3034. \begin{exercise}\normalfont
  3035. Implement the pass \code{allocate-registers}, which should come
  3036. after the \code{build-interference} pass. The three new passes,
  3037. \code{uncover-live}, \code{build-interference}, and
  3038. \code{allocate-registers} replace the \code{assign-homes} pass of
  3039. Section~\ref{sec:assign-r1}.
  3040. We recommend that you create a helper function named
  3041. \code{color-graph} that takes an interference graph and a list of
  3042. all the variables in the program. This function should return a
  3043. mapping of variables to their colors (represented as natural
  3044. numbers). By creating this helper function, you will be able to
  3045. reuse it in Chapter~\ref{ch:functions} when you add support for
  3046. functions.
  3047. Once you have obtained the coloring from \code{color-graph}, you can
  3048. assign the variables to registers or stack locations and then reuse
  3049. code from the \code{assign-homes} pass from
  3050. Section~\ref{sec:assign-r1} to replace the variables with their
  3051. assigned location.
  3052. Test your updated compiler by creating new example programs that
  3053. exercise all of the register allocation algorithm, such as forcing
  3054. variables to be spilled to the stack.
  3055. \end{exercise}
  3056. \section{Print x86 and Conventions for Registers}
  3057. \label{sec:print-x86-reg-alloc}
  3058. Recall that the \code{print-x86} pass generates the prelude and
  3059. conclusion instructions for the \code{main} function.
  3060. %
  3061. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3062. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3063. reason for this is that our \code{main} function must adhere to the
  3064. x86 calling conventions that we described in
  3065. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3066. allocator assigned variables to other callee-saved registers
  3067. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3068. saved to the stack in the prelude and restored in the conclusion. The
  3069. simplest approach is to save and restore all of the callee-saved
  3070. registers. The more efficient approach is to keep track of which
  3071. callee-saved registers were used and only save and restore
  3072. them. Either way, make sure to take this use of stack space into
  3073. account when you are calculating the size of the frame and adjusting
  3074. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3075. frame needs to be a multiple of 16 bytes!
  3076. \section{Challenge: Move Biasing}
  3077. \label{sec:move-biasing}
  3078. This section describes an optional enhancement to register allocation
  3079. for those students who are looking for an extra challenge or who have
  3080. a deeper interest in register allocation.
  3081. We return to the running example, but we remove the supposition that
  3082. we only have one register to use. So we have the following mapping of
  3083. color numbers to registers.
  3084. \[
  3085. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3086. \]
  3087. Using the same assignment of variables to color numbers that was
  3088. produced by the register allocator described in the last section, we
  3089. get the following program.
  3090. \begin{minipage}{0.3\textwidth}
  3091. \begin{lstlisting}
  3092. movq $1, v
  3093. movq $42, w
  3094. movq v, x
  3095. addq $7, x
  3096. movq x, y
  3097. movq x, z
  3098. addq w, z
  3099. movq y, t
  3100. negq t
  3101. movq z, %rax
  3102. addq t, %rax
  3103. jmp conclusion
  3104. \end{lstlisting}
  3105. \end{minipage}
  3106. $\Rightarrow\qquad$
  3107. \begin{minipage}{0.45\textwidth}
  3108. \begin{lstlisting}
  3109. movq $1, %rcx
  3110. movq $42, $rbx
  3111. movq %rcx, %rcx
  3112. addq $7, %rcx
  3113. movq %rcx, %rdx
  3114. movq %rcx, %rcx
  3115. addq %rbx, %rcx
  3116. movq %rdx, %rbx
  3117. negq %rbx
  3118. movq %rcx, %rax
  3119. addq %rbx, %rax
  3120. jmp conclusion
  3121. \end{lstlisting}
  3122. \end{minipage}
  3123. In the above output code there are two \key{movq} instructions that
  3124. can be removed because their source and target are the same. However,
  3125. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3126. register, we could instead remove three \key{movq} instructions. We
  3127. can accomplish this by taking into account which variables appear in
  3128. \key{movq} instructions with which other variables.
  3129. We say that two variables $p$ and $q$ are \emph{move related} if they
  3130. participate together in a \key{movq} instruction, that is, \key{movq}
  3131. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3132. allocator chooses a color for a variable, it should prefer a color
  3133. that has already been used for a move-related variable (assuming that
  3134. they do not interfere). Of course, this preference should not override
  3135. the preference for registers over stack locations. This preference
  3136. should be used as a tie breaker when choosing between registers or
  3137. when choosing between stack locations.
  3138. We recommend representing the move relationships in a graph, similar
  3139. to how we represented interference. The following is the \emph{move
  3140. graph} for our running example.
  3141. \[
  3142. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3143. \node (t) at (0,2) {$t$};
  3144. \node (z) at (3,2) {$z$};
  3145. \node (x) at (6,2) {$x$};
  3146. \node (y) at (3,0) {$y$};
  3147. \node (w) at (6,0) {$w$};
  3148. \node (v) at (9,0) {$v$};
  3149. \draw (v) to (x);
  3150. \draw (x) to (y);
  3151. \draw (x) to (z);
  3152. \draw (y) to (t);
  3153. \end{tikzpicture}
  3154. \]
  3155. Now we replay the graph coloring, pausing to see the coloring of
  3156. $y$. Recall the following configuration. The most saturated vertices
  3157. were $w$ and $y$.
  3158. \[
  3159. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3160. \node (t1) at (0,2) {$t:0,\{1\}$};
  3161. \node (z) at (3,2) {$z:1,\{0\}$};
  3162. \node (x) at (6,2) {$x:-,\{\}$};
  3163. \node (y) at (3,0) {$y:-,\{1\}$};
  3164. \node (w) at (6,0) {$w:-,\{1\}$};
  3165. \node (v) at (9,0) {$v:-,\{\}$};
  3166. \draw (t1) to (z);
  3167. \draw (z) to (y);
  3168. \draw (z) to (w);
  3169. \draw (x) to (w);
  3170. \draw (y) to (w);
  3171. \draw (v) to (w);
  3172. \end{tikzpicture}
  3173. \]
  3174. %
  3175. Last time we chose to color $w$ with $0$. But this time we note that
  3176. $w$ is not move related to any vertex, and $y$ is move related to $t$.
  3177. So we choose to color $y$ the same color, $0$.
  3178. \[
  3179. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3180. \node (t1) at (0,2) {$t:0,\{1\}$};
  3181. \node (z) at (3,2) {$z:1,\{0\}$};
  3182. \node (x) at (6,2) {$x:-,\{\}$};
  3183. \node (y) at (3,0) {$y:0,\{1\}$};
  3184. \node (w) at (6,0) {$w:-,\{0,1\}$};
  3185. \node (v) at (9,0) {$v:-,\{\}$};
  3186. \draw (t1) to (z);
  3187. \draw (z) to (y);
  3188. \draw (z) to (w);
  3189. \draw (x) to (w);
  3190. \draw (y) to (w);
  3191. \draw (v) to (w);
  3192. \end{tikzpicture}
  3193. \]
  3194. Now $w$ is the most saturated, so we color it $2$.
  3195. \[
  3196. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3197. \node (t1) at (0,2) {$t:0,\{1\}$};
  3198. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3199. \node (x) at (6,2) {$x:-,\{2\}$};
  3200. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3201. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3202. \node (v) at (9,0) {$v:-,\{2\}$};
  3203. \draw (t1) to (z);
  3204. \draw (z) to (y);
  3205. \draw (z) to (w);
  3206. \draw (x) to (w);
  3207. \draw (y) to (w);
  3208. \draw (v) to (w);
  3209. \end{tikzpicture}
  3210. \]
  3211. At this point, vertices $x$ and $v$ are most saturated,
  3212. but $x$ is move related to $y$ and $z$, so we color $x$ to $0$
  3213. to match $y$. Finally, we color $v$ to $0$.
  3214. \[
  3215. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3216. \node (t) at (0,2) {$t:0,\{1\}$};
  3217. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3218. \node (x) at (6,2) {$x:0,\{2\}$};
  3219. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3220. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3221. \node (v) at (9,0) {$v:0,\{2\}$};
  3222. \draw (t) to (z);
  3223. \draw (z) to (y);
  3224. \draw (z) to (w);
  3225. \draw (x) to (w);
  3226. \draw (y) to (w);
  3227. \draw (v) to (w);
  3228. \end{tikzpicture}
  3229. \]
  3230. So we have the following assignment of variables to registers.
  3231. \begin{gather*}
  3232. \{ v \mapsto \key{\%rbx}, \,
  3233. w \mapsto \key{\%rdx}, \,
  3234. x \mapsto \key{\%rbx}, \\
  3235. y \mapsto \key{\%rbx}, \,
  3236. z\mapsto \key{\%rcx},
  3237. t\mapsto \key{\%rbx} \}
  3238. \end{gather*}
  3239. We apply this register assignment to the running example, on the left,
  3240. to obtain the code on right.
  3241. \begin{minipage}{0.3\textwidth}
  3242. \begin{lstlisting}
  3243. movq $1, v
  3244. movq $42, w
  3245. movq v, x
  3246. addq $7, x
  3247. movq x, y
  3248. movq x, z
  3249. addq w, z
  3250. movq y, t
  3251. negq t
  3252. movq z, %rax
  3253. addq t, %rax
  3254. jmp conclusion
  3255. \end{lstlisting}
  3256. \end{minipage}
  3257. $\Rightarrow\qquad$
  3258. \begin{minipage}{0.45\textwidth}
  3259. \begin{lstlisting}
  3260. movq $1, %rbx
  3261. movq $42, %rdx
  3262. movq %rbx, %rbx
  3263. addq $7, %rbx
  3264. movq %rbx, %rbx
  3265. movq %rbx, %rcx
  3266. addq %rdx, %rcx
  3267. movq %rbx, %rbx
  3268. negq %rbx
  3269. movq %rcx, %rax
  3270. addq %rbx, %rax
  3271. jmp conclusion
  3272. \end{lstlisting}
  3273. \end{minipage}
  3274. The \code{patch-instructions} then removes the three trivial moves
  3275. from \key{rbx} to \key{rbx} to obtain the following result.
  3276. \begin{minipage}{0.45\textwidth}
  3277. \begin{lstlisting}
  3278. movq $1, %rbx
  3279. movq $42, %rdx
  3280. addq $7, %rbx
  3281. movq %rbx, %rcx
  3282. addq %rdx, %rcx
  3283. negq %rbx
  3284. movq %rcx, %rax
  3285. addq %rbx, %rax
  3286. jmp conclusion
  3287. \end{lstlisting}
  3288. \end{minipage}
  3289. \begin{exercise}\normalfont
  3290. Change your implementation of \code{allocate-registers} to take move
  3291. biasing into account. Make sure that your compiler still passes all of
  3292. the previous tests. Create two new tests that include at least one
  3293. opportunity for move biasing and visually inspect the output x86
  3294. programs to make sure that your move biasing is working properly.
  3295. \end{exercise}
  3296. \margincomment{\footnotesize To do: another neat challenge would be to do
  3297. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3298. \section{Output of the Running Example}
  3299. \label{sec:reg-alloc-output}
  3300. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3301. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3302. and move biasing. To demonstrate both the use of registers and the
  3303. stack, we have limited the register allocator to use just two
  3304. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3305. \code{main} function, we push \code{rbx} onto the stack because it is
  3306. a callee-saved register and it was assigned to variable by the
  3307. register allocator. We substract \code{8} from the \code{rsp} at the
  3308. end of the prelude to reserve space for the one spilled variable.
  3309. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3310. Moving on the the \code{start} block, we see how the registers were
  3311. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3312. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3313. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3314. that the prelude saved the callee-save register \code{rbx} onto the
  3315. stack. The spilled variables must be placed lower on the stack than
  3316. the saved callee-save registers, so in this case \code{w} is placed at
  3317. \code{-16(\%rbp)}.
  3318. In the \code{conclusion}, we undo the work that was done in the
  3319. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3320. spilled variables), then we pop the old values of \code{rbx} and
  3321. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3322. return control to the operating system.
  3323. \begin{figure}[tbp]
  3324. % s0_28.rkt
  3325. % (use-minimal-set-of-registers! #t)
  3326. % and only rbx rcx
  3327. % tmp 0 rbx
  3328. % z 1 rcx
  3329. % y 0 rbx
  3330. % w 2 16(%rbp)
  3331. % v 0 rbx
  3332. % x 0 rbx
  3333. \begin{lstlisting}
  3334. start:
  3335. movq $1, %rbx
  3336. movq $42, -16(%rbp)
  3337. addq $7, %rbx
  3338. movq %rbx, %rcx
  3339. addq -16(%rbp), %rcx
  3340. negq %rbx
  3341. movq %rcx, %rax
  3342. addq %rbx, %rax
  3343. jmp conclusion
  3344. .globl main
  3345. main:
  3346. pushq %rbp
  3347. movq %rsp, %rbp
  3348. pushq %rbx
  3349. subq $8, %rsp
  3350. jmp start
  3351. conclusion:
  3352. addq $8, %rsp
  3353. popq %rbx
  3354. popq %rbp
  3355. retq
  3356. \end{lstlisting}
  3357. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3358. \label{fig:running-example-x86}
  3359. \end{figure}
  3360. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3361. \chapter{Booleans and Control Flow}
  3362. \label{ch:bool-types}
  3363. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3364. integers. In this chapter we add a second kind of value, the Booleans,
  3365. to create the $R_2$ language. The Boolean values \emph{true} and
  3366. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3367. Racket. The $R_2$ language includes several operations that involve
  3368. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3369. conditional \key{if} expression. With the addition of \key{if}
  3370. expressions, programs can have non-trivial control flow which which
  3371. significantly impacts the \code{explicate-control} and the liveness
  3372. analysis for register allocation. Also, because we now have two kinds
  3373. of values, we need to handle programs that apply an operation to the
  3374. wrong kind of value, such as \code{(not 1)}.
  3375. There are two language design options for such situations. One option
  3376. is to signal an error and the other is to provide a wider
  3377. interpretation of the operation. The Racket language uses a mixture of
  3378. these two options, depending on the operation and the kind of
  3379. value. For example, the result of \code{(not 1)} in Racket is
  3380. \code{\#f} because Racket treats non-zero integers as if they were
  3381. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3382. error in Racket stating that \code{car} expects a pair.
  3383. The Typed Racket language makes similar design choices as Racket,
  3384. except much of the error detection happens at compile time instead of
  3385. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3386. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3387. reports a compile-time error because Typed Racket expects the type of
  3388. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3389. For the $R_2$ language we choose to be more like Typed Racket in that
  3390. we shall perform type checking during compilation. In
  3391. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3392. is, how to compile a dynamically typed language like Racket. The
  3393. $R_2$ language is a subset of Typed Racket but by no means includes
  3394. all of Typed Racket. For many operations we take a narrower
  3395. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3396. This chapter is organized as follows. We begin by defining the syntax
  3397. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3398. then introduce the idea of type checking and build a type checker for
  3399. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3400. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3401. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3402. how our compiler passes need to change to accommodate Booleans and
  3403. conditional control flow.
  3404. \section{The $R_2$ Language}
  3405. \label{sec:r2-lang}
  3406. The concrete syntax of the $R_2$ language is defined in
  3407. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3408. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3409. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3410. and the conditional \code{if} expression. Also, we expand the
  3411. operators to include
  3412. \begin{enumerate}
  3413. \item subtraction on integers,
  3414. \item the logical operators \key{and}, \key{or} and \key{not},
  3415. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3416. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3417. comparing integers.
  3418. \end{enumerate}
  3419. \begin{figure}[tp]
  3420. \centering
  3421. \fbox{
  3422. \begin{minipage}{0.96\textwidth}
  3423. \[
  3424. \begin{array}{lcl}
  3425. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3426. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3427. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3428. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3429. &\mid& \itm{bool}
  3430. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3431. \mid (\key{not}\;\Exp) \\
  3432. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3433. R_2 &::=& \Exp
  3434. \end{array}
  3435. \]
  3436. \end{minipage}
  3437. }
  3438. \caption{The concrete syntax of $R_2$, extending $R_1$
  3439. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3440. \label{fig:r2-concrete-syntax}
  3441. \end{figure}
  3442. \begin{figure}[tp]
  3443. \centering
  3444. \fbox{
  3445. \begin{minipage}{0.96\textwidth}
  3446. \[
  3447. \begin{array}{lcl}
  3448. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3449. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3450. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3451. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3452. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3453. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3454. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3455. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3456. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3457. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3458. \end{array}
  3459. \]
  3460. \end{minipage}
  3461. }
  3462. \caption{The abstract syntax of $R_2$.}
  3463. \label{fig:r2-syntax}
  3464. \end{figure}
  3465. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3466. the parts that are the same as the interpreter for $R_1$
  3467. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3468. evaluate to the corresponding Boolean values. The conditional
  3469. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3470. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3471. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3472. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3473. you might expect, but note that the \code{and} operation is
  3474. short-circuiting. That is, given the expression
  3475. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3476. $e_1$ evaluates to \code{\#f}.
  3477. With the addition of the comparison operations, there are quite a few
  3478. primitive operations and the interpreter code for them could become
  3479. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3480. out the different parts of the code for primitive operations into the
  3481. \code{interp-op} function and the similar parts of the code into the
  3482. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3483. do not use \code{interp-op} for the \code{and} operation because of
  3484. the short-circuiting behavior in the order of evaluation of its
  3485. arguments.
  3486. \begin{figure}[tbp]
  3487. \begin{lstlisting}
  3488. (define (interp-op op)
  3489. (match op
  3490. ...
  3491. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3492. ['eq? (lambda (v1 v2)
  3493. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3494. (and (boolean? v1) (boolean? v2)))
  3495. (eq? v1 v2)]))]
  3496. ['< (lambda (v1 v2)
  3497. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3498. ['<= (lambda (v1 v2)
  3499. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3500. ['> (lambda (v1 v2)
  3501. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3502. ['>= (lambda (v1 v2)
  3503. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3504. [else (error 'interp-op "unknown operator")]))
  3505. (define (interp-exp env)
  3506. (lambda (e)
  3507. (define recur (interp-exp env))
  3508. (match e
  3509. ...
  3510. [(Bool b) b]
  3511. [(If cnd thn els)
  3512. (define b (recur cnd))
  3513. (match b
  3514. [#t (recur thn)]
  3515. [#f (recur els)])]
  3516. [(Prim 'and (list e1 e2))
  3517. (define v1 (recur e1))
  3518. (match v1
  3519. [#t (match (recur e2) [#t #t] [#f #f])]
  3520. [#f #f])]
  3521. [(Prim op args)
  3522. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3523. )))
  3524. (define (interp-R2 p)
  3525. (match p
  3526. [(Program info e)
  3527. ((interp-exp '()) e)]
  3528. ))
  3529. \end{lstlisting}
  3530. \caption{Interpreter for the $R_2$ language.}
  3531. \label{fig:interp-R2}
  3532. \end{figure}
  3533. \section{Type Checking $R_2$ Programs}
  3534. \label{sec:type-check-r2}
  3535. It is helpful to think about type checking in two complementary
  3536. ways. A type checker predicts the type of value that will be produced
  3537. by each expression in the program. For $R_2$, we have just two types,
  3538. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3539. \begin{lstlisting}
  3540. (+ 10 (- (+ 12 20)))
  3541. \end{lstlisting}
  3542. produces an \key{Integer} while
  3543. \begin{lstlisting}
  3544. (and (not #f) #t)
  3545. \end{lstlisting}
  3546. produces a \key{Boolean}.
  3547. Another way to think about type checking is that it enforces a set of
  3548. rules about which operators can be applied to which kinds of
  3549. values. For example, our type checker for $R_2$ will signal an error
  3550. for the below expression because, as we have seen above, the
  3551. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3552. checker enforces the rule that the argument of \code{not} must be a
  3553. \key{Boolean}.
  3554. \begin{lstlisting}
  3555. (not (+ 10 (- (+ 12 20))))
  3556. \end{lstlisting}
  3557. The type checker for $R_2$ is a structurally recursive function over
  3558. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3559. the \code{type-check-exp} function. Given an input expression
  3560. \code{e}, the type checker either returns a type (\key{Integer} or
  3561. \key{Boolean}) or it signals an error. The type of an integer literal
  3562. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3563. To handle variables, the type checker uses an environment that maps
  3564. variables to types. Consider the clause for \key{let}. We type check
  3565. the initializing expression to obtain its type \key{T} and then
  3566. associate type \code{T} with the variable \code{x} in the
  3567. environment. When the type checker encounters a use of variable
  3568. \code{x} in the body of the \key{let}, it can find its type in the
  3569. environment.
  3570. \begin{figure}[tbp]
  3571. \begin{lstlisting}
  3572. (define (type-check-exp env)
  3573. (lambda (e)
  3574. (match e
  3575. [(Var x) (dict-ref env x)]
  3576. [(Int n) 'Integer]
  3577. [(Bool b) 'Boolean]
  3578. [(Let x e body)
  3579. (define Te ((type-check-exp env) e))
  3580. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3581. Tb]
  3582. ...
  3583. [else
  3584. (error "type-check-exp couldn't match" e)])))
  3585. (define (type-check env)
  3586. (lambda (e)
  3587. (match e
  3588. [(Program info body)
  3589. (define Tb ((type-check-exp '()) body))
  3590. (unless (equal? Tb 'Integer)
  3591. (error "result of the program must be an integer, not " Tb))
  3592. (Program info body)]
  3593. )))
  3594. \end{lstlisting}
  3595. \caption{Skeleton of a type checker for the $R_2$ language.}
  3596. \label{fig:type-check-R2}
  3597. \end{figure}
  3598. \begin{exercise}\normalfont
  3599. Complete the implementation of \code{type-check-R2} and test it on 10
  3600. new example programs in $R_2$ that you choose based on how thoroughly
  3601. they test the type checking function. Half of the example programs
  3602. should have a type error to make sure that your type checker properly
  3603. rejects them. The other half of the example programs should not have
  3604. type errors. Your testing should check that the result of the type
  3605. checker agrees with the value returned by the interpreter, that is, if
  3606. the type checker returns \key{Integer}, then the interpreter should
  3607. return an integer. Likewise, if the type checker returns
  3608. \key{Boolean}, then the interpreter should return \code{\#t} or
  3609. \code{\#f}. Note that if your type checker does not signal an error
  3610. for a program, then interpreting that program should not encounter an
  3611. error. If it does, there is something wrong with your type checker.
  3612. \end{exercise}
  3613. \section{Shrink the $R_2$ Language}
  3614. \label{sec:shrink-r2}
  3615. The $R_2$ language includes several operators that are easily
  3616. expressible in terms of other operators. For example, subtraction is
  3617. expressible in terms of addition and negation.
  3618. \[
  3619. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3620. \]
  3621. Several of the comparison operations are expressible in terms of
  3622. less-than and logical negation.
  3623. \[
  3624. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3625. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3626. \]
  3627. The \key{let} is needed in the above translation to ensure that
  3628. expression $e_1$ is evaluated before $e_2$.
  3629. By performing these translations near the front-end of the compiler,
  3630. the later passes of the compiler do not need to deal with these
  3631. constructs, making those passes shorter. On the other hand, sometimes
  3632. these translations make it more difficult to generate the most
  3633. efficient code with respect to the number of instructions. However,
  3634. these differences typically do not affect the number of accesses to
  3635. memory, which is the primary factor that determines execution time on
  3636. modern computer architectures.
  3637. \begin{exercise}\normalfont
  3638. Implement the pass \code{shrink} that removes subtraction,
  3639. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3640. by translating them to other constructs in $R_2$. Create tests to
  3641. make sure that the behavior of all of these constructs stays the
  3642. same after translation.
  3643. \end{exercise}
  3644. \section{XOR, Comparisons, and Control Flow in x86}
  3645. \label{sec:x86-1}
  3646. To implement the new logical operations, the comparison operations,
  3647. and the \key{if} expression, we need to delve further into the x86
  3648. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3649. larger subset of x86 that includes instructions for logical
  3650. operations, comparisons, and conditional jumps.
  3651. One small challenge is that x86 does not provide an instruction that
  3652. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3653. However, the \code{xorq} instruction can be used to encode \code{not}.
  3654. The \key{xorq} instruction takes two arguments, performs a pairwise
  3655. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3656. and writes the results into its second argument. Recall the truth
  3657. table for exclusive-or:
  3658. \begin{center}
  3659. \begin{tabular}{l|cc}
  3660. & 0 & 1 \\ \hline
  3661. 0 & 0 & 1 \\
  3662. 1 & 1 & 0
  3663. \end{tabular}
  3664. \end{center}
  3665. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3666. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3667. for the bit $1$, the result is the opposite of the second bit. Thus,
  3668. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3669. the first argument:
  3670. \[
  3671. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3672. \qquad\Rightarrow\qquad
  3673. \begin{array}{l}
  3674. \key{movq}~ \Arg\key{,} \Var\\
  3675. \key{xorq}~ \key{\$1,} \Var
  3676. \end{array}
  3677. \]
  3678. \begin{figure}[tp]
  3679. \fbox{
  3680. \begin{minipage}{0.96\textwidth}
  3681. \small
  3682. \[
  3683. \begin{array}{lcl}
  3684. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3685. \mid \BYTEREG{\code{'}\Reg} \\
  3686. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3687. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3688. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3689. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3690. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3691. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3692. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3693. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3694. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3695. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3696. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3697. &\mid& \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3698. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3699. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3700. \end{array}
  3701. \]
  3702. \end{minipage}
  3703. }
  3704. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3705. \label{fig:x86-1}
  3706. \end{figure}
  3707. Next we consider the x86 instructions that are relevant for compiling
  3708. the comparison operations. The \key{cmpq} instruction compares its two
  3709. arguments to determine whether one argument is less than, equal, or
  3710. greater than the other argument. The \key{cmpq} instruction is unusual
  3711. regarding the order of its arguments and where the result is
  3712. placed. The argument order is backwards: if you want to test whether
  3713. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3714. \key{cmpq} is placed in the special EFLAGS register. This register
  3715. cannot be accessed directly but it can be queried by a number of
  3716. instructions, including the \key{set} instruction. The \key{set}
  3717. instruction puts a \key{1} or \key{0} into its destination depending
  3718. on whether the comparison came out according to the condition code
  3719. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3720. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3721. The \key{set} instruction has an annoying quirk in that its
  3722. destination argument must be single byte register, such as \code{al},
  3723. which is part of the \code{rax} register. Thankfully, the
  3724. \key{movzbq} instruction can then be used to move from a single byte
  3725. register to a normal 64-bit register.
  3726. The x86 instruction for conditional jump are relevant to the
  3727. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3728. updates the program counter to point to the instruction after the
  3729. indicated label depending on whether the result in the EFLAGS register
  3730. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3731. instruction falls through to the next instruction. The abstract
  3732. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3733. that it separates the instruction name from the condition code. For
  3734. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3735. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3736. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3737. instruction to set the EFLAGS register.
  3738. \section{The $C_1$ Intermediate Language}
  3739. \label{sec:c1}
  3740. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3741. we need to grow that intermediate language to handle the new features
  3742. in $R_2$: Booleans and conditional expressions.
  3743. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3744. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3745. particular, we add logical and comparison operators to the $\Exp$
  3746. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3747. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3748. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3749. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3750. sequence of statements may now end with a \code{goto} or a conditional
  3751. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3752. depending on the outcome of the comparison. In
  3753. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3754. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3755. and \key{goto}'s.
  3756. \begin{figure}[tbp]
  3757. \fbox{
  3758. \begin{minipage}{0.96\textwidth}
  3759. \small
  3760. \[
  3761. \begin{array}{lcl}
  3762. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3763. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3764. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3765. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3766. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3767. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3768. \mid \key{goto}~\itm{label}\key{;}\\
  3769. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3770. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)^{+} }
  3771. \end{array}
  3772. \]
  3773. \end{minipage}
  3774. }
  3775. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3776. \label{fig:c1-concrete-syntax}
  3777. \end{figure}
  3778. \begin{figure}[tp]
  3779. \fbox{
  3780. \begin{minipage}{0.96\textwidth}
  3781. \small
  3782. \[
  3783. \begin{array}{lcl}
  3784. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3785. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3786. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3787. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3788. &\mid& \UNIOP{\key{'not}}{\Atm}
  3789. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3790. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3791. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3792. \mid \GOTO{\itm{label}} \\
  3793. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3794. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3795. \end{array}
  3796. \]
  3797. \end{minipage}
  3798. }
  3799. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3800. \label{fig:c1-syntax}
  3801. \end{figure}
  3802. \section{Explicate Control}
  3803. \label{sec:explicate-control-r2}
  3804. Recall that the purpose of \code{explicate-control} is to make the
  3805. order of evaluation explicit in the syntax of the program. With the
  3806. addition of \key{if} in $R_2$ this get more interesting.
  3807. As a motivating example, consider the following program that has an
  3808. \key{if} expression nested in the predicate of another \key{if}.
  3809. % s1_38.rkt
  3810. \begin{center}
  3811. \begin{minipage}{0.96\textwidth}
  3812. \begin{lstlisting}
  3813. (if (if (eq? (read) 1)
  3814. (eq? (read) 0)
  3815. (eq? (read) 2))
  3816. (+ 10 32)
  3817. (+ 700 77))
  3818. \end{lstlisting}
  3819. \end{minipage}
  3820. \end{center}
  3821. %
  3822. The naive way to compile \key{if} and \key{eq?} would be to handle
  3823. each of them in isolation, regardless of their context. Each
  3824. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3825. by a couple instructions to move the result from the EFLAGS register
  3826. into a general purpose register or stack location. Each \key{if} would
  3827. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3828. However, if we take context into account we can do better and reduce
  3829. the use of \key{cmpq} and EFLAG-accessing instructions.
  3830. One idea is to try and reorganize the code at the level of $R_2$,
  3831. pushing the outer \key{if} inside the inner one. This would yield the
  3832. following code.
  3833. \begin{center}
  3834. \begin{minipage}{0.96\textwidth}
  3835. \begin{lstlisting}
  3836. (if (eq? (read) 1)
  3837. (if (eq? (read) 0)
  3838. (+ 10 32)
  3839. (+ 700 77))
  3840. (if (eq? (read) 2))
  3841. (+ 10 32)
  3842. (+ 700 77))
  3843. \end{lstlisting}
  3844. \end{minipage}
  3845. \end{center}
  3846. Unfortunately, this approach duplicates the two branches, and a
  3847. compiler must never duplicate code!
  3848. We need a way to perform the above transformation, but without
  3849. duplicating code. The solution is straightforward if we think at the
  3850. level of x86 assembly: we can label the code for each of the branches
  3851. and insert jumps in all the places that need to execute the
  3852. branches. Put another way, we need to move away from abstract syntax
  3853. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3854. use a standard program representation called a \emph{control flow
  3855. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3856. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3857. each edge represents a jump to another block. The \key{Program}
  3858. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3859. as an alist mapping labels to basic blocks. Each block is
  3860. represented by the $\Tail$ non-terminal.
  3861. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3862. \code{remove-complex-opera*} pass and then the
  3863. \code{explicate-control} pass on the example program. We walk through
  3864. the output program and then discuss the algorithm.
  3865. %
  3866. Following the order of evaluation in the output of
  3867. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3868. comparison to \code{1} from the predicate of the inner \key{if}. In
  3869. the output of \code{explicate-control}, in the \code{start} block,
  3870. this becomes a \code{(read)} followed by a conditional \key{goto} to
  3871. either \code{block61} or \code{block62}. Each of these contains the
  3872. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3873. 1)}, respectively. Regarding \code{block61}, we start with the
  3874. \code{(read)} and comparison to \code{0} and then have a conditional
  3875. goto, either to \code{block59} or \code{block60}, which indirectly
  3876. take us to \code{block55} and \code{block56}, the two branches of the
  3877. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3878. story for \code{block62} is similar.
  3879. \begin{figure}[tbp]
  3880. \begin{tabular}{lll}
  3881. \begin{minipage}{0.4\textwidth}
  3882. \begin{lstlisting}
  3883. (if (if (eq? (read) 1)
  3884. (eq? (read) 0)
  3885. (eq? (read) 2))
  3886. (+ 10 32)
  3887. (+ 700 77))
  3888. \end{lstlisting}
  3889. \hspace{40pt}$\Downarrow$
  3890. \begin{lstlisting}
  3891. (if (if (let ([tmp52 (read)])
  3892. (eq? tmp52 1))
  3893. (let ([tmp53 (read)])
  3894. (eq? tmp53 0))
  3895. (let ([tmp54 (read)])
  3896. (eq? tmp54 2)))
  3897. (+ 10 32)
  3898. (+ 700 77))
  3899. \end{lstlisting}
  3900. \end{minipage}
  3901. &
  3902. $\Rightarrow$
  3903. &
  3904. \begin{minipage}{0.55\textwidth}
  3905. \begin{lstlisting}
  3906. block62:
  3907. tmp54 = (read);
  3908. if (eq? tmp54 2) then
  3909. goto block59;
  3910. else
  3911. goto block60;
  3912. block61:
  3913. tmp53 = (read);
  3914. if (eq? tmp53 0) then
  3915. goto block57;
  3916. else
  3917. goto block58;
  3918. block60:
  3919. goto block56;
  3920. block59:
  3921. goto block55;
  3922. block58:
  3923. goto block56;
  3924. block57:
  3925. goto block55;
  3926. block56:
  3927. return (+ 700 77);
  3928. block55:
  3929. return (+ 10 32);
  3930. start:
  3931. tmp52 = (read);
  3932. if (eq? tmp52 1) then
  3933. goto block61;
  3934. else
  3935. goto block62;
  3936. \end{lstlisting}
  3937. \end{minipage}
  3938. \end{tabular}
  3939. \caption{Example translation from $R_2$ to $C_1$
  3940. via the \code{explicate-control}.}
  3941. \label{fig:explicate-control-s1-38}
  3942. \end{figure}
  3943. The nice thing about the output of \code{explicate-control} is that
  3944. there are no unnecessary uses of \code{eq?} and every use of
  3945. \code{eq?} is part of a conditional jump. The down-side of this output
  3946. is that it includes trivial blocks, such as \code{block57} through
  3947. \code{block60}, that only jump to another block. We discuss a solution
  3948. to this problem in Section~\ref{sec:opt-jumps}.
  3949. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3950. \code{explicate-control} for $R_1$ using two mutually recursive
  3951. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3952. former function translates expressions in tail position whereas the
  3953. later function translates expressions on the right-hand-side of a
  3954. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3955. new kind of context to deal with: the predicate position of the
  3956. \key{if}. We need another function, \code{explicate-pred}, that takes
  3957. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3958. the then-branch and else-branch. The output of \code{explicate-pred}
  3959. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3960. Note that the three explicate functions need to construct a
  3961. control-flow graph, which we recommend they do via updates to a global
  3962. variable.
  3963. In the following paragraphs we consider the specific additions to the
  3964. \code{explicate-tail} and \code{explicate-assign} functions, and some
  3965. of cases for the \code{explicate-pred} function.
  3966. The \code{explicate-tail} function needs an additional case for
  3967. \key{if}. The branches of the \key{if} inherit the current context, so
  3968. they are in tail position. Let $B_1$ be the result of
  3969. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3970. be the result of apply \code{explicate-tail} to the ``else''
  3971. branch. Then the \key{if} as a whole translates to the block $B_3$
  3972. which is the result of applying \code{explicate-pred} to the predicate
  3973. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3974. \[
  3975. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3976. \]
  3977. Next we consider the case for \key{if} in the \code{explicate-assign}
  3978. function. The context of the \key{if} is an assignment to some
  3979. variable $x$ and then the control continues to some block $B_1$. The
  3980. code that we generate for the ``then'' and ``else'' branches needs to
  3981. continue to $B_1$, so we add $B_1$ to the control flow graph with a
  3982. fresh label $\ell_1$. Again, the branches of the \key{if} inherit the
  3983. current context, so that are in assignment positions. Let $B_2$ be
  3984. the result of applying \code{explicate-assign} to the ``then'' branch,
  3985. variable $x$, and the block \GOTO{$\ell_1$}. Let $B_3$ be the result
  3986. of applying \code{explicate-assign} to the ``else'' branch, variable
  3987. $x$, and the block \GOTO{$\ell_1$}. The \key{if} translates to the
  3988. block $B_4$ which is the result of applying \code{explicate-pred} to
  3989. the predicate $\itm{cnd}$ and the blocks $B_2$ and $B_3$.
  3990. \[
  3991. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3992. \]
  3993. The function \code{explicate-pred} will need a case for every
  3994. expression that can have type \code{Boolean}. We detail a few cases
  3995. here and leave the rest for the reader. The input to this function is
  3996. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  3997. the enclosing \key{if}. Suppose the expression is the Boolean
  3998. \code{\#t}. Then we can perform a kind of partial evaluation and
  3999. translate it to the ``then'' branch $B_1$. Likewise, we translate
  4000. \code{\#f} to the ``else`` branch $B_2$.
  4001. \[
  4002. \key{\#t} \quad\Rightarrow\quad B_1,
  4003. \qquad\qquad\qquad
  4004. \key{\#f} \quad\Rightarrow\quad B_2
  4005. \]
  4006. Next, suppose the expression is a less-than comparison. We translate
  4007. it to a conditional \code{goto}. We need labels for the two branches
  4008. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4009. obtain some labels $\ell_1$ and $\ell_2$. The translation of the
  4010. less-than comparison is as follows.
  4011. \[
  4012. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4013. \begin{array}{l}
  4014. \key{if}~(\key{<}~e_1~e_2) \\
  4015. \qquad\key{goto}~\ell_1\key{;}\\
  4016. \key{else}\\
  4017. \qquad\key{goto}~\ell_2\key{;}
  4018. \end{array}
  4019. \]
  4020. The case for \key{if} in \code{explicate-pred} is particularly
  4021. illuminating as it deals with the challenges that we discussed above
  4022. regarding the example of the nested \key{if} expressions. Again, we
  4023. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4024. obtain the labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4025. branches of the current \key{if} inherit their context from the
  4026. current one, that is, predicate context. So we apply
  4027. \code{explicate-pred} to the ``then'' branch with the two blocks
  4028. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4029. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4030. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4031. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4032. \[
  4033. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4034. \quad\Rightarrow\quad
  4035. B_5
  4036. \]
  4037. \begin{exercise}\normalfont
  4038. Implement the pass \code{explicate-control} by adding the cases for
  4039. \key{if} to the functions for tail and assignment contexts, and
  4040. implement \code{explicate-pred} for predicate contexts. Create test
  4041. cases that exercise all of the new cases in the code for this pass.
  4042. \end{exercise}
  4043. \section{Select Instructions}
  4044. \label{sec:select-r2}
  4045. Recall that the \code{select-instructions} pass lowers from our
  4046. $C$-like intermediate representation to the pseudo-x86 language, which
  4047. is suitable for conducting register allocation. The pass is
  4048. implemented using three auxiliary functions, one for each of the
  4049. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4050. For $\Atm$, we have new cases for the Booleans. We take the usual
  4051. approach of encoding them as integers, with true as 1 and false as 0.
  4052. \[
  4053. \key{\#t} \Rightarrow \key{1}
  4054. \qquad
  4055. \key{\#f} \Rightarrow \key{0}
  4056. \]
  4057. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4058. be implemented in terms of \code{xorq} as we discussed at the
  4059. beginning of this section. Given an assignment
  4060. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4061. if the left-hand side $\itm{var}$ is
  4062. the same as $\Atm$, then just the \code{xorq} suffices.
  4063. \[
  4064. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4065. \quad\Rightarrow\quad
  4066. \key{xorq}~\key{\$}1\key{,}~\Var
  4067. \]
  4068. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4069. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4070. x86. Then we have
  4071. \[
  4072. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4073. \quad\Rightarrow\quad
  4074. \begin{array}{l}
  4075. \key{movq}~\Arg\key{,}~\Var\\
  4076. \key{xorq}~\key{\$}1\key{,}~\Var
  4077. \end{array}
  4078. \]
  4079. Next consider the cases for \code{eq?} and less-than comparison.
  4080. Translating these operations to x86 is slightly involved due to the
  4081. unusual nature of the \key{cmpq} instruction discussed above. We
  4082. recommend translating an assignment from \code{eq?} into the following
  4083. sequence of three instructions. \\
  4084. \begin{tabular}{lll}
  4085. \begin{minipage}{0.4\textwidth}
  4086. \begin{lstlisting}
  4087. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4088. \end{lstlisting}
  4089. \end{minipage}
  4090. &
  4091. $\Rightarrow$
  4092. &
  4093. \begin{minipage}{0.4\textwidth}
  4094. \begin{lstlisting}
  4095. cmpq |$\Arg_2$|, |$\Arg_1$|
  4096. sete %al
  4097. movzbq %al, |$\Var$|
  4098. \end{lstlisting}
  4099. \end{minipage}
  4100. \end{tabular} \\
  4101. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4102. and conditional \key{goto}. Both are straightforward to handle. A
  4103. \key{goto} becomes a jump instruction.
  4104. \[
  4105. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4106. \]
  4107. A conditional \key{goto} becomes a compare instruction followed
  4108. by a conditional jump (for ``then'') and the fall-through is
  4109. to a regular jump (for ``else'').\\
  4110. \begin{tabular}{lll}
  4111. \begin{minipage}{0.4\textwidth}
  4112. \begin{lstlisting}
  4113. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4114. goto |$\ell_1$|;
  4115. else
  4116. goto |$\ell_2$|;
  4117. \end{lstlisting}
  4118. \end{minipage}
  4119. &
  4120. $\Rightarrow$
  4121. &
  4122. \begin{minipage}{0.4\textwidth}
  4123. \begin{lstlisting}
  4124. cmpq |$\Arg_2$|, |$\Arg_1$|
  4125. je |$\ell_1$|
  4126. jmp |$\ell_2$|
  4127. \end{lstlisting}
  4128. \end{minipage}
  4129. \end{tabular} \\
  4130. \begin{exercise}\normalfont
  4131. Expand your \code{select-instructions} pass to handle the new features
  4132. of the $R_2$ language. Test the pass on all the examples you have
  4133. created and make sure that you have some test programs that use the
  4134. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4135. the output using the \code{interp-x86} interpreter
  4136. (Appendix~\ref{appendix:interp}).
  4137. \end{exercise}
  4138. \section{Register Allocation}
  4139. \label{sec:register-allocation-r2}
  4140. The changes required for $R_2$ affect liveness analysis, building the
  4141. interference graph, and assigning homes, but the graph coloring
  4142. algorithm itself does not change.
  4143. \subsection{Liveness Analysis}
  4144. \label{sec:liveness-analysis-r2}
  4145. Recall that for $R_1$ we implemented liveness analysis for a single
  4146. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4147. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4148. produces many basic blocks arranged in a control-flow graph. The first
  4149. question we need to consider is: what order should we process the
  4150. basic blocks? Recall that to perform liveness analysis, we need to
  4151. know the live-after set. If a basic block has no successor blocks
  4152. (i.e. no out-edges in the control flow graph), then it has an empty
  4153. live-after set and we can immediately apply liveness analysis to
  4154. it. If a basic block has some successors, then we need to complete
  4155. liveness analysis on those blocks first. Furthermore, we know that
  4156. the control flow graph does not contain any cycles because $R_2$ does
  4157. not include loops
  4158. %
  4159. \footnote{If we were to add loops to the language, then the CFG could
  4160. contain cycles and we would instead need to use the classic worklist
  4161. algorithm for computing the fixed point of the liveness
  4162. analysis~\citep{Aho:1986qf}.}.
  4163. %
  4164. Returning to the question of what order should we process the basic
  4165. blocks, the answer is reverse topological order. We recommend using
  4166. the \code{tsort} (topological sort) and \code{transpose} functions of
  4167. the Racket \code{graph} package to obtain this ordering.
  4168. The next question is how to compute the live-after set of a block
  4169. given the live-before sets of all its successor blocks. (There can be
  4170. more than one because of conditional jumps.) During compilation we do
  4171. not know which way a conditional jump will go, so we do not know which
  4172. of the successor's live-before set to use. The solution to this
  4173. challenge is based on the observation that there is no harm to the
  4174. correctness of the compiler if we classify more variables as live than
  4175. the ones that are truly live during a particular execution of the
  4176. block. Thus, we can take the union of the live-before sets from all
  4177. the successors to be the live-after set for the block. Once we have
  4178. computed the live-after set, we can proceed to perform liveness
  4179. analysis on the block just as we did in
  4180. Section~\ref{sec:liveness-analysis-r1}.
  4181. The helper functions for computing the variables in an instruction's
  4182. argument and for computing the variables read-from ($R$) or written-to
  4183. ($W$) by an instruction need to be updated to handle the new kinds of
  4184. arguments and instructions in x86$_1$.
  4185. \subsection{Build Interference}
  4186. \label{sec:build-interference-r2}
  4187. Many of the new instructions in x86$_1$ can be handled in the same way
  4188. as the instructions in x86$_0$. Thus, if your code was already quite
  4189. general, it will not need to be changed to handle the new
  4190. instructions. If you code is not general enough, I recommend that you
  4191. change your code to be more general. For example, you can factor out
  4192. the computing of the the read and write sets for each kind of
  4193. instruction into two auxiliary functions.
  4194. Note that the \key{movzbq} instruction requires some special care,
  4195. just like the \key{movq} instruction. See rule number 3 in
  4196. Section~\ref{sec:build-interference}.
  4197. %% \subsection{Assign Homes}
  4198. %% \label{sec:assign-homes-r2}
  4199. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4200. %% to be updated to handle the \key{if} statement, simply by recursively
  4201. %% processing the child nodes. Hopefully your code already handles the
  4202. %% other new instructions, but if not, you can generalize your code.
  4203. \begin{exercise}\normalfont
  4204. Update the \code{register-allocation} pass so that it works for $R_2$
  4205. and test your compiler using your previously created programs on the
  4206. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4207. \end{exercise}
  4208. \section{Patch Instructions}
  4209. The second argument of the \key{cmpq} instruction must not be an
  4210. immediate value (such as an integer). So if you are comparing two
  4211. immediates, we recommend inserting a \key{movq} instruction to put the
  4212. second argument in \key{rax}.
  4213. %
  4214. The second argument of the \key{movzbq} must be a register.
  4215. %
  4216. There are no special restrictions on the x86 instructions \key{JmpIf}
  4217. and \key{Jmp}.
  4218. \begin{exercise}\normalfont
  4219. Update \code{patch-instructions} to handle the new x86 instructions.
  4220. Test your compiler using your previously created programs on the
  4221. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4222. \end{exercise}
  4223. \section{An Example Translation}
  4224. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4225. $R_2$ translated to x86, showing the results of
  4226. \code{explicate-control}, \code{select-instructions}, and the final
  4227. x86 assembly code.
  4228. \begin{figure}[tbp]
  4229. \begin{tabular}{lll}
  4230. \begin{minipage}{0.5\textwidth}
  4231. % s1_20.rkt
  4232. \begin{lstlisting}
  4233. (if (eq? (read) 1) 42 0)
  4234. \end{lstlisting}
  4235. $\Downarrow$
  4236. \begin{lstlisting}
  4237. start:
  4238. tmp7951 = (read);
  4239. if (eq? tmp7951 1) then
  4240. goto block7952;
  4241. else
  4242. goto block7953;
  4243. block7952:
  4244. return 42;
  4245. block7953:
  4246. return 0;
  4247. \end{lstlisting}
  4248. $\Downarrow$
  4249. \begin{lstlisting}
  4250. start:
  4251. callq read_int
  4252. movq %rax, tmp7951
  4253. cmpq $1, tmp7951
  4254. je block7952
  4255. jmp block7953
  4256. block7953:
  4257. movq $0, %rax
  4258. jmp conclusion
  4259. block7952:
  4260. movq $42, %rax
  4261. jmp conclusion
  4262. \end{lstlisting}
  4263. \end{minipage}
  4264. &
  4265. $\Rightarrow\qquad$
  4266. \begin{minipage}{0.4\textwidth}
  4267. \begin{lstlisting}
  4268. start:
  4269. callq read_int
  4270. movq %rax, %rcx
  4271. cmpq $1, %rcx
  4272. je block7952
  4273. jmp block7953
  4274. block7953:
  4275. movq $0, %rax
  4276. jmp conclusion
  4277. block7952:
  4278. movq $42, %rax
  4279. jmp conclusion
  4280. .globl main
  4281. main:
  4282. pushq %rbp
  4283. movq %rsp, %rbp
  4284. pushq %r13
  4285. pushq %r12
  4286. pushq %rbx
  4287. pushq %r14
  4288. subq $0, %rsp
  4289. jmp start
  4290. conclusion:
  4291. addq $0, %rsp
  4292. popq %r14
  4293. popq %rbx
  4294. popq %r12
  4295. popq %r13
  4296. popq %rbp
  4297. retq
  4298. \end{lstlisting}
  4299. \end{minipage}
  4300. \end{tabular}
  4301. \caption{Example compilation of an \key{if} expression to x86.}
  4302. \label{fig:if-example-x86}
  4303. \end{figure}
  4304. \begin{figure}[p]
  4305. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4306. \node (R2) at (0,2) {\large $R_2$};
  4307. \node (R2-2) at (3,2) {\large $R_2$};
  4308. \node (R2-3) at (6,2) {\large $R_2$};
  4309. \node (R2-4) at (9,2) {\large $R_2$};
  4310. \node (R2-5) at (12,2) {\large $R_2$};
  4311. \node (C1-1) at (6,0) {\large $C_1$};
  4312. %\node (C1-2) at (3,0) {\large $C_1$};
  4313. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4314. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4315. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4316. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4317. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4318. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4319. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4320. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4321. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4322. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4323. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4324. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4325. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4326. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4327. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4328. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4329. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4330. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4331. \end{tikzpicture}
  4332. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4333. \label{fig:R2-passes}
  4334. \end{figure}
  4335. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4336. compilation of $R_2$.
  4337. \section{Challenge: Optimize and Remove Jumps}
  4338. \label{sec:opt-jumps}
  4339. Recall that in the example output of \code{explicate-control} in
  4340. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4341. \code{block60} are trivial blocks, they do nothing but jump to another
  4342. block. The first goal of this challenge assignment is to remove those
  4343. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4344. \code{explicate-control} on the left and shows the result of bypassing
  4345. the trivial blocks on the right. Let us focus on \code{block61}. The
  4346. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4347. \code{block55}. The optimized code on the right of
  4348. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4349. \code{then} branch jumping directly to \code{block55}. The story is
  4350. similar for the \code{else} branch, as well as for the two branches in
  4351. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4352. have been optimized in this way, there are no longer any jumps to
  4353. blocks \code{block57} through \code{block60}, so they can be removed.
  4354. \begin{figure}[tbp]
  4355. \begin{tabular}{lll}
  4356. \begin{minipage}{0.4\textwidth}
  4357. \begin{lstlisting}
  4358. block62:
  4359. tmp54 = (read);
  4360. if (eq? tmp54 2) then
  4361. goto block59;
  4362. else
  4363. goto block60;
  4364. block61:
  4365. tmp53 = (read);
  4366. if (eq? tmp53 0) then
  4367. goto block57;
  4368. else
  4369. goto block58;
  4370. block60:
  4371. goto block56;
  4372. block59:
  4373. goto block55;
  4374. block58:
  4375. goto block56;
  4376. block57:
  4377. goto block55;
  4378. block56:
  4379. return (+ 700 77);
  4380. block55:
  4381. return (+ 10 32);
  4382. start:
  4383. tmp52 = (read);
  4384. if (eq? tmp52 1) then
  4385. goto block61;
  4386. else
  4387. goto block62;
  4388. \end{lstlisting}
  4389. \end{minipage}
  4390. &
  4391. $\Rightarrow$
  4392. &
  4393. \begin{minipage}{0.55\textwidth}
  4394. \begin{lstlisting}
  4395. block62:
  4396. tmp54 = (read);
  4397. if (eq? tmp54 2) then
  4398. goto block55;
  4399. else
  4400. goto block56;
  4401. block61:
  4402. tmp53 = (read);
  4403. if (eq? tmp53 0) then
  4404. goto block55;
  4405. else
  4406. goto block56;
  4407. block56:
  4408. return (+ 700 77);
  4409. block55:
  4410. return (+ 10 32);
  4411. start:
  4412. tmp52 = (read);
  4413. if (eq? tmp52 1) then
  4414. goto block61;
  4415. else
  4416. goto block62;
  4417. \end{lstlisting}
  4418. \end{minipage}
  4419. \end{tabular}
  4420. \caption{Optimize jumps by removing trivial blocks.}
  4421. \label{fig:optimize-jumps}
  4422. \end{figure}
  4423. The name of this pass is \code{optimize-jumps}. We recommend
  4424. implementing this pass in two phases. The first phrase builds a hash
  4425. table that maps labels to possibly improved labels. The second phase
  4426. changes the target of each \code{goto} to use the improved label. If
  4427. the label is for a trivial block, then the hash table should map the
  4428. label to the first non-trivial block that can be reached from this
  4429. label by jumping through trivial blocks. If the label is for a
  4430. non-trivial block, then the hash table should map the label to itself;
  4431. we do not want to change jumps to non-trivial blocks.
  4432. The first phase can be accomplished by constructing an empty hash
  4433. table, call it \code{short-cut}, and then iterating over the control
  4434. flow graph. Each time you encouter a block that is just a \code{goto},
  4435. then update the hash table, mapping the block's source to the target
  4436. of the \code{goto}. Also, the hash table may already have mapped some
  4437. labels to the block's source, to you must iterate through the hash
  4438. table and update all of those so that they instead map to the target
  4439. of the \code{goto}.
  4440. For the second phase, we recommend iterating through the $\Tail$ of
  4441. each block in the program, updating the target of every \code{goto}
  4442. according to the mapping in \code{short-cut}.
  4443. \begin{exercise}\normalfont
  4444. Implement the \code{optimize-jumps} pass and check that it remove
  4445. trivial blocks in a few example programs. Then check that your
  4446. compiler still passes all of your tests.
  4447. \end{exercise}
  4448. There is another opportunity for optimizing jumps that is apparent in
  4449. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4450. end with a jump to \code{block7953} and there are no other jumps to
  4451. \code{block7953} in the rest of the program. In this situation we can
  4452. avoid the runtime overhead of this jump by merging \code{block7953}
  4453. into the preceeding block, in this case the \code{start} block.
  4454. Figure~\ref{fig:remove-jumps} shows the output of
  4455. \code{select-instructions} on the left and the result of this
  4456. optimization on the right.
  4457. \begin{figure}[tbp]
  4458. \begin{tabular}{lll}
  4459. \begin{minipage}{0.5\textwidth}
  4460. % s1_20.rkt
  4461. \begin{lstlisting}
  4462. start:
  4463. callq read_int
  4464. movq %rax, tmp7951
  4465. cmpq $1, tmp7951
  4466. je block7952
  4467. jmp block7953
  4468. block7953:
  4469. movq $0, %rax
  4470. jmp conclusion
  4471. block7952:
  4472. movq $42, %rax
  4473. jmp conclusion
  4474. \end{lstlisting}
  4475. \end{minipage}
  4476. &
  4477. $\Rightarrow\qquad$
  4478. \begin{minipage}{0.4\textwidth}
  4479. \begin{lstlisting}
  4480. start:
  4481. callq read_int
  4482. movq %rax, tmp7951
  4483. cmpq $1, tmp7951
  4484. je block7952
  4485. movq $0, %rax
  4486. jmp conclusion
  4487. block7952:
  4488. movq $42, %rax
  4489. jmp conclusion
  4490. \end{lstlisting}
  4491. \end{minipage}
  4492. \end{tabular}
  4493. \caption{Merging basic blocks by removing unnecessary jumps.}
  4494. \label{fig:remove-jumps}
  4495. \end{figure}
  4496. \begin{exercise}\normalfont
  4497. Implement a pass named \code{remove-jumps} that merges basic blocks
  4498. into their preceeding basic block, when there is only one preceeding
  4499. block. Check that your pass accomplishes this goal on several test
  4500. programs and check that your compiler passes all of your tests.
  4501. \end{exercise}
  4502. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4503. \chapter{Tuples and Garbage Collection}
  4504. \label{ch:tuples}
  4505. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4506. things to discuss in this chapter. \\ --Jeremy}
  4507. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4508. all the IR grammars are spelled out! \\ --Jeremy}
  4509. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4510. but keep type annotations on vector creation and local variables, function
  4511. parameters, etc. \\ --Jeremy}
  4512. \margincomment{\scriptsize Be more explicit about how to deal with
  4513. the root stack. \\ --Jeremy}
  4514. In this chapter we study the implementation of mutable tuples (called
  4515. ``vectors'' in Racket). This language feature is the first to use the
  4516. computer's \emph{heap} because the lifetime of a Racket tuple is
  4517. indefinite, that is, a tuple lives forever from the programmer's
  4518. viewpoint. Of course, from an implementer's viewpoint, it is important
  4519. to reclaim the space associated with a tuple when it is no longer
  4520. needed, which is why we also study \emph{garbage collection}
  4521. techniques in this chapter.
  4522. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4523. interpreter and type checker. The $R_3$ language extends the $R_2$
  4524. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4525. \code{void} value. The reason for including the later is that the
  4526. \code{vector-set!} operation returns a value of type
  4527. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4528. called the \code{Unit} type in the programming languages
  4529. literature. Racket's \code{Void} type is inhabited by a single value
  4530. \code{void} which corresponds to \code{unit} or \code{()} in the
  4531. literature~\citep{Pierce:2002hj}.}.
  4532. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4533. copying live objects back and forth between two halves of the
  4534. heap. The garbage collector requires coordination with the compiler so
  4535. that it can see all of the \emph{root} pointers, that is, pointers in
  4536. registers or on the procedure call stack.
  4537. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4538. discuss all the necessary changes and additions to the compiler
  4539. passes, including a new compiler pass named \code{expose-allocation}.
  4540. \section{The $R_3$ Language}
  4541. \label{sec:r3}
  4542. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4543. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4544. $R_3$ language includes three new forms for creating a tuple, reading
  4545. an element of a tuple, and writing to an element of a tuple. The
  4546. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4547. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4548. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4549. first-class values. The element at index $1$ of \code{t} is
  4550. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4551. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4552. element at index $0$ of the 1-tuple. So the result of the program is
  4553. $42$.
  4554. \begin{figure}[tbp]
  4555. \begin{lstlisting}
  4556. (let ([t (vector 40 #t (vector 2))])
  4557. (if (vector-ref t 1)
  4558. (+ (vector-ref t 0)
  4559. (vector-ref (vector-ref t 2) 0))
  4560. 44))
  4561. \end{lstlisting}
  4562. \caption{Example program that creates tuples and reads from them.}
  4563. \label{fig:vector-eg}
  4564. \end{figure}
  4565. \begin{figure}[tbp]
  4566. \centering
  4567. \fbox{
  4568. \begin{minipage}{0.96\textwidth}
  4569. \[
  4570. \begin{array}{lcl}
  4571. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4572. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4573. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4574. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4575. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4576. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4577. \mid (\key{and}\;\Exp\;\Exp)
  4578. \mid (\key{or}\;\Exp\;\Exp)
  4579. \mid (\key{not}\;\Exp) } \\
  4580. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4581. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4582. &\mid& (\key{vector}\;\Exp^{+})
  4583. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4584. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4585. &\mid& (\key{void}) \\
  4586. R_3 &::=& \Exp
  4587. \end{array}
  4588. \]
  4589. \end{minipage}
  4590. }
  4591. \caption{The concrete syntax of $R_3$, extending $R_2$
  4592. (Figure~\ref{fig:r2-concrete-syntax}).}
  4593. \label{fig:r3-concrete-syntax}
  4594. \end{figure}
  4595. \begin{figure}[tp]
  4596. \centering
  4597. \fbox{
  4598. \begin{minipage}{0.96\textwidth}
  4599. \[
  4600. \begin{array}{lcl}
  4601. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4602. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4603. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4604. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4605. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4606. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4607. &\mid& \gray{ \BOOL{\itm{bool}}
  4608. \mid \AND{\Exp}{\Exp} }\\
  4609. &\mid& \gray{ \OR{\Exp}{\Exp}
  4610. \mid \NOT{\Exp} } \\
  4611. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4612. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4613. &\mid& \VECTOR{\Exp} \\
  4614. &\mid& \VECREF{\Exp}{\Int}\\
  4615. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4616. &\mid& \VOID{} \\
  4617. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4618. \end{array}
  4619. \]
  4620. \end{minipage}
  4621. }
  4622. \caption{The abstract syntax of $R_3$.}
  4623. \label{fig:r3-syntax}
  4624. \end{figure}
  4625. Tuples are our first encounter with heap-allocated data, which raises
  4626. several interesting issues. First, variable binding performs a
  4627. shallow-copy when dealing with tuples, which means that different
  4628. variables can refer to the same tuple, i.e., different variables can
  4629. be \emph{aliases} for the same thing. Consider the following example
  4630. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4631. the mutation through \code{t2} is visible when referencing the tuple
  4632. from \code{t1}, so the result of this program is \code{42}.
  4633. \begin{center}
  4634. \begin{minipage}{0.96\textwidth}
  4635. \begin{lstlisting}
  4636. (let ([t1 (vector 3 7)])
  4637. (let ([t2 t1])
  4638. (let ([_ (vector-set! t2 0 42)])
  4639. (vector-ref t1 0))))
  4640. \end{lstlisting}
  4641. \end{minipage}
  4642. \end{center}
  4643. The next issue concerns the lifetime of tuples. Of course, they are
  4644. created by the \code{vector} form, but when does their lifetime end?
  4645. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4646. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4647. is not tied to any notion of static scoping. For example, the
  4648. following program returns \code{3} even though the variable \code{t}
  4649. goes out of scope prior to accessing the vector.
  4650. \begin{center}
  4651. \begin{minipage}{0.96\textwidth}
  4652. \begin{lstlisting}
  4653. (vector-ref
  4654. (let ([t (vector 3 7)])
  4655. t)
  4656. 0)
  4657. \end{lstlisting}
  4658. \end{minipage}
  4659. \end{center}
  4660. From the perspective of programmer-observable behavior, tuples live
  4661. forever. Of course, if they really lived forever, then many programs
  4662. would run out of memory.\footnote{The $R_3$ language does not have
  4663. looping or recursive function, so it is nigh impossible to write a
  4664. program in $R_3$ that will run out of memory. However, we add
  4665. recursive functions in the next Chapter!} A Racket implementation
  4666. must therefore perform automatic garbage collection.
  4667. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4668. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4669. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4670. operations in Racket. One subtle point is that the \code{vector-set!}
  4671. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4672. can be passed around just like other values inside an $R_3$ program,
  4673. but there are no operations specific to the the \code{\#<void>} value
  4674. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4675. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4676. otherwise.
  4677. \begin{figure}[tbp]
  4678. \begin{lstlisting}
  4679. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4680. (define (interp-op op)
  4681. (match op
  4682. ...
  4683. ['vector vector]
  4684. ['vector-ref vector-ref]
  4685. ['vector-set! vector-set!]
  4686. [else (error 'interp-op "unknown operator")]))
  4687. (define (interp-R3 env)
  4688. (lambda (e)
  4689. (match e
  4690. ...
  4691. [else (error 'interp-R3 "unrecognized expression")]
  4692. )))
  4693. \end{lstlisting}
  4694. \caption{Interpreter for the $R_3$ language.}
  4695. \label{fig:interp-R3}
  4696. \end{figure}
  4697. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4698. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4699. need to know which variables are pointers into the heap, that is,
  4700. which variables are vectors. Also, when allocating a vector, we need
  4701. to know which elements of the vector are pointers. We can obtain this
  4702. information during type checking. The type checker in
  4703. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4704. expression, it also wraps every sub-expression $e$ with the form
  4705. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4706. % TODO: UPDATE? -Jeremy
  4707. Subsequently, in the \code{uncover-locals} pass
  4708. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4709. propagated to all variables (including the temporaries generated by
  4710. \code{remove-complex-opera*}).
  4711. \begin{figure}[tbp]
  4712. \begin{lstlisting}
  4713. (define (type-check-exp env)
  4714. (lambda (e)
  4715. (define recur (type-check-exp env))
  4716. (match e
  4717. ...
  4718. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4719. [(Prim 'vector es)
  4720. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4721. (recur e)))
  4722. (let ([t `(Vector ,@t*)])
  4723. (values (HasType (Prim 'vector e*) t) t))]
  4724. [(Prim 'vector-ref (list e (Int i)))
  4725. (define-values (e^ t) (recur e))
  4726. (match t
  4727. [`(Vector ,ts ...)
  4728. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4729. (error 'type-check-exp "invalid index ~a" i))
  4730. (let ([t (list-ref ts i)])
  4731. (values
  4732. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4733. t))]
  4734. [else (error "expected a vector in vector-ref, not" t)])]
  4735. [(Prim 'eq? (list e1 e2))
  4736. (define-values (e1^ T1) (recur e1))
  4737. (define-values (e2^ T2) (recur e2))
  4738. (unless (equal? T1 T2)
  4739. (error "arguments of eq? must have the same type, but are not"
  4740. (list T1 T2)))
  4741. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4742. ...
  4743. )))
  4744. \end{lstlisting}
  4745. \caption{Type checker for the $R_3$ language.}
  4746. \label{fig:typecheck-R3}
  4747. \end{figure}
  4748. \section{Garbage Collection}
  4749. \label{sec:GC}
  4750. Here we study a relatively simple algorithm for garbage collection
  4751. that is the basis of state-of-the-art garbage
  4752. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4753. particular, we describe a two-space copying
  4754. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4755. perform the
  4756. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4757. coarse-grained depiction of what happens in a two-space collector,
  4758. showing two time steps, prior to garbage collection on the top and
  4759. after garbage collection on the bottom. In a two-space collector, the
  4760. heap is divided into two parts, the FromSpace and the
  4761. ToSpace. Initially, all allocations go to the FromSpace until there is
  4762. not enough room for the next allocation request. At that point, the
  4763. garbage collector goes to work to make more room.
  4764. The garbage collector must be careful not to reclaim tuples that will
  4765. be used by the program in the future. Of course, it is impossible in
  4766. general to predict what a program will do, but we can over approximate
  4767. the will-be-used tuples by preserving all tuples that could be
  4768. accessed by \emph{any} program given the current computer state. A
  4769. program could access any tuple whose address is in a register or on
  4770. the procedure call stack. These addresses are called the \emph{root
  4771. set}. In addition, a program could access any tuple that is
  4772. transitively reachable from the root set. Thus, it is safe for the
  4773. garbage collector to reclaim the tuples that are not reachable in this
  4774. way.
  4775. So the goal of the garbage collector is twofold:
  4776. \begin{enumerate}
  4777. \item preserve all tuple that are reachable from the root set via a
  4778. path of pointers, that is, the \emph{live} tuples, and
  4779. \item reclaim the memory of everything else, that is, the
  4780. \emph{garbage}.
  4781. \end{enumerate}
  4782. A copying collector accomplishes this by copying all of the live
  4783. objects from the FromSpace into the ToSpace and then performs a slight
  4784. of hand, treating the ToSpace as the new FromSpace and the old
  4785. FromSpace as the new ToSpace. In the example of
  4786. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4787. root set, one in a register and two on the stack. All of the live
  4788. objects have been copied to the ToSpace (the right-hand side of
  4789. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4790. pointer relationships. For example, the pointer in the register still
  4791. points to a 2-tuple whose first element is a 3-tuple and second
  4792. element is a 2-tuple. There are four tuples that are not reachable
  4793. from the root set and therefore do not get copied into the ToSpace.
  4794. (The situation in Figure~\ref{fig:copying-collector}, with a
  4795. cycle, cannot be created by a well-typed program in $R_3$. However,
  4796. creating cycles will be possible once we get to $R_6$. We design
  4797. the garbage collector to deal with cycles to begin with, so we will
  4798. not need to revisit this issue.)
  4799. \begin{figure}[tbp]
  4800. \centering
  4801. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4802. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4803. \caption{A copying collector in action.}
  4804. \label{fig:copying-collector}
  4805. \end{figure}
  4806. There are many alternatives to copying collectors (and their older
  4807. siblings, the generational collectors) when its comes to garbage
  4808. collection, such as mark-and-sweep and reference counting. The
  4809. strengths of copying collectors are that allocation is fast (just a
  4810. test and pointer increment), there is no fragmentation, cyclic garbage
  4811. is collected, and the time complexity of collection only depends on
  4812. the amount of live data, and not on the amount of
  4813. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4814. copying collectors is that they use a lot of space, though that
  4815. problem is ameliorated in generational collectors. Racket and Scheme
  4816. programs tend to allocate many small objects and generate a lot of
  4817. garbage, so copying and generational collectors are a good fit. Of
  4818. course, garbage collection is an active research topic, especially
  4819. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4820. continuously developing new techniques and revisiting old
  4821. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4822. \subsection{Graph Copying via Cheney's Algorithm}
  4823. \label{sec:cheney}
  4824. Let us take a closer look at how the copy works. The allocated objects
  4825. and pointers can be viewed as a graph and we need to copy the part of
  4826. the graph that is reachable from the root set. To make sure we copy
  4827. all of the reachable vertices in the graph, we need an exhaustive
  4828. graph traversal algorithm, such as depth-first search or breadth-first
  4829. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4830. take into account the possibility of cycles by marking which vertices
  4831. have already been visited, so as to ensure termination of the
  4832. algorithm. These search algorithms also use a data structure such as a
  4833. stack or queue as a to-do list to keep track of the vertices that need
  4834. to be visited. We shall use breadth-first search and a trick due to
  4835. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4836. copying tuples into the ToSpace.
  4837. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4838. copy progresses. The queue is represented by a chunk of contiguous
  4839. memory at the beginning of the ToSpace, using two pointers to track
  4840. the front and the back of the queue. The algorithm starts by copying
  4841. all tuples that are immediately reachable from the root set into the
  4842. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4843. old tuple to indicate that it has been visited. (We discuss the
  4844. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4845. inside the copied tuples in the queue still point back to the
  4846. FromSpace. Once the initial queue has been created, the algorithm
  4847. enters a loop in which it repeatedly processes the tuple at the front
  4848. of the queue and pops it off the queue. To process a tuple, the
  4849. algorithm copies all the tuple that are directly reachable from it to
  4850. the ToSpace, placing them at the back of the queue. The algorithm then
  4851. updates the pointers in the popped tuple so they point to the newly
  4852. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4853. step we copy the tuple whose second element is $42$ to the back of the
  4854. queue. The other pointer goes to a tuple that has already been copied,
  4855. so we do not need to copy it again, but we do need to update the
  4856. pointer to the new location. This can be accomplished by storing a
  4857. \emph{forwarding} pointer to the new location in the old tuple, back
  4858. when we initially copied the tuple into the ToSpace. This completes
  4859. one step of the algorithm. The algorithm continues in this way until
  4860. the front of the queue is empty, that is, until the front catches up
  4861. with the back.
  4862. \begin{figure}[tbp]
  4863. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4864. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4865. \label{fig:cheney}
  4866. \end{figure}
  4867. \subsection{Data Representation}
  4868. \label{sec:data-rep-gc}
  4869. The garbage collector places some requirements on the data
  4870. representations used by our compiler. First, the garbage collector
  4871. needs to distinguish between pointers and other kinds of data. There
  4872. are several ways to accomplish this.
  4873. \begin{enumerate}
  4874. \item Attached a tag to each object that identifies what type of
  4875. object it is~\citep{McCarthy:1960dz}.
  4876. \item Store different types of objects in different
  4877. regions~\citep{Steele:1977ab}.
  4878. \item Use type information from the program to either generate
  4879. type-specific code for collecting or to generate tables that can
  4880. guide the
  4881. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4882. \end{enumerate}
  4883. Dynamically typed languages, such as Lisp, need to tag objects
  4884. anyways, so option 1 is a natural choice for those languages.
  4885. However, $R_3$ is a statically typed language, so it would be
  4886. unfortunate to require tags on every object, especially small and
  4887. pervasive objects like integers and Booleans. Option 3 is the
  4888. best-performing choice for statically typed languages, but comes with
  4889. a relatively high implementation complexity. To keep this chapter to a
  4890. 2-week time budget, we recommend a combination of options 1 and 2,
  4891. with separate strategies used for the stack and the heap.
  4892. Regarding the stack, we recommend using a separate stack for
  4893. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4894. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4895. local variable needs to be spilled and is of type \code{(Vector
  4896. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4897. of the normal procedure call stack. Furthermore, we always spill
  4898. vector-typed variables if they are live during a call to the
  4899. collector, thereby ensuring that no pointers are in registers during a
  4900. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4901. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4902. layout using a root stack. The root stack contains the two pointers
  4903. from the regular stack and also the pointer in the second
  4904. register.
  4905. \begin{figure}[tbp]
  4906. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4907. \caption{Maintaining a root stack to facilitate garbage collection.}
  4908. \label{fig:shadow-stack}
  4909. \end{figure}
  4910. The problem of distinguishing between pointers and other kinds of data
  4911. also arises inside of each tuple. We solve this problem by attaching a
  4912. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4913. in on the tags for two of the tuples in the example from
  4914. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4915. in a big-endian way, from right-to-left, with bit location 0 (the
  4916. least significant bit) on the far right, which corresponds to the
  4917. directional of the x86 shifting instructions \key{salq} (shift
  4918. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4919. specifying which elements of the tuple are pointers, the part labeled
  4920. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4921. a pointer and a 0 bit indicates some other kind of data. The pointer
  4922. mask starts at bit location 7. We have limited tuples to a maximum
  4923. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4924. tag also contains two other pieces of information. The length of the
  4925. tuple (number of elements) is stored in bits location 1 through
  4926. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4927. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4928. has not yet been copied. If the bit has value 0 then the entire tag
  4929. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4930. always zero anyways because our tuples are 8-byte aligned.)
  4931. \begin{figure}[tbp]
  4932. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4933. \caption{Representation for tuples in the heap.}
  4934. \label{fig:tuple-rep}
  4935. \end{figure}
  4936. \subsection{Implementation of the Garbage Collector}
  4937. \label{sec:organize-gz}
  4938. The implementation of the garbage collector needs to do a lot of
  4939. bit-level data manipulation and we need to link it with our
  4940. compiler-generated x86 code. Thus, we recommend implementing the
  4941. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4942. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4943. interface to the garbage collector. The \code{initialize} function
  4944. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4945. function is meant to be called near the beginning of \code{main},
  4946. before the rest of the program executes. The \code{initialize}
  4947. function puts the address of the beginning of the FromSpace into the
  4948. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4949. points to the address that is 1-past the last element of the
  4950. FromSpace. (We use half-open intervals to represent chunks of
  4951. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4952. points to the first element of the root stack.
  4953. As long as there is room left in the FromSpace, your generated code
  4954. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4955. %
  4956. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4957. --Jeremy}
  4958. %
  4959. The amount of room left in FromSpace is the difference between the
  4960. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4961. function should be called when there is not enough room left in the
  4962. FromSpace for the next allocation. The \code{collect} function takes
  4963. a pointer to the current top of the root stack (one past the last item
  4964. that was pushed) and the number of bytes that need to be
  4965. allocated. The \code{collect} function performs the copying collection
  4966. and leaves the heap in a state such that the next allocation will
  4967. succeed.
  4968. \begin{figure}[tbp]
  4969. \begin{lstlisting}
  4970. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4971. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4972. int64_t* free_ptr;
  4973. int64_t* fromspace_begin;
  4974. int64_t* fromspace_end;
  4975. int64_t** rootstack_begin;
  4976. \end{lstlisting}
  4977. \caption{The compiler's interface to the garbage collector.}
  4978. \label{fig:gc-header}
  4979. \end{figure}
  4980. \begin{exercise}
  4981. In the file \code{runtime.c} you will find the implementation of
  4982. \code{initialize} and a partial implementation of \code{collect}.
  4983. The \code{collect} function calls another function, \code{cheney},
  4984. to perform the actual copy, and that function is left to the reader
  4985. to implement. The following is the prototype for \code{cheney}.
  4986. \begin{lstlisting}
  4987. static void cheney(int64_t** rootstack_ptr);
  4988. \end{lstlisting}
  4989. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4990. rootstack (which is an array of pointers). The \code{cheney} function
  4991. also communicates with \code{collect} through the global
  4992. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4993. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4994. the ToSpace:
  4995. \begin{lstlisting}
  4996. static int64_t* tospace_begin;
  4997. static int64_t* tospace_end;
  4998. \end{lstlisting}
  4999. The job of the \code{cheney} function is to copy all the live
  5000. objects (reachable from the root stack) into the ToSpace, update
  5001. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5002. update the root stack so that it points to the objects in the
  5003. ToSpace, and finally to swap the global pointers for the FromSpace
  5004. and ToSpace.
  5005. \end{exercise}
  5006. %% \section{Compiler Passes}
  5007. %% \label{sec:code-generation-gc}
  5008. The introduction of garbage collection has a non-trivial impact on our
  5009. compiler passes. We introduce one new compiler pass called
  5010. \code{expose-allocation} and make non-trivial changes to
  5011. \code{type-check}, \code{flatten}, \code{select-instructions},
  5012. \code{allocate-registers}, and \code{print-x86}. The following
  5013. program will serve as our running example. It creates two tuples, one
  5014. nested inside the other. Both tuples have length one. The example then
  5015. accesses the element in the inner tuple tuple via two vector
  5016. references.
  5017. % tests/s2_17.rkt
  5018. \begin{lstlisting}
  5019. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5020. \end{lstlisting}
  5021. Next we proceed to discuss the new \code{expose-allocation} pass.
  5022. \section{Expose Allocation}
  5023. \label{sec:expose-allocation}
  5024. The pass \code{expose-allocation} lowers the \code{vector} creation
  5025. form into a conditional call to the collector followed by the
  5026. allocation. We choose to place the \code{expose-allocation} pass
  5027. before \code{flatten} because \code{expose-allocation} introduces new
  5028. variables, which can be done locally with \code{let}, but \code{let}
  5029. is gone after \code{flatten}. In the following, we show the
  5030. transformation for the \code{vector} form into let-bindings for the
  5031. initializing expressions, by a conditional \code{collect}, an
  5032. \code{allocate}, and the initialization of the vector.
  5033. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  5034. total bytes need to be allocated for the vector, which is 8 for the
  5035. tag plus \itm{len} times 8.)
  5036. \begin{lstlisting}
  5037. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5038. |$\Longrightarrow$|
  5039. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5040. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5041. (global-value fromspace_end))
  5042. (void)
  5043. (collect |\itm{bytes}|))])
  5044. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5045. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5046. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5047. |$v$|) ... )))) ...)
  5048. \end{lstlisting}
  5049. (In the above, we suppressed all of the \code{has-type} forms in the
  5050. output for the sake of readability.) The placement of the initializing
  5051. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  5052. the sequence of \code{vector-set!}'s is important, as those expressions
  5053. may trigger garbage collection and we do not want an allocated but
  5054. uninitialized tuple to be present during a garbage collection.
  5055. The output of \code{expose-allocation} is a language that extends
  5056. $R_3$ with the three new forms that we use above in the translation of
  5057. \code{vector}.
  5058. \[
  5059. \begin{array}{lcl}
  5060. \Exp &::=& \cdots
  5061. \mid (\key{collect} \,\itm{int})
  5062. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5063. \mid (\key{global-value} \,\itm{name})
  5064. \end{array}
  5065. \]
  5066. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  5067. %% the beginning of the program which will instruct the garbage collector
  5068. %% to set up the FromSpace, ToSpace, and all the global variables. The
  5069. %% two arguments of \code{initialize} specify the initial allocated space
  5070. %% for the root stack and for the heap.
  5071. %
  5072. %% The \code{expose-allocation} pass annotates all of the local variables
  5073. %% in the \code{program} form with their type.
  5074. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5075. \code{expose-allocation} pass on our running example.
  5076. \begin{figure}[tbp]
  5077. % tests/s2_17.rkt
  5078. \begin{lstlisting}
  5079. (vector-ref
  5080. (vector-ref
  5081. (let ([vecinit7976
  5082. (let ([vecinit7972 42])
  5083. (let ([collectret7974
  5084. (if (< (+ free_ptr 16) fromspace_end)
  5085. (void)
  5086. (collect 16);
  5087. )])
  5088. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5089. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5090. alloc7971)
  5091. )
  5092. )
  5093. )
  5094. ])
  5095. (let ([collectret7978
  5096. (if (< (+ free_ptr 16) fromspace_end)
  5097. (void)
  5098. (collect 16);
  5099. )])
  5100. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5101. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5102. alloc7975)
  5103. )
  5104. )
  5105. )
  5106. 0)
  5107. 0)
  5108. \end{lstlisting}
  5109. \caption{Output of the \code{expose-allocation} pass, minus
  5110. all of the \code{HasType} forms.}
  5111. \label{fig:expose-alloc-output}
  5112. \end{figure}
  5113. %\clearpage
  5114. \section{Explicate Control and the $C_2$ language}
  5115. \label{sec:explicate-control-r3}
  5116. \begin{figure}[tp]
  5117. \fbox{
  5118. \begin{minipage}{0.96\textwidth}
  5119. \small
  5120. \[
  5121. \begin{array}{lcl}
  5122. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5123. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5124. \Exp &::= & \gray{ \Atm \mid \READ{} \mid \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5125. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5126. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type})
  5127. \mid \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5128. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5129. &\mid& (\key{GlobalValue} \,\itm{name}) \mid (\key{Void}) \\
  5130. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} \mid \RETURN{\Exp} }
  5131. \mid (\key{Collect} \,\itm{int}) \\
  5132. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }\\
  5133. &\mid& \gray{ \GOTO{\itm{label}} }\\
  5134. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5135. C_2 & ::= & \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)^{+}}}
  5136. \end{array}
  5137. \]
  5138. \end{minipage}
  5139. }
  5140. \caption{The abstract syntax of the $C_2$ language.
  5141. TODO: UPDATE}
  5142. \label{fig:c2-syntax}
  5143. \end{figure}
  5144. The output of \code{explicate-control} is a program in the
  5145. intermediate language $C_2$, whose syntax is defined in
  5146. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  5147. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5148. \key{global-value} expressions and the \code{collect} statement. The
  5149. \code{explicate-control} pass can treat these new forms much like the
  5150. other forms.
  5151. \section{Uncover Locals}
  5152. \label{sec:uncover-locals-r3}
  5153. Recall that the \code{explicate-control} function collects all of the
  5154. local variables so that it can store them in the $\itm{info}$ field of
  5155. the \code{Program} structure. Also recall that we need to know the
  5156. types of all the local variables for purposes of identifying the root
  5157. set for the garbage collector. Thus, we create a pass named
  5158. \code{uncover-locals} to collect not just the variables but the
  5159. variables and their types in the form of an alist. Thanks
  5160. to the \code{HasType} nodes, the types are readily available in the
  5161. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  5162. \code{uncover-locals} pass on the running example.
  5163. \begin{figure}[tbp]
  5164. % tests/s2_17.rkt
  5165. \begin{lstlisting}
  5166. program:
  5167. locals:
  5168. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5169. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5170. collectret7974 : 'Void, initret7977 : 'Void,
  5171. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5172. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5173. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  5174. initret7973 : 'Void,
  5175. block7991:
  5176. (collect 16);
  5177. goto block7989;
  5178. block7990:
  5179. collectret7974 = (void);
  5180. goto block7989;
  5181. block7989:
  5182. alloc7971 = (allocate 1 (Vector Integer));
  5183. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5184. vecinit7976 = alloc7971;
  5185. tmp7982 = free_ptr;
  5186. tmp7983 = (+ tmp7982 16);
  5187. tmp7984 = fromspace_end;
  5188. if (< tmp7983 tmp7984) then
  5189. goto block7987;
  5190. else
  5191. goto block7988;
  5192. block7988:
  5193. (collect 16);
  5194. goto block7986;
  5195. block7987:
  5196. collectret7978 = (void);
  5197. goto block7986;
  5198. block7986:
  5199. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5200. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5201. tmp7985 = (vector-ref alloc7975 0);
  5202. return (vector-ref tmp7985 0);
  5203. start:
  5204. vecinit7972 = 42;
  5205. tmp7979 = free_ptr;
  5206. tmp7980 = (+ tmp7979 16);
  5207. tmp7981 = fromspace_end;
  5208. if (< tmp7980 tmp7981) then
  5209. goto block7990;
  5210. else
  5211. goto block7991;
  5212. \end{lstlisting}
  5213. \caption{Output of \code{uncover-locals} for the running example.}
  5214. \label{fig:uncover-locals-r3}
  5215. \end{figure}
  5216. \clearpage
  5217. \section{Select Instructions}
  5218. \label{sec:select-instructions-gc}
  5219. %% void (rep as zero)
  5220. %% allocate
  5221. %% collect (callq collect)
  5222. %% vector-ref
  5223. %% vector-set!
  5224. %% global-value (postpone)
  5225. In this pass we generate x86 code for most of the new operations that
  5226. were needed to compile tuples, including \code{allocate},
  5227. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  5228. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  5229. The \code{vector-ref} and \code{vector-set!} forms translate into
  5230. \code{movq} instructions with the appropriate \key{deref}. (The
  5231. plus one is to get past the tag at the beginning of the tuple
  5232. representation.)
  5233. \begin{lstlisting}
  5234. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  5235. |$\Longrightarrow$|
  5236. (movq |$\itm{vec}'$| (reg r11))
  5237. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  5238. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  5239. |$\Longrightarrow$|
  5240. (movq |$\itm{vec}'$| (reg r11))
  5241. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  5242. (movq (int 0) |$\itm{lhs}$|)
  5243. \end{lstlisting}
  5244. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  5245. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  5246. register \code{r11} ensures that offsets are only performed with
  5247. register operands. This requires removing \code{r11} from
  5248. consideration by the register allocating.
  5249. We compile the \code{allocate} form to operations on the
  5250. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5251. is the next free address in the FromSpace, so we move it into the
  5252. \itm{lhs} and then move it forward by enough space for the tuple being
  5253. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5254. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5255. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5256. how the tag is organized. We recommend using the Racket operations
  5257. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  5258. The type annotation in the \code{vector} form is used to determine the
  5259. pointer mask region of the tag.
  5260. \begin{lstlisting}
  5261. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5262. |$\Longrightarrow$|
  5263. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5264. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5265. (movq |$\itm{lhs}'$| (reg r11))
  5266. (movq (int |$\itm{tag}$|) (deref r11 0))
  5267. \end{lstlisting}
  5268. The \code{collect} form is compiled to a call to the \code{collect}
  5269. function in the runtime. The arguments to \code{collect} are the top
  5270. of the root stack and the number of bytes that need to be allocated.
  5271. We shall use a dedicated register, \code{r15}, to store the pointer to
  5272. the top of the root stack. So \code{r15} is not available for use by
  5273. the register allocator.
  5274. \begin{lstlisting}
  5275. (collect |$\itm{bytes}$|)
  5276. |$\Longrightarrow$|
  5277. (movq (reg r15) (reg rdi))
  5278. (movq |\itm{bytes}| (reg rsi))
  5279. (callq collect)
  5280. \end{lstlisting}
  5281. \begin{figure}[tp]
  5282. \fbox{
  5283. \begin{minipage}{0.96\textwidth}
  5284. \[
  5285. \begin{array}{lcl}
  5286. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5287. \mid (\key{deref}\,\Reg\,\Int) } \\
  5288. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5289. \mid (\key{global-value}\; \itm{name}) \\
  5290. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5291. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5292. (\key{subq} \; \Arg\; \Arg) \mid
  5293. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5294. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5295. (\key{pushq}\;\Arg) \mid
  5296. (\key{popq}\;\Arg) \mid
  5297. (\key{retq})} \\
  5298. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5299. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5300. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5301. \mid (\key{jmp} \; \itm{label})
  5302. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5303. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5304. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5305. \end{array}
  5306. \]
  5307. \end{minipage}
  5308. }
  5309. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5310. \label{fig:x86-2}
  5311. \end{figure}
  5312. The syntax of the $x86_2$ language is defined in
  5313. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5314. of the form for global variables.
  5315. %
  5316. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5317. \code{select-instructions} pass on the running example.
  5318. \begin{figure}[tbp]
  5319. \centering
  5320. \begin{minipage}{0.75\textwidth}
  5321. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5322. (program
  5323. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5324. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5325. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5326. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5327. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5328. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5329. ((block63 . (block ()
  5330. (movq (reg r15) (reg rdi))
  5331. (movq (int 16) (reg rsi))
  5332. (callq collect)
  5333. (jmp block61)))
  5334. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5335. (block61 . (block ()
  5336. (movq (global-value free_ptr) (var alloc43))
  5337. (addq (int 16) (global-value free_ptr))
  5338. (movq (var alloc43) (reg r11))
  5339. (movq (int 3) (deref r11 0))
  5340. (movq (var alloc43) (reg r11))
  5341. (movq (var vecinit44) (deref r11 8))
  5342. (movq (int 0) (var initret45))
  5343. (movq (var alloc43) (var vecinit48))
  5344. (movq (global-value free_ptr) (var tmp54))
  5345. (movq (var tmp54) (var tmp55))
  5346. (addq (int 16) (var tmp55))
  5347. (movq (global-value fromspace_end) (var tmp56))
  5348. (cmpq (var tmp56) (var tmp55))
  5349. (jmp-if l block59)
  5350. (jmp block60)))
  5351. (block60 . (block ()
  5352. (movq (reg r15) (reg rdi))
  5353. (movq (int 16) (reg rsi))
  5354. (callq collect)
  5355. (jmp block58))
  5356. (block59 . (block ()
  5357. (movq (int 0) (var collectret50))
  5358. (jmp block58)))
  5359. (block58 . (block ()
  5360. (movq (global-value free_ptr) (var alloc47))
  5361. (addq (int 16) (global-value free_ptr))
  5362. (movq (var alloc47) (reg r11))
  5363. (movq (int 131) (deref r11 0))
  5364. (movq (var alloc47) (reg r11))
  5365. (movq (var vecinit48) (deref r11 8))
  5366. (movq (int 0) (var initret49))
  5367. (movq (var alloc47) (reg r11))
  5368. (movq (deref r11 8) (var tmp57))
  5369. (movq (var tmp57) (reg r11))
  5370. (movq (deref r11 8) (reg rax))
  5371. (jmp conclusion)))
  5372. (start . (block ()
  5373. (movq (int 42) (var vecinit44))
  5374. (movq (global-value free_ptr) (var tmp51))
  5375. (movq (var tmp51) (var tmp52))
  5376. (addq (int 16) (var tmp52))
  5377. (movq (global-value fromspace_end) (var tmp53))
  5378. (cmpq (var tmp53) (var tmp52))
  5379. (jmp-if l block62)
  5380. (jmp block63))))))
  5381. \end{lstlisting}
  5382. \end{minipage}
  5383. \caption{Output of the \code{select-instructions} pass.}
  5384. \label{fig:select-instr-output-gc}
  5385. \end{figure}
  5386. \clearpage
  5387. \section{Register Allocation}
  5388. \label{sec:reg-alloc-gc}
  5389. As discussed earlier in this chapter, the garbage collector needs to
  5390. access all the pointers in the root set, that is, all variables that
  5391. are vectors. It will be the responsibility of the register allocator
  5392. to make sure that:
  5393. \begin{enumerate}
  5394. \item the root stack is used for spilling vector-typed variables, and
  5395. \item if a vector-typed variable is live during a call to the
  5396. collector, it must be spilled to ensure it is visible to the
  5397. collector.
  5398. \end{enumerate}
  5399. The later responsibility can be handled during construction of the
  5400. inference graph, by adding interference edges between the call-live
  5401. vector-typed variables and all the callee-saved registers. (They
  5402. already interfere with the caller-saved registers.) The type
  5403. information for variables is in the \code{program} form, so we
  5404. recommend adding another parameter to the \code{build-interference}
  5405. function to communicate this alist.
  5406. The spilling of vector-typed variables to the root stack can be
  5407. handled after graph coloring, when choosing how to assign the colors
  5408. (integers) to registers and stack locations. The \code{program} output
  5409. of this pass changes to also record the number of spills to the root
  5410. stack.
  5411. % build-interference
  5412. %
  5413. % callq
  5414. % extra parameter for var->type assoc. list
  5415. % update 'program' and 'if'
  5416. % allocate-registers
  5417. % allocate spilled vectors to the rootstack
  5418. % don't change color-graph
  5419. \section{Print x86}
  5420. \label{sec:print-x86-gc}
  5421. \margincomment{\scriptsize We need to show the translation to x86 and what
  5422. to do about global-value. \\ --Jeremy}
  5423. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5424. \code{print-x86} pass on the running example. In the prelude and
  5425. conclusion of the \code{main} function, we treat the root stack very
  5426. much like the regular stack in that we move the root stack pointer
  5427. (\code{r15}) to make room for all of the spills to the root stack,
  5428. except that the root stack grows up instead of down. For the running
  5429. example, there was just one spill so we increment \code{r15} by 8
  5430. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5431. One issue that deserves special care is that there may be a call to
  5432. \code{collect} prior to the initializing assignments for all the
  5433. variables in the root stack. We do not want the garbage collector to
  5434. accidentally think that some uninitialized variable is a pointer that
  5435. needs to be followed. Thus, we zero-out all locations on the root
  5436. stack in the prelude of \code{main}. In
  5437. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5438. %
  5439. \lstinline{movq $0, (%r15)}
  5440. %
  5441. accomplishes this task. The garbage collector tests each root to see
  5442. if it is null prior to dereferencing it.
  5443. \begin{figure}[htbp]
  5444. \begin{minipage}[t]{0.5\textwidth}
  5445. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5446. _block58:
  5447. movq _free_ptr(%rip), %rcx
  5448. addq $16, _free_ptr(%rip)
  5449. movq %rcx, %r11
  5450. movq $131, 0(%r11)
  5451. movq %rcx, %r11
  5452. movq -8(%r15), %rax
  5453. movq %rax, 8(%r11)
  5454. movq $0, %rdx
  5455. movq %rcx, %r11
  5456. movq 8(%r11), %rcx
  5457. movq %rcx, %r11
  5458. movq 8(%r11), %rax
  5459. jmp _conclusion
  5460. _block59:
  5461. movq $0, %rcx
  5462. jmp _block58
  5463. _block62:
  5464. movq $0, %rcx
  5465. jmp _block61
  5466. _block60:
  5467. movq %r15, %rdi
  5468. movq $16, %rsi
  5469. callq _collect
  5470. jmp _block58
  5471. _block63:
  5472. movq %r15, %rdi
  5473. movq $16, %rsi
  5474. callq _collect
  5475. jmp _block61
  5476. _start:
  5477. movq $42, %rbx
  5478. movq _free_ptr(%rip), %rdx
  5479. addq $16, %rdx
  5480. movq _fromspace_end(%rip), %rcx
  5481. cmpq %rcx, %rdx
  5482. jl _block62
  5483. jmp _block63
  5484. \end{lstlisting}
  5485. \end{minipage}
  5486. \begin{minipage}[t]{0.45\textwidth}
  5487. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5488. _block61:
  5489. movq _free_ptr(%rip), %rcx
  5490. addq $16, _free_ptr(%rip)
  5491. movq %rcx, %r11
  5492. movq $3, 0(%r11)
  5493. movq %rcx, %r11
  5494. movq %rbx, 8(%r11)
  5495. movq $0, %rdx
  5496. movq %rcx, -8(%r15)
  5497. movq _free_ptr(%rip), %rcx
  5498. addq $16, %rcx
  5499. movq _fromspace_end(%rip), %rdx
  5500. cmpq %rdx, %rcx
  5501. jl _block59
  5502. jmp _block60
  5503. .globl _main
  5504. _main:
  5505. pushq %rbp
  5506. movq %rsp, %rbp
  5507. pushq %r12
  5508. pushq %rbx
  5509. pushq %r13
  5510. pushq %r14
  5511. subq $0, %rsp
  5512. movq $16384, %rdi
  5513. movq $16, %rsi
  5514. callq _initialize
  5515. movq _rootstack_begin(%rip), %r15
  5516. movq $0, (%r15)
  5517. addq $8, %r15
  5518. jmp _start
  5519. _conclusion:
  5520. subq $8, %r15
  5521. addq $0, %rsp
  5522. popq %r14
  5523. popq %r13
  5524. popq %rbx
  5525. popq %r12
  5526. popq %rbp
  5527. retq
  5528. \end{lstlisting}
  5529. \end{minipage}
  5530. \caption{Output of the \code{print-x86} pass.}
  5531. \label{fig:print-x86-output-gc}
  5532. \end{figure}
  5533. \margincomment{\scriptsize Suggest an implementation strategy
  5534. in which the students first do the code gen and test that
  5535. without GC (just use a big heap), then after that is debugged,
  5536. implement the GC. \\ --Jeremy}
  5537. \begin{figure}[p]
  5538. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5539. \node (R3) at (0,2) {\large $R_3$};
  5540. \node (R3-2) at (3,2) {\large $R_3$};
  5541. \node (R3-3) at (6,2) {\large $R_3$};
  5542. \node (R3-4) at (9,2) {\large $R_3$};
  5543. \node (R3-5) at (12,2) {\large $R_3$};
  5544. \node (C2-4) at (3,0) {\large $C_2$};
  5545. \node (C2-3) at (6,0) {\large $C_2$};
  5546. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5547. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5548. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5549. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5550. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5551. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5552. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5553. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5554. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5555. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5556. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5557. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5558. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5559. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5560. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5561. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5562. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5563. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5564. \end{tikzpicture}
  5565. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5566. \label{fig:R3-passes}
  5567. \end{figure}
  5568. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5569. for the compilation of $R_3$.
  5570. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5571. \chapter{Functions}
  5572. \label{ch:functions}
  5573. This chapter studies the compilation of functions at the level of
  5574. abstraction of the C language. This corresponds to a subset of Typed
  5575. Racket in which only top-level function definitions are allowed. These
  5576. kind of functions are an important stepping stone to implementing
  5577. lexically-scoped functions in the form of \key{lambda} abstractions,
  5578. which is the topic of Chapter~\ref{ch:lambdas}.
  5579. \section{The $R_4$ Language}
  5580. The syntax for function definitions and function application is shown
  5581. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5582. Programs in $R_4$ start with zero or more function definitions. The
  5583. function names from these definitions are in-scope for the entire
  5584. program, including all other function definitions (so the ordering of
  5585. function definitions does not matter). The syntax for function
  5586. application does not include an explicit keyword, which is error prone
  5587. when using \code{match}. To alleviate this problem, we change the
  5588. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5589. during type checking.
  5590. Functions are first-class in the sense that a function pointer is data
  5591. and can be stored in memory or passed as a parameter to another
  5592. function. Thus, we introduce a function type, written
  5593. \begin{lstlisting}
  5594. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5595. \end{lstlisting}
  5596. for a function whose $n$ parameters have the types $\Type_1$ through
  5597. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5598. these functions (with respect to Racket functions) is that they are
  5599. not lexically scoped. That is, the only external entities that can be
  5600. referenced from inside a function body are other globally-defined
  5601. functions. The syntax of $R_4$ prevents functions from being nested
  5602. inside each other.
  5603. \begin{figure}[tp]
  5604. \centering
  5605. \fbox{
  5606. \begin{minipage}{0.96\textwidth}
  5607. \[
  5608. \begin{array}{lcl}
  5609. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5610. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5611. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5612. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5613. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5614. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5615. \mid (\key{and}\;\Exp\;\Exp)
  5616. \mid (\key{or}\;\Exp\;\Exp)
  5617. \mid (\key{not}\;\Exp)} \\
  5618. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5619. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5620. (\key{vector-ref}\;\Exp\;\Int)} \\
  5621. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5622. &\mid& (\Exp \; \Exp^{*}) \\
  5623. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5624. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5625. \end{array}
  5626. \]
  5627. \end{minipage}
  5628. }
  5629. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5630. with functions.}
  5631. \label{fig:r4-syntax}
  5632. \end{figure}
  5633. The program in Figure~\ref{fig:r4-function-example} is a
  5634. representative example of defining and using functions in $R_4$. We
  5635. define a function \code{map-vec} that applies some other function
  5636. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5637. vector containing the results. We also define a function \code{add1}
  5638. that does what its name suggests. The program then applies
  5639. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5640. \code{(vector 1 42)}, from which we return the \code{42}.
  5641. \begin{figure}[tbp]
  5642. \begin{lstlisting}
  5643. (program ()
  5644. (define (map-vec [f : (Integer -> Integer)]
  5645. [v : (Vector Integer Integer)])
  5646. : (Vector Integer Integer)
  5647. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5648. (define (add1 [x : Integer]) : Integer
  5649. (+ x 1))
  5650. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5651. )
  5652. \end{lstlisting}
  5653. \caption{Example of using functions in $R_4$.}
  5654. \label{fig:r4-function-example}
  5655. \end{figure}
  5656. The definitional interpreter for $R_4$ is in
  5657. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5658. responsible for setting up the mutual recursion between the top-level
  5659. function definitions. We use the classic back-patching approach that
  5660. uses mutable variables and makes two passes over the function
  5661. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5662. top-level environment using a mutable cons cell for each function
  5663. definition. Note that the \code{lambda} value for each function is
  5664. incomplete; it does not yet include the environment. Once the
  5665. top-level environment is constructed, we then iterate over it and
  5666. update the \code{lambda} value's to use the top-level environment.
  5667. \begin{figure}[tp]
  5668. \begin{lstlisting}
  5669. (define (interp-exp env)
  5670. (lambda (e)
  5671. (define recur (interp-exp env))
  5672. (match e
  5673. ...
  5674. [`(,fun ,args ...)
  5675. (define arg-vals (for/list ([e args]) (recur e)))
  5676. (define fun-val (recur fun))
  5677. (match fun-val
  5678. [`(lambda (,xs ...) ,body ,fun-env)
  5679. (define new-env (append (map cons xs arg-vals) fun-env))
  5680. ((interp-exp new-env) body)]
  5681. [else (error "interp-exp, expected function, not" fun-val)])]
  5682. [else (error 'interp-exp "unrecognized expression")]
  5683. )))
  5684. (define (interp-def d)
  5685. (match d
  5686. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5687. (mcons f `(lambda ,xs ,body ()))]
  5688. ))
  5689. (define (interp-R4 p)
  5690. (match p
  5691. [`(program ,ds ... ,body)
  5692. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5693. (for/list ([b top-level])
  5694. (set-mcdr! b (match (mcdr b)
  5695. [`(lambda ,xs ,body ())
  5696. `(lambda ,xs ,body ,top-level)])))
  5697. ((interp-exp top-level) body))]
  5698. ))
  5699. \end{lstlisting}
  5700. \caption{Interpreter for the $R_4$ language.}
  5701. \label{fig:interp-R4}
  5702. \end{figure}
  5703. \section{Functions in x86}
  5704. \label{sec:fun-x86}
  5705. \margincomment{\tiny Make sure callee-saved registers are discussed
  5706. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5707. \margincomment{\tiny Talk about the return address on the
  5708. stack and what callq and retq does.\\ --Jeremy }
  5709. The x86 architecture provides a few features to support the
  5710. implementation of functions. We have already seen that x86 provides
  5711. labels so that one can refer to the location of an instruction, as is
  5712. needed for jump instructions. Labels can also be used to mark the
  5713. beginning of the instructions for a function. Going further, we can
  5714. obtain the address of a label by using the \key{leaq} instruction and
  5715. \key{rip}-relative addressing. For example, the following puts the
  5716. address of the \code{add1} label into the \code{rbx} register.
  5717. \begin{lstlisting}
  5718. leaq add1(%rip), %rbx
  5719. \end{lstlisting}
  5720. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5721. instruction for jumping to a function whose location is given by a
  5722. label. Here we instead will be jumping to a function whose location is
  5723. given by an address, that is, we need to make an \emph{indirect
  5724. function call}. The x86 syntax is to give the register name prefixed
  5725. with an asterisk.
  5726. \begin{lstlisting}
  5727. callq *%rbx
  5728. \end{lstlisting}
  5729. \subsection{Calling Conventions}
  5730. The \code{callq} instruction provides partial support for implementing
  5731. functions, but it does not handle (1) parameter passing, (2) saving
  5732. and restoring frames on the procedure call stack, or (3) determining
  5733. how registers are shared by different functions. These issues require
  5734. coordination between the caller and the callee, which is often
  5735. assembly code written by different programmers or generated by
  5736. different compilers. As a result, people have developed
  5737. \emph{conventions} that govern how functions calls are performed.
  5738. Here we shall use the same conventions used by the \code{gcc}
  5739. compiler~\citep{Matz:2013aa}.
  5740. Regarding (1) parameter passing, the convention is to use the
  5741. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5742. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5743. than six arguments, then the convention is to use space on the frame
  5744. of the caller for the rest of the arguments. However, to ease the
  5745. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5746. we shall arrange to never have more than six arguments.
  5747. %
  5748. The register \code{rax} is for the return value of the function.
  5749. Regarding (2) frames and the procedure call stack, the convention is
  5750. that the stack grows down, with each function call using a chunk of
  5751. space called a frame. The caller sets the stack pointer, register
  5752. \code{rsp}, to the last data item in its frame. The callee must not
  5753. change anything in the caller's frame, that is, anything that is at or
  5754. above the stack pointer. The callee is free to use locations that are
  5755. below the stack pointer.
  5756. Regarding (3) the sharing of registers between different functions,
  5757. recall from Section~\ref{sec:calling-conventions} that the registers
  5758. are divided into two groups, the caller-saved registers and the
  5759. callee-saved registers. The caller should assume that all the
  5760. caller-saved registers get overwritten with arbitrary values by the
  5761. callee. Thus, the caller should either 1) not put values that are live
  5762. across a call in caller-saved registers, or 2) save and restore values
  5763. that are live across calls. We shall recommend option 1). On the flip
  5764. side, if the callee wants to use a callee-saved register, the callee
  5765. must save the contents of those registers on their stack frame and
  5766. then put them back prior to returning to the caller. The base
  5767. pointer, register \code{rbp}, is used as a point-of-reference within a
  5768. frame, so that each local variable can be accessed at a fixed offset
  5769. from the base pointer.
  5770. %
  5771. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5772. frames.
  5773. %% If we were to use stack arguments, they would be between the
  5774. %% caller locals and the callee return address.
  5775. \begin{figure}[tbp]
  5776. \centering
  5777. \begin{tabular}{r|r|l|l} \hline
  5778. Caller View & Callee View & Contents & Frame \\ \hline
  5779. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5780. 0(\key{\%rbp}) & & old \key{rbp} \\
  5781. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5782. \ldots & & \ldots \\
  5783. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5784. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5785. \ldots & & \ldots \\
  5786. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5787. %% & & \\
  5788. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5789. %% & \ldots & \ldots \\
  5790. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5791. \hline
  5792. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5793. & 0(\key{\%rbp}) & old \key{rbp} \\
  5794. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5795. & \ldots & \ldots \\
  5796. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5797. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5798. & \ldots & \ldots \\
  5799. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5800. \end{tabular}
  5801. \caption{Memory layout of caller and callee frames.}
  5802. \label{fig:call-frames}
  5803. \end{figure}
  5804. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5805. %% local variables and for storing the values of callee-saved registers
  5806. %% (we shall refer to all of these collectively as ``locals''), and that
  5807. %% at the beginning of a function we move the stack pointer \code{rsp}
  5808. %% down to make room for them.
  5809. %% We recommend storing the local variables
  5810. %% first and then the callee-saved registers, so that the local variables
  5811. %% can be accessed using \code{rbp} the same as before the addition of
  5812. %% functions.
  5813. %% To make additional room for passing arguments, we shall
  5814. %% move the stack pointer even further down. We count how many stack
  5815. %% arguments are needed for each function call that occurs inside the
  5816. %% body of the function and find their maximum. Adding this number to the
  5817. %% number of locals gives us how much the \code{rsp} should be moved at
  5818. %% the beginning of the function. In preparation for a function call, we
  5819. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5820. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5821. %% so on.
  5822. %% Upon calling the function, the stack arguments are retrieved by the
  5823. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5824. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5825. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5826. %% the layout of the caller and callee frames. Notice how important it is
  5827. %% that we correctly compute the maximum number of arguments needed for
  5828. %% function calls; if that number is too small then the arguments and
  5829. %% local variables will smash into each other!
  5830. \subsection{Efficient Tail Calls}
  5831. \label{sec:tail-call}
  5832. In general, the amount of stack space used by a program is determined
  5833. by the longest chain of nested function calls. That is, if function
  5834. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5835. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5836. $n$ can grow quite large in the case of recursive or mutually
  5837. recursive functions. However, in some cases we can arrange to use only
  5838. constant space, i.e. $O(1)$, instead of $O(n)$.
  5839. If a function call is the last action in a function body, then that
  5840. call is said to be a \emph{tail call}. In such situations, the frame
  5841. of the caller is no longer needed, so we can pop the caller's frame
  5842. before making the tail call. With this approach, a recursive function
  5843. that only makes tail calls will only use $O(1)$ stack space.
  5844. Functional languages like Racket typically rely heavily on recursive
  5845. functions, so they typically guarantee that all tail calls will be
  5846. optimized in this way.
  5847. However, some care is needed with regards to argument passing in tail
  5848. calls. As mentioned above, for arguments beyond the sixth, the
  5849. convention is to use space in the caller's frame for passing
  5850. arguments. But here we've popped the caller's frame and can no longer
  5851. use it. Another alternative is to use space in the callee's frame for
  5852. passing arguments. However, this option is also problematic because
  5853. the caller and callee's frame overlap in memory. As we begin to copy
  5854. the arguments from their sources in the caller's frame, the target
  5855. locations in the callee's frame might overlap with the sources for
  5856. later arguments! We solve this problem by not using the stack for
  5857. parameter passing but instead use the heap, as we describe in the
  5858. Section~\ref{sec:limit-functions-r4}.
  5859. As mentioned above, for a tail call we pop the caller's frame prior to
  5860. making the tail call. The instructions for popping a frame are the
  5861. instructions that we usually place in the conclusion of a
  5862. function. Thus, we also need to place such code immediately before
  5863. each tail call. These instructions include restoring the callee-saved
  5864. registers, so it is good that the argument passing registers are all
  5865. caller-saved registers.
  5866. One last note regarding which instruction to use to make the tail
  5867. call. When the callee is finished, it should not return to the current
  5868. function, but it should return to the function that called the current
  5869. one. Thus, the return address that is already on the stack is the
  5870. right one, and we should not use \key{callq} to make the tail call, as
  5871. that would unnecessarily overwrite the return address. Instead we can
  5872. simply use the \key{jmp} instruction. Like the indirect function call,
  5873. we write an indirect jump with a register prefixed with an asterisk.
  5874. We recommend using \code{rax} to hold the jump target because the
  5875. preceding ``conclusion'' overwrites just about everything else.
  5876. \begin{lstlisting}
  5877. jmp *%rax
  5878. \end{lstlisting}
  5879. %% Now that we have a good understanding of functions as they appear in
  5880. %% $R_4$ and the support for functions in x86, we need to plan the
  5881. %% changes to our compiler, that is, do we need any new passes and/or do
  5882. %% we need to change any existing passes? Also, do we need to add new
  5883. %% kinds of AST nodes to any of the intermediate languages?
  5884. \section{Shrink $R_4$}
  5885. \label{sec:shrink-r4}
  5886. The \code{shrink} pass performs a couple minor modifications to the
  5887. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5888. field to each function definition:
  5889. \begin{lstlisting}
  5890. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5891. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5892. \end{lstlisting}
  5893. and introduces an explicit \code{main} function.\\
  5894. \begin{tabular}{lll}
  5895. \begin{minipage}{0.45\textwidth}
  5896. \begin{lstlisting}
  5897. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5898. \end{lstlisting}
  5899. \end{minipage}
  5900. &
  5901. $\Rightarrow$
  5902. &
  5903. \begin{minipage}{0.45\textwidth}
  5904. \begin{lstlisting}
  5905. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5906. \end{lstlisting}
  5907. \end{minipage}
  5908. \end{tabular} \\
  5909. where $\itm{mainDef}$ is
  5910. \begin{lstlisting}
  5911. (define (main) : Integer () |$\Exp'$|)
  5912. \end{lstlisting}
  5913. \section{Reveal Functions}
  5914. \label{sec:reveal-functions-r4}
  5915. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5916. compilation because it conflates the use of function names and local
  5917. variables. This is a problem because we need to compile the use of a
  5918. function name differently than the use of a local variable; we need to
  5919. use \code{leaq} to convert the function name (a label in x86) to an
  5920. address in a register. Thus, it is a good idea to create a new pass
  5921. that changes function references from just a symbol $f$ to
  5922. \code{(fun-ref $f$)}. A good name for this pass is
  5923. \code{reveal-functions} and the output language, $F_1$, is defined in
  5924. Figure~\ref{fig:f1-syntax}.
  5925. \begin{figure}[tp]
  5926. \centering
  5927. \fbox{
  5928. \begin{minipage}{0.96\textwidth}
  5929. \[
  5930. \begin{array}{lcl}
  5931. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5932. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5933. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5934. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5935. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5936. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5937. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5938. (\key{vector-ref}\;\Exp\;\Int)} \\
  5939. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5940. (\key{app}\; \Exp \; \Exp^{*})} \\
  5941. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5942. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5943. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5944. \end{array}
  5945. \]
  5946. \end{minipage}
  5947. }
  5948. \caption{The $F_1$ language, an extension of $R_4$
  5949. (Figure~\ref{fig:r4-syntax}).}
  5950. \label{fig:f1-syntax}
  5951. \end{figure}
  5952. %% Distinguishing between calls in tail position and non-tail position
  5953. %% requires the pass to have some notion of context. We recommend using
  5954. %% two mutually recursive functions, one for processing expressions in
  5955. %% tail position and another for the rest.
  5956. Placing this pass after \code{uniquify} is a good idea, because it
  5957. will make sure that there are no local variables and functions that
  5958. share the same name. On the other hand, \code{reveal-functions} needs
  5959. to come before the \code{explicate-control} pass because that pass
  5960. will help us compile \code{fun-ref} into assignment statements.
  5961. \section{Limit Functions}
  5962. \label{sec:limit-functions-r4}
  5963. This pass transforms functions so that they have at most six
  5964. parameters and transforms all function calls so that they pass at most
  5965. six arguments. A simple strategy for imposing an argument limit of
  5966. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5967. into a vector, making that subsequent vector the $n$th argument.
  5968. \begin{tabular}{lll}
  5969. \begin{minipage}{0.2\textwidth}
  5970. \begin{lstlisting}
  5971. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5972. \end{lstlisting}
  5973. \end{minipage}
  5974. &
  5975. $\Rightarrow$
  5976. &
  5977. \begin{minipage}{0.4\textwidth}
  5978. \begin{lstlisting}
  5979. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5980. \end{lstlisting}
  5981. \end{minipage}
  5982. \end{tabular}
  5983. In the body of the function, all occurrences of the $i$th argument in
  5984. which $i>5$ must be replaced with a \code{vector-ref}.
  5985. \section{Remove Complex Operators and Operands}
  5986. \label{sec:rco-r4}
  5987. The primary decisions to make for this pass is whether to classify
  5988. \code{fun-ref} and \code{app} as either simple or complex
  5989. expressions. Recall that a simple expression will eventually end up as
  5990. just an ``immediate'' argument of an x86 instruction. Function
  5991. application will be translated to a sequence of instructions, so
  5992. \code{app} must be classified as complex expression. Regarding
  5993. \code{fun-ref}, as discussed above, the function label needs to
  5994. be converted to an address using the \code{leaq} instruction. Thus,
  5995. even though \code{fun-ref} seems rather simple, it needs to be
  5996. classified as a complex expression so that we generate an assignment
  5997. statement with a left-hand side that can serve as the target of the
  5998. \code{leaq}.
  5999. \section{Explicate Control and the $C_3$ language}
  6000. \label{sec:explicate-control-r4}
  6001. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  6002. \key{explicate-control}. The three mutually recursive functions for
  6003. this pass, for assignment, tail, and predicate contexts, must all be
  6004. updated with cases for \code{fun-ref} and \code{app}. In
  6005. assignment and predicate contexts, \code{app} becomes \code{call},
  6006. whereas in tail position \code{app} becomes \code{tailcall}. We
  6007. recommend defining a new function for processing function definitions.
  6008. This code is similar to the case for \code{program} in $R_3$. The
  6009. top-level \code{explicate-control} function that handles the
  6010. \code{program} form of $R_4$ can then apply this new function to all
  6011. the function definitions.
  6012. \begin{figure}[tp]
  6013. \fbox{
  6014. \begin{minipage}{0.96\textwidth}
  6015. \[
  6016. \begin{array}{lcl}
  6017. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6018. \\
  6019. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6020. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6021. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6022. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6023. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6024. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6025. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  6026. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6027. \mid (\key{collect} \,\itm{int}) }\\
  6028. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6029. &\mid& \gray{(\key{goto}\,\itm{label})
  6030. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6031. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  6032. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  6033. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  6034. \end{array}
  6035. \]
  6036. \end{minipage}
  6037. }
  6038. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  6039. \label{fig:c3-syntax}
  6040. \end{figure}
  6041. \section{Uncover Locals}
  6042. \label{sec:uncover-locals-r4}
  6043. The function for processing $\Tail$ should be updated with a case for
  6044. \code{tailcall}. We also recommend creating a new function for
  6045. processing function definitions. Each function definition in $C_3$ has
  6046. its own set of local variables, so the code for function definitions
  6047. should be similar to the case for the \code{program} form in $C_2$.
  6048. \section{Select Instructions}
  6049. \label{sec:select-r4}
  6050. The output of select instructions is a program in the x86$_3$
  6051. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6052. \begin{figure}[tp]
  6053. \fbox{
  6054. \begin{minipage}{0.96\textwidth}
  6055. \[
  6056. \begin{array}{lcl}
  6057. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6058. \mid (\key{deref}\,\Reg\,\Int) } \\
  6059. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6060. \mid (\key{global-value}\; \itm{name}) } \\
  6061. &\mid& (\key{fun-ref}\; \itm{label})\\
  6062. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6063. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6064. (\key{subq} \; \Arg\; \Arg) \mid
  6065. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6066. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6067. (\key{pushq}\;\Arg) \mid
  6068. (\key{popq}\;\Arg) \mid
  6069. (\key{retq}) } \\
  6070. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6071. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6072. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6073. \mid (\key{jmp} \; \itm{label})
  6074. \mid (\key{j}\itm{cc} \; \itm{label})
  6075. \mid (\key{label} \; \itm{label}) } \\
  6076. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6077. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6078. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  6079. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  6080. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  6081. \end{array}
  6082. \]
  6083. \end{minipage}
  6084. }
  6085. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6086. \label{fig:x86-3}
  6087. \end{figure}
  6088. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  6089. as follows: \\
  6090. \begin{tabular}{lll}
  6091. \begin{minipage}{0.45\textwidth}
  6092. \begin{lstlisting}
  6093. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  6094. \end{lstlisting}
  6095. \end{minipage}
  6096. &
  6097. $\Rightarrow$
  6098. &
  6099. \begin{minipage}{0.4\textwidth}
  6100. \begin{lstlisting}
  6101. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  6102. \end{lstlisting}
  6103. \end{minipage}
  6104. \end{tabular} \\
  6105. Regarding function definitions, we need to remove their parameters and
  6106. instead perform parameter passing in terms of the conventions
  6107. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6108. in the argument passing registers, and inside the function we should
  6109. generate a \code{movq} instruction for each parameter, to move the
  6110. argument value from the appropriate register to a new local variable
  6111. with the same name as the old parameter.
  6112. Next, consider the compilation of function calls, which have the
  6113. following form upon input to \code{select-instructions}.
  6114. \begin{lstlisting}
  6115. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6116. \end{lstlisting}
  6117. In the mirror image of handling the parameters of function
  6118. definitions, the arguments \itm{args} need to be moved to the argument
  6119. passing registers.
  6120. %
  6121. Once the instructions for parameter passing have been generated, the
  6122. function call itself can be performed with an indirect function call,
  6123. for which I recommend creating the new instruction
  6124. \code{indirect-callq}. Of course, the return value from the function
  6125. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6126. \begin{lstlisting}
  6127. (indirect-callq |\itm{fun}|)
  6128. (movq (reg rax) |\itm{lhs}|)
  6129. \end{lstlisting}
  6130. Regarding tail calls, the parameter passing is the same as non-tail
  6131. calls: generate instructions to move the arguments into to the
  6132. argument passing registers. After that we need to pop the frame from
  6133. the procedure call stack. However, we do not yet know how big the
  6134. frame is; that gets determined during register allocation. So instead
  6135. of generating those instructions here, we invent a new instruction
  6136. that means ``pop the frame and then do an indirect jump'', which we
  6137. name \code{tail-jmp}.
  6138. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6139. using the label \code{start} for the initial block of a program, and
  6140. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6141. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  6142. can be compiled to an assignment to \code{rax} followed by a jump to
  6143. \code{conclusion}. With the addition of function definitions, we will
  6144. have a starting block and conclusion for each function, but their
  6145. labels need to be unique. We recommend prepending the function's name
  6146. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6147. labels. (Alternatively, one could \code{gensym} labels for the start
  6148. and conclusion and store them in the $\itm{info}$ field of the
  6149. function definition.)
  6150. \section{Uncover Live}
  6151. %% The rest of the passes need only minor modifications to handle the new
  6152. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6153. %% \code{leaq}.
  6154. Inside \code{uncover-live}, when computing the $W$ set (written
  6155. variables) for an \code{indirect-callq} instruction, we recommend
  6156. including all the caller-saved registers, which will have the affect
  6157. of making sure that no caller-saved register actually needs to be
  6158. saved.
  6159. \section{Build Interference Graph}
  6160. With the addition of function definitions, we compute an interference
  6161. graph for each function (not just one for the whole program).
  6162. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6163. spill vector-typed variables that are live during a call to the
  6164. \code{collect}. With the addition of functions to our language, we
  6165. need to revisit this issue. Many functions will perform allocation and
  6166. therefore have calls to the collector inside of them. Thus, we should
  6167. not only spill a vector-typed variable when it is live during a call
  6168. to \code{collect}, but we should spill the variable if it is live
  6169. during any function call. Thus, in the \code{build-interference} pass,
  6170. we recommend adding interference edges between call-live vector-typed
  6171. variables and the callee-saved registers (in addition to the usual
  6172. addition of edges between call-live variables and the caller-saved
  6173. registers).
  6174. \section{Patch Instructions}
  6175. In \code{patch-instructions}, you should deal with the x86
  6176. idiosyncrasy that the destination argument of \code{leaq} must be a
  6177. register. Additionally, you should ensure that the argument of
  6178. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6179. code generation more convenient, because we will be trampling many
  6180. registers before the tail call (as explained below).
  6181. \section{Print x86}
  6182. For the \code{print-x86} pass, we recommend the following translations:
  6183. \begin{lstlisting}
  6184. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6185. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6186. \end{lstlisting}
  6187. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6188. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6189. is what we will want to do, but before the jump we need to pop the
  6190. current frame. So we need to restore the state of the registers to the
  6191. point they were at when the current function was called. This
  6192. sequence of instructions is the same as the code for the conclusion of
  6193. a function.
  6194. Note that your \code{print-x86} pass needs to add the code for saving
  6195. and restoring callee-saved registers, if you have not already
  6196. implemented that. This is necessary when generating code for function
  6197. definitions.
  6198. \section{An Example Translation}
  6199. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6200. function in $R_4$ to x86. The figure also includes the results of the
  6201. \code{explicate-control} and \code{select-instructions} passes. We
  6202. have omitted the \code{has-type} AST nodes for readability. Can you
  6203. see any ways to improve the translation?
  6204. \begin{figure}[tbp]
  6205. \begin{tabular}{ll}
  6206. \begin{minipage}{0.45\textwidth}
  6207. % s3_2.rkt
  6208. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6209. (program
  6210. (define (add [x : Integer]
  6211. [y : Integer])
  6212. : Integer (+ x y))
  6213. (add 40 2))
  6214. \end{lstlisting}
  6215. $\Downarrow$
  6216. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6217. (program ()
  6218. (define (add86 [x87 : Integer]
  6219. [y88 : Integer]) : Integer ()
  6220. ((add86start . (return (+ x87 y88)))))
  6221. (define (main) : Integer ()
  6222. ((mainstart .
  6223. (seq (assign tmp89 (fun-ref add86))
  6224. (tailcall tmp89 40 2))))))
  6225. \end{lstlisting}
  6226. \end{minipage}
  6227. &
  6228. $\Rightarrow$
  6229. \begin{minipage}{0.5\textwidth}
  6230. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6231. (program ()
  6232. (define (add86)
  6233. ((locals (x87 . Integer) (y88 . Integer))
  6234. (num-params . 2))
  6235. ((add86start .
  6236. (block ()
  6237. (movq (reg rcx) (var x87))
  6238. (movq (reg rdx) (var y88))
  6239. (movq (var x87) (reg rax))
  6240. (addq (var y88) (reg rax))
  6241. (jmp add86conclusion)))))
  6242. (define (main)
  6243. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6244. (num-params . 0))
  6245. ((mainstart .
  6246. (block ()
  6247. (leaq (fun-ref add86) (var tmp89))
  6248. (movq (int 40) (reg rcx))
  6249. (movq (int 2) (reg rdx))
  6250. (tail-jmp (var tmp89))))))
  6251. \end{lstlisting}
  6252. $\Downarrow$
  6253. \end{minipage}
  6254. \end{tabular}
  6255. \begin{tabular}{lll}
  6256. \begin{minipage}{0.3\textwidth}
  6257. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6258. _add90start:
  6259. movq %rcx, %rsi
  6260. movq %rdx, %rcx
  6261. movq %rsi, %rax
  6262. addq %rcx, %rax
  6263. jmp _add90conclusion
  6264. .globl _add90
  6265. .align 16
  6266. _add90:
  6267. pushq %rbp
  6268. movq %rsp, %rbp
  6269. pushq %r12
  6270. pushq %rbx
  6271. pushq %r13
  6272. pushq %r14
  6273. subq $0, %rsp
  6274. jmp _add90start
  6275. _add90conclusion:
  6276. addq $0, %rsp
  6277. popq %r14
  6278. popq %r13
  6279. popq %rbx
  6280. popq %r12
  6281. subq $0, %r15
  6282. popq %rbp
  6283. retq
  6284. \end{lstlisting}
  6285. \end{minipage}
  6286. &
  6287. \begin{minipage}{0.3\textwidth}
  6288. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6289. _mainstart:
  6290. leaq _add90(%rip), %rsi
  6291. movq $40, %rcx
  6292. movq $2, %rdx
  6293. movq %rsi, %rax
  6294. addq $0, %rsp
  6295. popq %r14
  6296. popq %r13
  6297. popq %rbx
  6298. popq %r12
  6299. subq $0, %r15
  6300. popq %rbp
  6301. jmp *%rax
  6302. .globl _main
  6303. .align 16
  6304. _main:
  6305. pushq %rbp
  6306. movq %rsp, %rbp
  6307. pushq %r12
  6308. pushq %rbx
  6309. pushq %r13
  6310. pushq %r14
  6311. subq $0, %rsp
  6312. movq $16384, %rdi
  6313. movq $16, %rsi
  6314. callq _initialize
  6315. movq _rootstack_begin(%rip), %r15
  6316. jmp _mainstart
  6317. \end{lstlisting}
  6318. \end{minipage}
  6319. &
  6320. \begin{minipage}{0.3\textwidth}
  6321. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6322. _mainconclusion:
  6323. addq $0, %rsp
  6324. popq %r14
  6325. popq %r13
  6326. popq %rbx
  6327. popq %r12
  6328. subq $0, %r15
  6329. popq %rbp
  6330. retq
  6331. \end{lstlisting}
  6332. \end{minipage}
  6333. \end{tabular}
  6334. \caption{Example compilation of a simple function to x86.}
  6335. \label{fig:add-fun}
  6336. \end{figure}
  6337. \begin{exercise}\normalfont
  6338. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6339. Create 5 new programs that use functions, including examples that pass
  6340. functions and return functions from other functions and including
  6341. recursive functions. Test your compiler on these new programs and all
  6342. of your previously created test programs.
  6343. \end{exercise}
  6344. \begin{figure}[p]
  6345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6346. \node (R4) at (0,2) {\large $R_4$};
  6347. \node (R4-2) at (3,2) {\large $R_4$};
  6348. \node (R4-3) at (6,2) {\large $R_4$};
  6349. \node (F1-1) at (12,0) {\large $F_1$};
  6350. \node (F1-2) at (9,0) {\large $F_1$};
  6351. \node (F1-3) at (6,0) {\large $F_1$};
  6352. \node (F1-4) at (3,0) {\large $F_1$};
  6353. \node (C3-1) at (6,-2) {\large $C_3$};
  6354. \node (C3-2) at (3,-2) {\large $C_3$};
  6355. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6356. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6357. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6358. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6359. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6360. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6361. \path[->,bend left=15] (R4) edge [above] node
  6362. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6363. \path[->,bend left=15] (R4-2) edge [above] node
  6364. {\ttfamily\footnotesize uniquify} (R4-3);
  6365. \path[->,bend left=15] (R4-3) edge [right] node
  6366. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6367. \path[->,bend left=15] (F1-1) edge [below] node
  6368. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6369. \path[->,bend right=15] (F1-2) edge [above] node
  6370. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6371. \path[->,bend right=15] (F1-3) edge [above] node
  6372. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6373. \path[->,bend left=15] (F1-4) edge [right] node
  6374. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6375. \path[->,bend left=15] (C3-1) edge [below] node
  6376. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6377. \path[->,bend right=15] (C3-2) edge [left] node
  6378. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6379. \path[->,bend left=15] (x86-2) edge [left] node
  6380. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6381. \path[->,bend right=15] (x86-2-1) edge [below] node
  6382. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6383. \path[->,bend right=15] (x86-2-2) edge [left] node
  6384. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6385. \path[->,bend left=15] (x86-3) edge [above] node
  6386. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6387. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6388. \end{tikzpicture}
  6389. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6390. \label{fig:R4-passes}
  6391. \end{figure}
  6392. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6393. the compilation of $R_4$.
  6394. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6395. \chapter{Lexically Scoped Functions}
  6396. \label{ch:lambdas}
  6397. This chapter studies lexically scoped functions as they appear in
  6398. functional languages such as Racket. By lexical scoping we mean that a
  6399. function's body may refer to variables whose binding site is outside
  6400. of the function, in an enclosing scope.
  6401. %
  6402. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6403. anonymous function defined using the \key{lambda} form. The body of
  6404. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6405. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6406. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6407. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6408. returned from the function \code{f}. Below the definition of \code{f},
  6409. we have two calls to \code{f} with different arguments for \code{x},
  6410. first \code{5} then \code{3}. The functions returned from \code{f} are
  6411. bound to variables \code{g} and \code{h}. Even though these two
  6412. functions were created by the same \code{lambda}, they are really
  6413. different functions because they use different values for
  6414. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6415. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6416. the result of this program is \code{42}.
  6417. \begin{figure}[btp]
  6418. % s4_6.rkt
  6419. \begin{lstlisting}
  6420. (define (f [x : Integer]) : (Integer -> Integer)
  6421. (let ([y 4])
  6422. (lambda: ([z : Integer]) : Integer
  6423. (+ x (+ y z)))))
  6424. (let ([g (f 5)])
  6425. (let ([h (f 3)])
  6426. (+ (g 11) (h 15))))
  6427. \end{lstlisting}
  6428. \caption{Example of a lexically scoped function.}
  6429. \label{fig:lexical-scoping}
  6430. \end{figure}
  6431. \section{The $R_5$ Language}
  6432. The syntax for this language with anonymous functions and lexical
  6433. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6434. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6435. for function application. In this chapter we shall describe how to
  6436. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6437. into a combination of functions (as in $R_4$) and tuples (as in
  6438. $R_3$).
  6439. \begin{figure}[tp]
  6440. \centering
  6441. \fbox{
  6442. \begin{minipage}{0.96\textwidth}
  6443. \[
  6444. \begin{array}{lcl}
  6445. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6446. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6447. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6448. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6449. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6450. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6451. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6452. \mid (\key{and}\;\Exp\;\Exp)
  6453. \mid (\key{or}\;\Exp\;\Exp)
  6454. \mid (\key{not}\;\Exp) } \\
  6455. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6456. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6457. (\key{vector-ref}\;\Exp\;\Int)} \\
  6458. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6459. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6460. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6461. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6462. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6463. \end{array}
  6464. \]
  6465. \end{minipage}
  6466. }
  6467. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6468. with \key{lambda}.}
  6469. \label{fig:r5-syntax}
  6470. \end{figure}
  6471. To compile lexically-scoped functions to top-level function
  6472. definitions, the compiler will need to provide special treatment to
  6473. variable occurrences such as \code{x} and \code{y} in the body of the
  6474. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6475. of $R_4$ may not refer to variables defined outside the function. To
  6476. identify such variable occurrences, we review the standard notion of
  6477. free variable.
  6478. \begin{definition}
  6479. A variable is \emph{free with respect to an expression} $e$ if the
  6480. variable occurs inside $e$ but does not have an enclosing binding in
  6481. $e$.
  6482. \end{definition}
  6483. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6484. free with respect to the expression \code{(+ x (+ y z))}. On the
  6485. other hand, only \code{x} and \code{y} are free with respect to the
  6486. following expression because \code{z} is bound by the \code{lambda}.
  6487. \begin{lstlisting}
  6488. (lambda: ([z : Integer]) : Integer
  6489. (+ x (+ y z)))
  6490. \end{lstlisting}
  6491. Once we have identified the free variables of a \code{lambda}, we need
  6492. to arrange for some way to transport, at runtime, the values of those
  6493. variables from the point where the \code{lambda} was created to the
  6494. point where the \code{lambda} is applied. Referring again to
  6495. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6496. needs to be used in the application of \code{g} to \code{11}, but the
  6497. binding of \code{x} to \code{3} needs to be used in the application of
  6498. \code{h} to \code{15}. An efficient solution to the problem, due to
  6499. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6500. free variables together with the function pointer for the lambda's
  6501. code, an arrangement called a \emph{flat closure} (which we shorten to
  6502. just ``closure'') . Fortunately, we have all the ingredients to make
  6503. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6504. Chapter~\ref{ch:functions} gave us function pointers. The function
  6505. pointer shall reside at index $0$ and the values for free variables
  6506. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6507. the two closures created by the two calls to \code{f} in
  6508. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6509. the same \key{lambda}, they share the same function pointer but differ
  6510. in the values for the free variable \code{x}.
  6511. \begin{figure}[tbp]
  6512. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6513. \caption{Example closure representation for the \key{lambda}'s
  6514. in Figure~\ref{fig:lexical-scoping}.}
  6515. \label{fig:closures}
  6516. \end{figure}
  6517. \section{Interpreting $R_5$}
  6518. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6519. $R_5$. The clause for \key{lambda} saves the current environment
  6520. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6521. the environment from the \key{lambda}, the \code{lam-env}, when
  6522. interpreting the body of the \key{lambda}. The \code{lam-env}
  6523. environment is extended with the mapping of parameters to argument
  6524. values.
  6525. \begin{figure}[tbp]
  6526. \begin{lstlisting}
  6527. (define (interp-exp env)
  6528. (lambda (e)
  6529. (define recur (interp-exp env))
  6530. (match e
  6531. ...
  6532. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6533. `(lambda ,xs ,body ,env)]
  6534. [`(app ,fun ,args ...)
  6535. (define fun-val ((interp-exp env) fun))
  6536. (define arg-vals (map (interp-exp env) args))
  6537. (match fun-val
  6538. [`(lambda (,xs ...) ,body ,lam-env)
  6539. (define new-env (append (map cons xs arg-vals) lam-env))
  6540. ((interp-exp new-env) body)]
  6541. [else (error "interp-exp, expected function, not" fun-val)])]
  6542. [else (error 'interp-exp "unrecognized expression")]
  6543. )))
  6544. \end{lstlisting}
  6545. \caption{Interpreter for $R_5$.}
  6546. \label{fig:interp-R5}
  6547. \end{figure}
  6548. \section{Type Checking $R_5$}
  6549. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6550. \key{lambda} form. The body of the \key{lambda} is checked in an
  6551. environment that includes the current environment (because it is
  6552. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6553. require the body's type to match the declared return type.
  6554. \begin{figure}[tbp]
  6555. \begin{lstlisting}
  6556. (define (typecheck-R5 env)
  6557. (lambda (e)
  6558. (match e
  6559. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6560. (define new-env (append (map cons xs Ts) env))
  6561. (define bodyT ((typecheck-R5 new-env) body))
  6562. (cond [(equal? rT bodyT)
  6563. `(,@Ts -> ,rT)]
  6564. [else
  6565. (error "mismatch in return type" bodyT rT)])]
  6566. ...
  6567. )))
  6568. \end{lstlisting}
  6569. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6570. \label{fig:typecheck-R5}
  6571. \end{figure}
  6572. \section{Closure Conversion}
  6573. The compiling of lexically-scoped functions into top-level function
  6574. definitions is accomplished in the pass \code{convert-to-closures}
  6575. that comes after \code{reveal-functions} and before
  6576. \code{limit-functions}.
  6577. As usual, we shall implement the pass as a recursive function over the
  6578. AST. All of the action is in the clauses for \key{lambda} and
  6579. \key{app}. We transform a \key{lambda} expression into an expression
  6580. that creates a closure, that is, creates a vector whose first element
  6581. is a function pointer and the rest of the elements are the free
  6582. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6583. generated to identify the function.
  6584. \begin{tabular}{lll}
  6585. \begin{minipage}{0.4\textwidth}
  6586. \begin{lstlisting}
  6587. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6588. \end{lstlisting}
  6589. \end{minipage}
  6590. &
  6591. $\Rightarrow$
  6592. &
  6593. \begin{minipage}{0.4\textwidth}
  6594. \begin{lstlisting}
  6595. (vector |\itm{name}| |\itm{fvs}| ...)
  6596. \end{lstlisting}
  6597. \end{minipage}
  6598. \end{tabular} \\
  6599. %
  6600. In addition to transforming each \key{lambda} into a \key{vector}, we
  6601. must create a top-level function definition for each \key{lambda}, as
  6602. shown below.\\
  6603. \begin{minipage}{0.8\textwidth}
  6604. \begin{lstlisting}
  6605. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6606. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6607. ...
  6608. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6609. |\itm{body'}|)...))
  6610. \end{lstlisting}
  6611. \end{minipage}\\
  6612. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6613. parameters are the normal parameters of the \key{lambda}. The types
  6614. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6615. underscore is a dummy type because it is rather difficult to give a
  6616. type to the function in the closure's type, and it does not matter.
  6617. The sequence of \key{let} forms bind the free variables to their
  6618. values obtained from the closure.
  6619. We transform function application into code that retrieves the
  6620. function pointer from the closure and then calls the function, passing
  6621. in the closure as the first argument. We bind $e'$ to a temporary
  6622. variable to avoid code duplication.
  6623. \begin{tabular}{lll}
  6624. \begin{minipage}{0.3\textwidth}
  6625. \begin{lstlisting}
  6626. (app |$e$| |\itm{es}| ...)
  6627. \end{lstlisting}
  6628. \end{minipage}
  6629. &
  6630. $\Rightarrow$
  6631. &
  6632. \begin{minipage}{0.5\textwidth}
  6633. \begin{lstlisting}
  6634. (let ([|\itm{tmp}| |$e'$|])
  6635. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6636. \end{lstlisting}
  6637. \end{minipage}
  6638. \end{tabular} \\
  6639. There is also the question of what to do with top-level function
  6640. definitions. To maintain a uniform translation of function
  6641. application, we turn function references into closures.
  6642. \begin{tabular}{lll}
  6643. \begin{minipage}{0.3\textwidth}
  6644. \begin{lstlisting}
  6645. (fun-ref |$f$|)
  6646. \end{lstlisting}
  6647. \end{minipage}
  6648. &
  6649. $\Rightarrow$
  6650. &
  6651. \begin{minipage}{0.5\textwidth}
  6652. \begin{lstlisting}
  6653. (vector (fun-ref |$f$|))
  6654. \end{lstlisting}
  6655. \end{minipage}
  6656. \end{tabular} \\
  6657. %
  6658. The top-level function definitions need to be updated as well to take
  6659. an extra closure parameter.
  6660. \section{An Example Translation}
  6661. \label{sec:example-lambda}
  6662. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6663. conversion for the example program demonstrating lexical scoping that
  6664. we discussed at the beginning of this chapter.
  6665. \begin{figure}[h]
  6666. \begin{minipage}{0.8\textwidth}
  6667. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6668. (program
  6669. (define (f [x : Integer]) : (Integer -> Integer)
  6670. (let ([y 4])
  6671. (lambda: ([z : Integer]) : Integer
  6672. (+ x (+ y z)))))
  6673. (let ([g (f 5)])
  6674. (let ([h (f 3)])
  6675. (+ (g 11) (h 15)))))
  6676. \end{lstlisting}
  6677. $\Downarrow$
  6678. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6679. (program (type Integer)
  6680. (define (f (x : Integer)) : (Integer -> Integer)
  6681. (let ((y 4))
  6682. (lambda: ((z : Integer)) : Integer
  6683. (+ x (+ y z)))))
  6684. (let ((g (app (fun-ref f) 5)))
  6685. (let ((h (app (fun-ref f) 3)))
  6686. (+ (app g 11) (app h 15)))))
  6687. \end{lstlisting}
  6688. $\Downarrow$
  6689. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6690. (program (type Integer)
  6691. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6692. (let ((y 4))
  6693. (vector (fun-ref lam.1) x y)))
  6694. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6695. (let ((x (vector-ref clos.2 1)))
  6696. (let ((y (vector-ref clos.2 2)))
  6697. (+ x (+ y z)))))
  6698. (let ((g (let ((t.1 (vector (fun-ref f))))
  6699. (app (vector-ref t.1 0) t.1 5))))
  6700. (let ((h (let ((t.2 (vector (fun-ref f))))
  6701. (app (vector-ref t.2 0) t.2 3))))
  6702. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6703. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6704. \end{lstlisting}
  6705. \end{minipage}
  6706. \caption{Example of closure conversion.}
  6707. \label{fig:lexical-functions-example}
  6708. \end{figure}
  6709. \begin{figure}[p]
  6710. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6711. \node (R4) at (0,2) {\large $R_4$};
  6712. \node (R4-2) at (3,2) {\large $R_4$};
  6713. \node (R4-3) at (6,2) {\large $R_4$};
  6714. \node (F1-1) at (12,0) {\large $F_1$};
  6715. \node (F1-2) at (9,0) {\large $F_1$};
  6716. \node (F1-3) at (6,0) {\large $F_1$};
  6717. \node (F1-4) at (3,0) {\large $F_1$};
  6718. \node (F1-5) at (0,0) {\large $F_1$};
  6719. \node (C3-1) at (6,-2) {\large $C_3$};
  6720. \node (C3-2) at (3,-2) {\large $C_3$};
  6721. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6722. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6723. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6724. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6725. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6726. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6727. \path[->,bend left=15] (R4) edge [above] node
  6728. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6729. \path[->,bend left=15] (R4-2) edge [above] node
  6730. {\ttfamily\footnotesize uniquify} (R4-3);
  6731. \path[->] (R4-3) edge [right] node
  6732. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6733. \path[->,bend left=15] (F1-1) edge [below] node
  6734. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6735. \path[->,bend right=15] (F1-2) edge [above] node
  6736. {\ttfamily\footnotesize limit-functions} (F1-3);
  6737. \path[->,bend right=15] (F1-3) edge [above] node
  6738. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6739. \path[->,bend right=15] (F1-4) edge [above] node
  6740. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6741. \path[->] (F1-5) edge [left] node
  6742. {\ttfamily\footnotesize explicate-control} (C3-1);
  6743. \path[->,bend left=15] (C3-1) edge [below] node
  6744. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6745. \path[->,bend right=15] (C3-2) edge [left] node
  6746. {\ttfamily\footnotesize select-instr.} (x86-2);
  6747. \path[->,bend left=15] (x86-2) edge [left] node
  6748. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6749. \path[->,bend right=15] (x86-2-1) edge [below] node
  6750. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6751. \path[->,bend right=15] (x86-2-2) edge [left] node
  6752. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6753. \path[->,bend left=15] (x86-3) edge [above] node
  6754. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6755. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6756. \end{tikzpicture}
  6757. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6758. functions.}
  6759. \label{fig:R5-passes}
  6760. \end{figure}
  6761. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6762. for the compilation of $R_5$.
  6763. \begin{exercise}\normalfont
  6764. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6765. Create 5 new programs that use \key{lambda} functions and make use of
  6766. lexical scoping. Test your compiler on these new programs and all of
  6767. your previously created test programs.
  6768. \end{exercise}
  6769. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6770. \chapter{Dynamic Typing}
  6771. \label{ch:type-dynamic}
  6772. In this chapter we discuss the compilation of a dynamically typed
  6773. language, named $R_7$, that is a subset of the Racket
  6774. language. (Recall that in the previous chapters we have studied
  6775. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6776. languages, an expression may produce values of differing
  6777. type. Consider the following example with a conditional expression
  6778. that may return a Boolean or an integer depending on the input to the
  6779. program.
  6780. \begin{lstlisting}
  6781. (not (if (eq? (read) 1) #f 0))
  6782. \end{lstlisting}
  6783. Languages that allow expressions to produce different kinds of values
  6784. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6785. such as subtype polymorphism and parametric
  6786. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6787. talking about here does not have a special name, but it is the usual
  6788. kind that arises in dynamically typed languages.
  6789. Another characteristic of dynamically typed languages is that
  6790. primitive operations, such as \code{not}, are often defined to operate
  6791. on many different types of values. In fact, in Racket, the \code{not}
  6792. operator produces a result for any kind of value: given \code{\#f} it
  6793. returns \code{\#t} and given anything else it returns \code{\#f}.
  6794. Furthermore, even when primitive operations restrict their inputs to
  6795. values of a certain type, this restriction is enforced at runtime
  6796. instead of during compilation. For example, the following vector
  6797. reference results in a run-time contract violation.
  6798. \begin{lstlisting}
  6799. (vector-ref (vector 42) #t)
  6800. \end{lstlisting}
  6801. \begin{figure}[tp]
  6802. \centering
  6803. \fbox{
  6804. \begin{minipage}{0.97\textwidth}
  6805. \[
  6806. \begin{array}{rcl}
  6807. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6808. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6809. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6810. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6811. &\mid& \key{\#t} \mid \key{\#f}
  6812. \mid (\key{and}\;\Exp\;\Exp)
  6813. \mid (\key{or}\;\Exp\;\Exp)
  6814. \mid (\key{not}\;\Exp) \\
  6815. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6816. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6817. (\key{vector-ref}\;\Exp\;\Exp) \\
  6818. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6819. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6820. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6821. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6822. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6823. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6824. \end{array}
  6825. \]
  6826. \end{minipage}
  6827. }
  6828. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6829. \label{fig:r7-syntax}
  6830. \end{figure}
  6831. The syntax of $R_7$, our subset of Racket, is defined in
  6832. Figure~\ref{fig:r7-syntax}.
  6833. %
  6834. The definitional interpreter for $R_7$ is given in
  6835. Figure~\ref{fig:interp-R7}.
  6836. \begin{figure}[tbp]
  6837. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6838. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6839. (define (valid-op? op) (member op '(+ - and or not)))
  6840. (define (interp-r7 env)
  6841. (lambda (ast)
  6842. (define recur (interp-r7 env))
  6843. (match ast
  6844. [(? symbol?) (lookup ast env)]
  6845. [(? integer?) `(inject ,ast Integer)]
  6846. [#t `(inject #t Boolean)]
  6847. [#f `(inject #f Boolean)]
  6848. [`(read) `(inject ,(read-fixnum) Integer)]
  6849. [`(lambda (,xs ...) ,body)
  6850. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6851. [`(define (,f ,xs ...) ,body)
  6852. (mcons f `(lambda ,xs ,body))]
  6853. [`(program ,ds ... ,body)
  6854. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6855. (for/list ([b top-level])
  6856. (set-mcdr! b (match (mcdr b)
  6857. [`(lambda ,xs ,body)
  6858. `(inject (lambda ,xs ,body ,top-level)
  6859. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6860. ((interp-r7 top-level) body))]
  6861. [`(vector ,(app recur elts) ...)
  6862. (define tys (map get-tagged-type elts))
  6863. `(inject ,(apply vector elts) (Vector ,@tys))]
  6864. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6865. (match v1
  6866. [`(inject ,vec ,ty)
  6867. (vector-set! vec n v2)
  6868. `(inject (void) Void)])]
  6869. [`(vector-ref ,(app recur v) ,n)
  6870. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6871. [`(let ([,x ,(app recur v)]) ,body)
  6872. ((interp-r7 (cons (cons x v) env)) body)]
  6873. [`(,op ,es ...) #:when (valid-op? op)
  6874. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6875. [`(eq? ,(app recur l) ,(app recur r))
  6876. `(inject ,(equal? l r) Boolean)]
  6877. [`(if ,(app recur q) ,t ,f)
  6878. (match q
  6879. [`(inject #f Boolean) (recur f)]
  6880. [else (recur t)])]
  6881. [`(,(app recur f-val) ,(app recur vs) ...)
  6882. (match f-val
  6883. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6884. (define new-env (append (map cons xs vs) lam-env))
  6885. ((interp-r7 new-env) body)]
  6886. [else (error "interp-r7, expected function, not" f-val)])])))
  6887. \end{lstlisting}
  6888. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6889. \label{fig:interp-R7}
  6890. \end{figure}
  6891. Let us consider how we might compile $R_7$ to x86, thinking about the
  6892. first example above. Our bit-level representation of the Boolean
  6893. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6894. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6895. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6896. general, cannot be determined at compile time, but depends on the
  6897. runtime type of its input, as in the example above that depends on the
  6898. result of \code{(read)}.
  6899. The way around this problem is to include information about a value's
  6900. runtime type in the value itself, so that this information can be
  6901. inspected by operators such as \code{not}. In particular, we shall
  6902. steal the 3 right-most bits from our 64-bit values to encode the
  6903. runtime type. We shall use $001$ to identify integers, $100$ for
  6904. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6905. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6906. define the following auxiliary function.
  6907. \begin{align*}
  6908. \itm{tagof}(\key{Integer}) &= 001 \\
  6909. \itm{tagof}(\key{Boolean}) &= 100 \\
  6910. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6911. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6912. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6913. \itm{tagof}(\key{Void}) &= 101
  6914. \end{align*}
  6915. (We shall say more about the new \key{Vectorof} type shortly.)
  6916. This stealing of 3 bits comes at some
  6917. price: our integers are reduced to ranging from $-2^{60}$ to
  6918. $2^{60}$. The stealing does not adversely affect vectors and
  6919. procedures because those values are addresses, and our addresses are
  6920. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6921. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6922. bits with the tag and we can simply zero-out the tag to recover the
  6923. original address.
  6924. In some sense, these tagged values are a new kind of value. Indeed,
  6925. we can extend our \emph{typed} language with tagged values by adding a
  6926. new type to classify them, called \key{Any}, and with operations for
  6927. creating and using tagged values, yielding the $R_6$ language that we
  6928. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6929. fundamental support for polymorphism and runtime types that we need to
  6930. support dynamic typing.
  6931. There is an interesting interaction between tagged values and garbage
  6932. collection. A variable of type \code{Any} might refer to a vector and
  6933. therefore it might be a root that needs to be inspected and copied
  6934. during garbage collection. Thus, we need to treat variables of type
  6935. \code{Any} in a similar way to variables of type \code{Vector} for
  6936. purposes of register allocation, which we discuss in
  6937. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6938. variable of type \code{Any} is spilled, it must be spilled to the root
  6939. stack. But this means that the garbage collector needs to be able to
  6940. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6941. value that points to a tuple, and (3) a tagged value that is not a
  6942. tuple. We enable this differentiation by choosing not to use the tag
  6943. $000$. Instead, that bit pattern is reserved for identifying plain old
  6944. pointers to tuples. On the other hand, if one of the first three bits
  6945. is set, then we have a tagged value, and inspecting the tag can
  6946. differentiation between vectors ($010$) and the other kinds of values.
  6947. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6948. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6949. extend our compiler to handle the new features of $R_6$
  6950. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6951. \ref{sec:register-allocation-r6}).
  6952. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6953. \label{sec:r6-lang}
  6954. \begin{figure}[tp]
  6955. \centering
  6956. \fbox{
  6957. \begin{minipage}{0.97\textwidth}
  6958. \[
  6959. \begin{array}{lcl}
  6960. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6961. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6962. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6963. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6964. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6965. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6966. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6967. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6968. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6969. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6970. \mid (\key{and}\;\Exp\;\Exp)
  6971. \mid (\key{or}\;\Exp\;\Exp)
  6972. \mid (\key{not}\;\Exp)} \\
  6973. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6974. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6975. (\key{vector-ref}\;\Exp\;\Int)} \\
  6976. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6977. &\mid& \gray{(\Exp \; \Exp^{*})
  6978. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6979. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6980. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6981. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6982. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6983. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6984. \end{array}
  6985. \]
  6986. \end{minipage}
  6987. }
  6988. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6989. with \key{Any}.}
  6990. \label{fig:r6-syntax}
  6991. \end{figure}
  6992. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6993. $(\key{inject}\; e\; T)$ form converts the value produced by
  6994. expression $e$ of type $T$ into a tagged value. The
  6995. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6996. expression $e$ into a value of type $T$ or else halts the program if
  6997. the type tag is equivalent to $T$. We treat
  6998. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6999. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7000. Note that in both \key{inject} and
  7001. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7002. which simplifies the implementation and corresponds with what is
  7003. needed for compiling untyped Racket. The type predicates,
  7004. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7005. if the tag corresponds to the predicate, and return \key{\#t}
  7006. otherwise.
  7007. %
  7008. Selections from the type checker for $R_6$ are shown in
  7009. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7010. Figure~\ref{fig:interp-R6}.
  7011. \begin{figure}[btp]
  7012. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7013. (define (flat-ty? ty) ...)
  7014. (define (typecheck-R6 env)
  7015. (lambda (e)
  7016. (define recur (typecheck-R6 env))
  7017. (match e
  7018. [`(inject ,e ,ty)
  7019. (unless (flat-ty? ty)
  7020. (error "may only inject a value of flat type, not ~a" ty))
  7021. (define-values (new-e e-ty) (recur e))
  7022. (cond
  7023. [(equal? e-ty ty)
  7024. (values `(inject ,new-e ,ty) 'Any)]
  7025. [else
  7026. (error "inject expected ~a to have type ~a" e ty)])]
  7027. [`(project ,e ,ty)
  7028. (unless (flat-ty? ty)
  7029. (error "may only project to a flat type, not ~a" ty))
  7030. (define-values (new-e e-ty) (recur e))
  7031. (cond
  7032. [(equal? e-ty 'Any)
  7033. (values `(project ,new-e ,ty) ty)]
  7034. [else
  7035. (error "project expected ~a to have type Any" e)])]
  7036. [`(vector-ref ,e ,i)
  7037. (define-values (new-e e-ty) (recur e))
  7038. (match e-ty
  7039. [`(Vector ,ts ...) ...]
  7040. [`(Vectorof ,ty)
  7041. (unless (exact-nonnegative-integer? i)
  7042. (error 'type-check "invalid index ~a" i))
  7043. (values `(vector-ref ,new-e ,i) ty)]
  7044. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7045. ...
  7046. )))
  7047. \end{lstlisting}
  7048. \caption{Type checker for parts of the $R_6$ language.}
  7049. \label{fig:typecheck-R6}
  7050. \end{figure}
  7051. % to do: add rules for vector-ref, etc. for Vectorof
  7052. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7053. \begin{figure}[btp]
  7054. \begin{lstlisting}
  7055. (define primitives (set 'boolean? ...))
  7056. (define (interp-op op)
  7057. (match op
  7058. ['boolean? (lambda (v)
  7059. (match v
  7060. [`(tagged ,v1 Boolean) #t]
  7061. [else #f]))]
  7062. ...))
  7063. ;; Equivalence of flat types
  7064. (define (tyeq? t1 t2)
  7065. (match `(,t1 ,t2)
  7066. [`((Vectorof Any) (Vector ,t2s ...))
  7067. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7068. [`((Vector ,t1s ...) (Vectorof Any))
  7069. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7070. [else (equal? t1 t2)]))
  7071. (define (interp-R6 env)
  7072. (lambda (ast)
  7073. (match ast
  7074. [`(inject ,e ,t)
  7075. `(tagged ,((interp-R6 env) e) ,t)]
  7076. [`(project ,e ,t2)
  7077. (define v ((interp-R6 env) e))
  7078. (match v
  7079. [`(tagged ,v1 ,t1)
  7080. (cond [(tyeq? t1 t2)
  7081. v1]
  7082. [else
  7083. (error "in project, type mismatch" t1 t2)])]
  7084. [else
  7085. (error "in project, expected tagged value" v)])]
  7086. ...)))
  7087. \end{lstlisting}
  7088. \caption{Interpreter for $R_6$.}
  7089. \label{fig:interp-R6}
  7090. \end{figure}
  7091. %\clearpage
  7092. \section{Shrinking $R_6$}
  7093. \label{sec:shrink-r6}
  7094. In the \code{shrink} pass we recommend compiling \code{project} into
  7095. an explicit \code{if} expression that uses three new operations:
  7096. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7097. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7098. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7099. value from a tagged value. Finally, the \code{exit} operation ends the
  7100. execution of the program by invoking the operating system's
  7101. \code{exit} function. So the translation for \code{project} is as
  7102. follows. (We have omitted the \code{has-type} AST nodes to make this
  7103. output more readable.)
  7104. \begin{tabular}{lll}
  7105. \begin{minipage}{0.3\textwidth}
  7106. \begin{lstlisting}
  7107. (project |$e$| |$\Type$|)
  7108. \end{lstlisting}
  7109. \end{minipage}
  7110. &
  7111. $\Rightarrow$
  7112. &
  7113. \begin{minipage}{0.5\textwidth}
  7114. \begin{lstlisting}
  7115. (let ([|$\itm{tmp}$| |$e'$|])
  7116. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7117. (value-of-any |$\itm{tmp}$|)
  7118. (exit)))
  7119. \end{lstlisting}
  7120. \end{minipage}
  7121. \end{tabular} \\
  7122. Similarly, we recommend translating the type predicates
  7123. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7124. \section{Instruction Selection for $R_6$}
  7125. \label{sec:select-r6}
  7126. \paragraph{Inject}
  7127. We recommend compiling an \key{inject} as follows if the type is
  7128. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7129. destination to the left by the number of bits specified its source
  7130. argument (in this case $3$, the length of the tag) and it preserves
  7131. the sign of the integer. We use the \key{orq} instruction to combine
  7132. the tag and the value to form the tagged value. \\
  7133. \begin{tabular}{lll}
  7134. \begin{minipage}{0.4\textwidth}
  7135. \begin{lstlisting}
  7136. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7137. \end{lstlisting}
  7138. \end{minipage}
  7139. &
  7140. $\Rightarrow$
  7141. &
  7142. \begin{minipage}{0.5\textwidth}
  7143. \begin{lstlisting}
  7144. (movq |$e'$| |\itm{lhs}'|)
  7145. (salq (int 3) |\itm{lhs}'|)
  7146. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7147. \end{lstlisting}
  7148. \end{minipage}
  7149. \end{tabular} \\
  7150. The instruction selection for vectors and procedures is different
  7151. because their is no need to shift them to the left. The rightmost 3
  7152. bits are already zeros as described above. So we just combine the
  7153. value and the tag using \key{orq}. \\
  7154. \begin{tabular}{lll}
  7155. \begin{minipage}{0.4\textwidth}
  7156. \begin{lstlisting}
  7157. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7158. \end{lstlisting}
  7159. \end{minipage}
  7160. &
  7161. $\Rightarrow$
  7162. &
  7163. \begin{minipage}{0.5\textwidth}
  7164. \begin{lstlisting}
  7165. (movq |$e'$| |\itm{lhs}'|)
  7166. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7167. \end{lstlisting}
  7168. \end{minipage}
  7169. \end{tabular}
  7170. \paragraph{Tag of Any}
  7171. Recall that the \code{tag-of-any} operation extracts the type tag from
  7172. a value of type \code{Any}. The type tag is the bottom three bits, so
  7173. we obtain the tag by taking the bitwise-and of the value with $111$
  7174. ($7$ in decimal).
  7175. \begin{tabular}{lll}
  7176. \begin{minipage}{0.4\textwidth}
  7177. \begin{lstlisting}
  7178. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7179. \end{lstlisting}
  7180. \end{minipage}
  7181. &
  7182. $\Rightarrow$
  7183. &
  7184. \begin{minipage}{0.5\textwidth}
  7185. \begin{lstlisting}
  7186. (movq |$e'$| |\itm{lhs}'|)
  7187. (andq (int 7) |\itm{lhs}'|)
  7188. \end{lstlisting}
  7189. \end{minipage}
  7190. \end{tabular}
  7191. \paragraph{Value of Any}
  7192. Like \key{inject}, the instructions for \key{value-of-any} are
  7193. different depending on whether the type $T$ is a pointer (vector or
  7194. procedure) or not (Integer or Boolean). The following shows the
  7195. instruction selection for Integer and Boolean. We produce an untagged
  7196. value by shifting it to the right by 3 bits.
  7197. %
  7198. \\
  7199. \begin{tabular}{lll}
  7200. \begin{minipage}{0.4\textwidth}
  7201. \begin{lstlisting}
  7202. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7203. \end{lstlisting}
  7204. \end{minipage}
  7205. &
  7206. $\Rightarrow$
  7207. &
  7208. \begin{minipage}{0.5\textwidth}
  7209. \begin{lstlisting}
  7210. (movq |$e'$| |\itm{lhs}'|)
  7211. (sarq (int 3) |\itm{lhs}'|)
  7212. \end{lstlisting}
  7213. \end{minipage}
  7214. \end{tabular} \\
  7215. %
  7216. In the case for vectors and procedures, there is no need to
  7217. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7218. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7219. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7220. \code{movq} into the destination $\itm{lhs}$. We then generate
  7221. \code{andq} with the tagged value to get the desired result. \\
  7222. %
  7223. \begin{tabular}{lll}
  7224. \begin{minipage}{0.4\textwidth}
  7225. \begin{lstlisting}
  7226. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7227. \end{lstlisting}
  7228. \end{minipage}
  7229. &
  7230. $\Rightarrow$
  7231. &
  7232. \begin{minipage}{0.5\textwidth}
  7233. \begin{lstlisting}
  7234. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7235. (andq |$e'$| |\itm{lhs}'|)
  7236. \end{lstlisting}
  7237. \end{minipage}
  7238. \end{tabular}
  7239. %% \paragraph{Type Predicates} We leave it to the reader to
  7240. %% devise a sequence of instructions to implement the type predicates
  7241. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7242. \section{Register Allocation for $R_6$}
  7243. \label{sec:register-allocation-r6}
  7244. As mentioned above, a variable of type \code{Any} might refer to a
  7245. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7246. of type \code{Any} in the same way that it treats variables of type
  7247. \code{Vector} for purposes of garbage collection. In particular,
  7248. \begin{itemize}
  7249. \item If a variable of type \code{Any} is live during a function call,
  7250. then it must be spilled. One way to accomplish this is to augment
  7251. the pass \code{build-interference} to mark all variables that are
  7252. live after a \code{callq} as interfering with all the registers.
  7253. \item If a variable of type \code{Any} is spilled, it must be spilled
  7254. to the root stack instead of the normal procedure call stack.
  7255. \end{itemize}
  7256. \begin{exercise}\normalfont
  7257. Expand your compiler to handle $R_6$ as discussed in the last few
  7258. sections. Create 5 new programs that use the \code{Any} type and the
  7259. new operations (\code{inject}, \code{project}, \code{boolean?},
  7260. etc.). Test your compiler on these new programs and all of your
  7261. previously created test programs.
  7262. \end{exercise}
  7263. \section{Compiling $R_7$ to $R_6$}
  7264. \label{sec:compile-r7}
  7265. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7266. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7267. given a subexpression $e$ of $R_7$, the pass will produce an
  7268. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7269. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7270. the Boolean \code{\#t}, which must be injected to produce an
  7271. expression of type \key{Any}.
  7272. %
  7273. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7274. addition, is representative of compilation for many operations: the
  7275. arguments have type \key{Any} and must be projected to \key{Integer}
  7276. before the addition can be performed.
  7277. The compilation of \key{lambda} (third row of
  7278. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7279. produce type annotations: we simply use \key{Any}.
  7280. %
  7281. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7282. has to account for some differences in behavior between $R_7$ and
  7283. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7284. kind of values can be used in various places. For example, the
  7285. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7286. the arguments need not be of the same type (but in that case, the
  7287. result will be \code{\#f}).
  7288. \begin{figure}[btp]
  7289. \centering
  7290. \begin{tabular}{|lll|} \hline
  7291. \begin{minipage}{0.25\textwidth}
  7292. \begin{lstlisting}
  7293. #t
  7294. \end{lstlisting}
  7295. \end{minipage}
  7296. &
  7297. $\Rightarrow$
  7298. &
  7299. \begin{minipage}{0.6\textwidth}
  7300. \begin{lstlisting}
  7301. (inject #t Boolean)
  7302. \end{lstlisting}
  7303. \end{minipage}
  7304. \\[2ex]\hline
  7305. \begin{minipage}{0.25\textwidth}
  7306. \begin{lstlisting}
  7307. (+ |$e_1$| |$e_2$|)
  7308. \end{lstlisting}
  7309. \end{minipage}
  7310. &
  7311. $\Rightarrow$
  7312. &
  7313. \begin{minipage}{0.6\textwidth}
  7314. \begin{lstlisting}
  7315. (inject
  7316. (+ (project |$e'_1$| Integer)
  7317. (project |$e'_2$| Integer))
  7318. Integer)
  7319. \end{lstlisting}
  7320. \end{minipage}
  7321. \\[2ex]\hline
  7322. \begin{minipage}{0.25\textwidth}
  7323. \begin{lstlisting}
  7324. (lambda (|$x_1 \ldots$|) |$e$|)
  7325. \end{lstlisting}
  7326. \end{minipage}
  7327. &
  7328. $\Rightarrow$
  7329. &
  7330. \begin{minipage}{0.6\textwidth}
  7331. \begin{lstlisting}
  7332. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7333. (Any|$\ldots$|Any -> Any))
  7334. \end{lstlisting}
  7335. \end{minipage}
  7336. \\[2ex]\hline
  7337. \begin{minipage}{0.25\textwidth}
  7338. \begin{lstlisting}
  7339. (app |$e_0$| |$e_1 \ldots e_n$|)
  7340. \end{lstlisting}
  7341. \end{minipage}
  7342. &
  7343. $\Rightarrow$
  7344. &
  7345. \begin{minipage}{0.6\textwidth}
  7346. \begin{lstlisting}
  7347. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7348. |$e'_1 \ldots e'_n$|)
  7349. \end{lstlisting}
  7350. \end{minipage}
  7351. \\[2ex]\hline
  7352. \begin{minipage}{0.25\textwidth}
  7353. \begin{lstlisting}
  7354. (vector-ref |$e_1$| |$e_2$|)
  7355. \end{lstlisting}
  7356. \end{minipage}
  7357. &
  7358. $\Rightarrow$
  7359. &
  7360. \begin{minipage}{0.6\textwidth}
  7361. \begin{lstlisting}
  7362. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7363. (let ([tmp2 (project |$e'_2$| Integer)])
  7364. (vector-ref tmp1 tmp2)))
  7365. \end{lstlisting}
  7366. \end{minipage}
  7367. \\[2ex]\hline
  7368. \begin{minipage}{0.25\textwidth}
  7369. \begin{lstlisting}
  7370. (if |$e_1$| |$e_2$| |$e_3$|)
  7371. \end{lstlisting}
  7372. \end{minipage}
  7373. &
  7374. $\Rightarrow$
  7375. &
  7376. \begin{minipage}{0.6\textwidth}
  7377. \begin{lstlisting}
  7378. (if (eq? |$e'_1$| (inject #f Boolean))
  7379. |$e'_3$|
  7380. |$e'_2$|)
  7381. \end{lstlisting}
  7382. \end{minipage}
  7383. \\[2ex]\hline
  7384. \begin{minipage}{0.25\textwidth}
  7385. \begin{lstlisting}
  7386. (eq? |$e_1$| |$e_2$|)
  7387. \end{lstlisting}
  7388. \end{minipage}
  7389. &
  7390. $\Rightarrow$
  7391. &
  7392. \begin{minipage}{0.6\textwidth}
  7393. \begin{lstlisting}
  7394. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7395. \end{lstlisting}
  7396. \end{minipage}
  7397. \\[2ex]\hline
  7398. \end{tabular}
  7399. \caption{Compiling $R_7$ to $R_6$.}
  7400. \label{fig:compile-r7-r6}
  7401. \end{figure}
  7402. \begin{exercise}\normalfont
  7403. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7404. Create tests for $R_7$ by adapting all of your previous test programs
  7405. by removing type annotations. Add 5 more tests programs that
  7406. specifically rely on the language being dynamically typed. That is,
  7407. they should not be legal programs in a statically typed language, but
  7408. nevertheless, they should be valid $R_7$ programs that run to
  7409. completion without error.
  7410. \end{exercise}
  7411. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7412. \chapter{Gradual Typing}
  7413. \label{ch:gradual-typing}
  7414. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7415. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7416. \chapter{Parametric Polymorphism}
  7417. \label{ch:parametric-polymorphism}
  7418. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7419. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7420. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7421. \chapter{High-level Optimization}
  7422. \label{ch:high-level-optimization}
  7423. This chapter will present a procedure inlining pass based on the
  7424. algorithm of \citet{Waddell:1997fk}.
  7425. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7426. \chapter{Appendix}
  7427. \section{Interpreters}
  7428. \label{appendix:interp}
  7429. We provide several interpreters in the \key{interp.rkt} file. The
  7430. \key{interp-scheme} function takes an AST in one of the Racket-like
  7431. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7432. the program, returning the result value. The \key{interp-C} function
  7433. interprets an AST for a program in one of the C-like languages ($C_0,
  7434. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7435. for an x86 program.
  7436. \section{Utility Functions}
  7437. \label{appendix:utilities}
  7438. The utility function described in this section can be found in the
  7439. \key{utilities.rkt} file.
  7440. The \key{read-program} function takes a file path and parses that file
  7441. (it must be a Racket program) into an abstract syntax tree with a
  7442. \key{Program} node at the top.
  7443. The \key{parse-program} function takes an S-expression representation
  7444. of an AST and converts it into the struct-based representation.
  7445. The \key{assert} function displays the error message \key{msg} if the
  7446. Boolean \key{bool} is false.
  7447. \begin{lstlisting}
  7448. (define (assert msg bool) ...)
  7449. \end{lstlisting}
  7450. % remove discussion of lookup? -Jeremy
  7451. The \key{lookup} function takes a key and an alist, and returns the
  7452. first value that is associated with the given key, if there is one. If
  7453. not, an error is triggered. The alist may contain both immutable
  7454. pairs (built with \key{cons}) and mutable pairs (built with
  7455. \key{mcons}).
  7456. The \key{map2} function ...
  7457. %% \subsection{Graphs}
  7458. %% \begin{itemize}
  7459. %% \item The \code{make-graph} function takes a list of vertices
  7460. %% (symbols) and returns a graph.
  7461. %% \item The \code{add-edge} function takes a graph and two vertices and
  7462. %% adds an edge to the graph that connects the two vertices. The graph
  7463. %% is updated in-place. There is no return value for this function.
  7464. %% \item The \code{adjacent} function takes a graph and a vertex and
  7465. %% returns the set of vertices that are adjacent to the given
  7466. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7467. %% used with functions from the \code{racket/set} module.
  7468. %% \item The \code{vertices} function takes a graph and returns the list
  7469. %% of vertices in the graph.
  7470. %% \end{itemize}
  7471. \subsection{Testing}
  7472. The \key{interp-tests} function takes a compiler name (a string), a
  7473. description of the passes, an interpreter for the source language, a
  7474. test family name (a string), and a list of test numbers, and runs the
  7475. compiler passes and the interpreters to check whether the passes
  7476. correct. The description of the passes is a list with one entry per
  7477. pass. An entry is a list with three things: a string giving the name
  7478. of the pass, the function that implements the pass (a translator from
  7479. AST to AST), and a function that implements the interpreter (a
  7480. function from AST to result value) for the language of the output of
  7481. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7482. good choice. The \key{interp-tests} function assumes that the
  7483. subdirectory \key{tests} has a collection of Scheme programs whose names
  7484. all start with the family name, followed by an underscore and then the
  7485. test number, ending in \key{.scm}. Also, for each Scheme program there
  7486. is a file with the same number except that it ends with \key{.in} that
  7487. provides the input for the Scheme program.
  7488. \begin{lstlisting}
  7489. (define (interp-tests name passes test-family test-nums) ...)
  7490. \end{lstlisting}
  7491. The compiler-tests function takes a compiler name (a string) a
  7492. description of the passes (as described above for
  7493. \code{interp-tests}), a test family name (a string), and a list of
  7494. test numbers (see the comment for interp-tests), and runs the compiler
  7495. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7496. machine code. It runs the machine code and checks that the output is
  7497. 42.
  7498. \begin{lstlisting}
  7499. (define (compiler-tests name passes test-family test-nums) ...)
  7500. \end{lstlisting}
  7501. The compile-file function takes a description of the compiler passes
  7502. (see the comment for \key{interp-tests}) and returns a function that,
  7503. given a program file name (a string ending in \key{.scm}), applies all
  7504. of the passes and writes the output to a file whose name is the same
  7505. as the program file name but with \key{.scm} replaced with \key{.s}.
  7506. \begin{lstlisting}
  7507. (define (compile-file passes)
  7508. (lambda (prog-file-name) ...))
  7509. \end{lstlisting}
  7510. \section{x86 Instruction Set Quick-Reference}
  7511. \label{sec:x86-quick-reference}
  7512. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7513. do. We write $A \to B$ to mean that the value of $A$ is written into
  7514. location $B$. Address offsets are given in bytes. The instruction
  7515. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7516. registers (such as $\%rax$), or memory references (such as
  7517. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7518. reference per instruction. Other operands must be immediates or
  7519. registers.
  7520. \begin{table}[tbp]
  7521. \centering
  7522. \begin{tabular}{l|l}
  7523. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7524. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7525. \texttt{negq} $A$ & $- A \to A$ \\
  7526. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7527. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7528. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7529. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7530. \texttt{retq} & Pops the return address and jumps to it \\
  7531. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7532. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7533. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7534. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7535. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7536. matches the condition code of the instruction, otherwise go to the
  7537. next instructions. The condition codes are \key{e} for ``equal'',
  7538. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7539. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7540. \texttt{jl} $L$ & \\
  7541. \texttt{jle} $L$ & \\
  7542. \texttt{jg} $L$ & \\
  7543. \texttt{jge} $L$ & \\
  7544. \texttt{jmp} $L$ & Jump to label $L$ \\
  7545. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7546. \texttt{movzbq} $A$, $B$ &
  7547. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7548. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7549. and the extra bytes of $B$ are set to zero.} \\
  7550. & \\
  7551. & \\
  7552. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7553. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7554. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7555. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7556. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7557. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7558. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7559. description of the condition codes. $A$ must be a single byte register
  7560. (e.g., \texttt{al} or \texttt{cl}).} \\
  7561. \texttt{setl} $A$ & \\
  7562. \texttt{setle} $A$ & \\
  7563. \texttt{setg} $A$ & \\
  7564. \texttt{setge} $A$ &
  7565. \end{tabular}
  7566. \vspace{5pt}
  7567. \caption{Quick-reference for the x86 instructions used in this book.}
  7568. \label{tab:x86-instr}
  7569. \end{table}
  7570. \bibliographystyle{plainnat}
  7571. \bibliography{all}
  7572. \end{document}
  7573. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7574. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7575. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7576. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7577. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7578. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7579. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7580. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7581. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7582. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7583. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7584. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7585. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7586. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7587. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7588. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7589. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7590. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7591. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7592. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7593. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7594. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7595. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7596. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7597. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7598. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7599. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7600. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7601. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7602. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7603. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7604. % LocalWords: struct symtab