book.tex 307 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224
  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. Some operating
  1245. systems require the frame size to be a multiple of 16 bytes. In the
  1246. context of a procedure call, the \emph{return address} is the next
  1247. instruction after the call instruction on the caller side. During a
  1248. function call, the return address is pushed onto the stack. The
  1249. register \key{rbp} is the \emph{base pointer} and is used to access
  1250. variables associated with the current procedure call. The base
  1251. pointer of the caller is pushed onto the stack after the return
  1252. address. We number the variables from $1$ to $n$. Variable $1$ is
  1253. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1254. $-16\key{(\%rbp)}$, etc.
  1255. \begin{figure}[tbp]
  1256. \begin{lstlisting}
  1257. start:
  1258. movq $10, -8(%rbp)
  1259. negq -8(%rbp)
  1260. movq -8(%rbp), %rax
  1261. addq $52, %rax
  1262. jmp conclusion
  1263. .globl main
  1264. main:
  1265. pushq %rbp
  1266. movq %rsp, %rbp
  1267. subq $16, %rsp
  1268. jmp start
  1269. conclusion:
  1270. addq $16, %rsp
  1271. popq %rbp
  1272. retq
  1273. \end{lstlisting}
  1274. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1275. \label{fig:p1-x86}
  1276. \end{figure}
  1277. \begin{figure}[tbp]
  1278. \centering
  1279. \begin{tabular}{|r|l|} \hline
  1280. Position & Contents \\ \hline
  1281. 8(\key{\%rbp}) & return address \\
  1282. 0(\key{\%rbp}) & old \key{rbp} \\
  1283. -8(\key{\%rbp}) & variable $1$ \\
  1284. -16(\key{\%rbp}) & variable $2$ \\
  1285. \ldots & \ldots \\
  1286. 0(\key{\%rsp}) & variable $n$\\ \hline
  1287. \end{tabular}
  1288. \caption{Memory layout of a frame.}
  1289. \label{fig:frame}
  1290. \end{figure}
  1291. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1292. three instructions are the typical \emph{prelude} for a procedure.
  1293. The instruction \key{pushq \%rbp} saves the base pointer for the
  1294. caller onto the stack and subtracts $8$ from the stack pointer. The
  1295. second instruction \key{movq \%rsp, \%rbp} changes the base pointer so
  1296. that it points the location of the old base pointer. The instruction
  1297. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1298. room for storing variables. This program needs one variable ($8$
  1299. bytes) but because the frame size is required to be a multiple of 16
  1300. bytes, the space for variables is rounded up to 16 bytes.
  1301. The four instructions under the label \code{start} carry out the work
  1302. of computing \code{(+ 52 (- 10)))}. The first instruction
  1303. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1304. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1305. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1306. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1307. \key{rax}, at which point \key{rax} contains $42$.
  1308. The three instructions under the label \code{conclusion} are the
  1309. typical \emph{finale} of a procedure. The first two instructions are
  1310. necessary to get the state of the machine back to where it was at the
  1311. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1312. moves the stack pointer back to point at the old base pointer. The
  1313. amount added here needs to match the amount that was subtracted in the
  1314. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1315. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1316. instruction, \key{retq}, jumps back to the procedure that called this
  1317. one and adds 8 to the stack pointer, which returns the stack pointer
  1318. to where it was prior to the procedure call.
  1319. The compiler needs a convenient representation for manipulating x86
  1320. programs, so we define an abstract syntax for x86 in
  1321. Figure~\ref{fig:x86-0-ast}. We refer to this language as $x86_0$ with
  1322. a subscript $0$ because later we introduce extended versions of this
  1323. assembly language. The main difference compared to the concrete syntax
  1324. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow labeled
  1325. instructions to appear anywhere, but instead organizes instructions
  1326. into groups called \emph{blocks} and associates a label with every
  1327. block, which is why the \key{CFG} struct (for control-flow graph)
  1328. includes an alist mapping labels to blocks. The reason for this
  1329. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1330. introduce conditional branching. The \code{Block} structure includes
  1331. an $\itm{info}$ field that is not needed for this chapter, but will
  1332. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1333. the $\itm{info}$ field should just contain an empty list.
  1334. \begin{figure}[tp]
  1335. \fbox{
  1336. \begin{minipage}{0.96\textwidth}
  1337. \small
  1338. \[
  1339. \begin{array}{lcl}
  1340. \Reg &::=& \allregisters{} \\
  1341. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1342. \mid \DEREF{\Reg}{\Int} \\
  1343. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1344. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1345. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1346. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1347. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1348. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1349. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1350. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1351. \end{array}
  1352. \]
  1353. \end{minipage}
  1354. }
  1355. \caption{The abstract syntax of $x86_0$ assembly.}
  1356. \label{fig:x86-0-ast}
  1357. \end{figure}
  1358. \section{Planning the trip to x86 via the $C_0$ language}
  1359. \label{sec:plan-s0-x86}
  1360. To compile one language to another it helps to focus on the
  1361. differences between the two languages because the compiler will need
  1362. to bridge those differences. What are the differences between $R_1$
  1363. and x86 assembly? Here are some of the most important ones:
  1364. \begin{enumerate}
  1365. \item[(a)] x86 arithmetic instructions typically have two arguments
  1366. and update the second argument in place. In contrast, $R_1$
  1367. arithmetic operations take two arguments and produce a new value.
  1368. An x86 instruction may have at most one memory-accessing argument.
  1369. Furthermore, some instructions place special restrictions on their
  1370. arguments.
  1371. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1372. whereas x86 instructions restrict their arguments to be integers
  1373. constants, registers, and memory locations.
  1374. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1375. sequence of instructions and jumps to labeled positions, whereas in
  1376. $R_1$ the order of evaluation is a left-to-right depth-first
  1377. traversal of the abstract syntax tree.
  1378. \item[(d)] An $R_1$ program can have any number of variables whereas
  1379. x86 has 16 registers and the procedure calls stack.
  1380. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1381. same name. The registers and memory locations of x86 all have unique
  1382. names or addresses.
  1383. \end{enumerate}
  1384. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1385. the problem into several steps, dealing with the above differences one
  1386. at a time. Each of these steps is called a \emph{pass} of the
  1387. compiler.
  1388. %
  1389. This terminology comes from each step traverses (i.e. passes over) the
  1390. AST of the program.
  1391. %
  1392. We begin by sketching how we might implement each pass, and give them
  1393. names. We then figure out an ordering of the passes and the
  1394. input/output language for each pass. The very first pass has $R_1$ as
  1395. its input language and the last pass has x86 as its output
  1396. language. In between we can choose whichever language is most
  1397. convenient for expressing the output of each pass, whether that be
  1398. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1399. Finally, to implement each pass we write one recursive function per
  1400. non-terminal in the grammar of the input language of the pass.
  1401. \begin{description}
  1402. \item[Pass \key{select-instructions}] To handle the difference between
  1403. $R_1$ operations and x86 instructions we convert each $R_1$
  1404. operation to a short sequence of instructions that accomplishes the
  1405. same task.
  1406. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1407. subexpression (i.e. operator and operand, and hence the name
  1408. \key{opera*}) is an \emph{atomic} expression (a variable or
  1409. integer), we introduce temporary variables to hold the results
  1410. of subexpressions.
  1411. \item[Pass \key{explicate-control}] To make the execution order of the
  1412. program explicit, we convert from the abstract syntax tree
  1413. representation into a \emph{control-flow graph} in which each node
  1414. contains a sequence of statements and the edges between nodes say
  1415. where to go at the end of the sequence.
  1416. \item[Pass \key{assign-homes}] To handle the difference between the
  1417. variables in $R_1$ versus the registers and stack locations in x86,
  1418. we assignment of each variable to a register or stack location.
  1419. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1420. by renaming every variable to a unique name, so that shadowing no
  1421. longer occurs.
  1422. \end{description}
  1423. The next question is: in what order should we apply these passes? This
  1424. question can be challenging because it is difficult to know ahead of
  1425. time which orders will be better (easier to implement, produce more
  1426. efficient code, etc.) so oftentimes trial-and-error is
  1427. involved. Nevertheless, we can try to plan ahead and make educated
  1428. choices regarding the ordering.
  1429. Let us consider the ordering of \key{uniquify} and
  1430. \key{remove-complex-opera*}. The assignment of subexpressions to
  1431. temporary variables involves introducing new variables and moving
  1432. subexpressions, which might change the shadowing of variables and
  1433. inadvertently change the behavior of the program. But if we apply
  1434. \key{uniquify} first, this will not be an issue. Of course, this means
  1435. that in \key{remove-complex-opera*}, we need to ensure that the
  1436. temporary variables that it creates are unique.
  1437. What should be the ordering of \key{explicate-control} with respect to
  1438. \key{uniquify}? The \key{uniquify} pass should come first because
  1439. \key{explicate-control} changes all the \key{let}-bound variables to
  1440. become local variables whose scope is the entire program, which would
  1441. confuse variables with the same name.
  1442. %
  1443. Likewise, we place \key{explicate-control} after
  1444. \key{remove-complex-opera*} because \key{explicate-control} removes
  1445. the \key{let} form, but it is convenient to use \key{let} in the
  1446. output of \key{remove-complex-opera*}.
  1447. %
  1448. Regarding \key{assign-homes}, it is helpful to place
  1449. \key{explicate-control} first because \key{explicate-control} changes
  1450. \key{let}-bound variables into program-scope variables. This means
  1451. that the \key{assign-homes} pass can read off the variables from the
  1452. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1453. entire program in search of \key{let}-bound variables.
  1454. Last, we need to decide on the ordering of \key{select-instructions}
  1455. and \key{assign-homes}. These two passes are intertwined, creating a
  1456. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1457. have already determined which instructions will be used, because x86
  1458. instructions have restrictions about which of their arguments can be
  1459. registers versus stack locations. One might want to give preferential
  1460. treatment to variables that occur in register-argument positions. On
  1461. the other hand, it may turn out to be impossible to make sure that all
  1462. such variables are assigned to registers, and then one must redo the
  1463. selection of instructions. Some compilers handle this problem by
  1464. iteratively repeating these two passes until a good solution is found.
  1465. We shall use a simpler approach in which \key{select-instructions}
  1466. comes first, followed by the \key{assign-homes}, then a third
  1467. pass named \key{patch-instructions} that uses a reserved register to
  1468. patch-up outstanding problems regarding instructions with too many
  1469. memory accesses. The disadvantage of this approach is some programs
  1470. may not execute as efficiently as they would if we used the iterative
  1471. approach and used all of the registers for variables.
  1472. \begin{figure}[tbp]
  1473. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1474. \node (R1) at (0,2) {\large $R_1$};
  1475. \node (R1-2) at (3,2) {\large $R_1$};
  1476. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1477. %\node (C0-1) at (6,0) {\large $C_0$};
  1478. \node (C0-2) at (3,0) {\large $C_0$};
  1479. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1480. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1481. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1482. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1483. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1484. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1485. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1486. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1487. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1488. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1489. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1490. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1491. \end{tikzpicture}
  1492. \caption{Overview of the passes for compiling $R_1$. }
  1493. \label{fig:R1-passes}
  1494. \end{figure}
  1495. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1496. passes in the form of a graph. Each pass is an edge and the
  1497. input/output language of each pass is a node in the graph. The output
  1498. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1499. are still in the $R_1$ language, but the output of the pass
  1500. \key{explicate-control} is in a different language $C_0$ that is
  1501. designed to make the order of evaluation explicit in its syntax, which
  1502. we introduce in the next section. The \key{select-instruction} pass
  1503. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1504. \key{patch-instructions} passes input and output variants of x86
  1505. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1506. \key{print-x86}, which converts from the abstract syntax of
  1507. $\text{x86}_0$ to the concrete syntax of x86.
  1508. In the next sections we discuss the $C_0$ language and the
  1509. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1510. remainder of this chapter gives hints regarding the implementation of
  1511. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1512. \subsection{The $C_0$ Intermediate Language}
  1513. The output of \key{explicate-control} is similar to the $C$
  1514. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1515. categories for expressions and statements, so we name it $C_0$. The
  1516. concrete syntax for $C_0$ is defined in
  1517. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1518. is defined in Figure~\ref{fig:c0-syntax}.
  1519. %
  1520. The $C_0$ language supports the same operators as $R_1$ but the
  1521. arguments of operators are restricted to atomic expressions (variables
  1522. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1523. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1524. executed in sequence using the \key{Seq} form. A sequence of
  1525. statements always ends with \key{Return}, a guarantee that is baked
  1526. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1527. this non-terminal comes from the term \emph{tail position}, which
  1528. refers to an expression that is the last one to execute within a
  1529. function. (A expression in tail position may contain subexpressions,
  1530. and those may or may not be in tail position depending on the kind of
  1531. expression.)
  1532. A $C_0$ program consists of a control-flow graph (represented as an
  1533. alist mapping labels to tails). This is more general than
  1534. necessary for the present chapter, as we do not yet need to introduce
  1535. \key{goto} for jumping to labels, but it saves us from having to
  1536. change the syntax of the program construct in
  1537. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1538. \key{start}, and the whole program is its tail.
  1539. %
  1540. The $\itm{info}$ field of the \key{Program} form, after the
  1541. \key{explicate-control} pass, contains a mapping from the symbol
  1542. \key{locals} to a list of variables, that is, a list of all the
  1543. variables used in the program. At the start of the program, these
  1544. variables are uninitialized; they become initialized on their first
  1545. assignment.
  1546. \begin{figure}[tbp]
  1547. \fbox{
  1548. \begin{minipage}{0.96\textwidth}
  1549. \[
  1550. \begin{array}{lcl}
  1551. \Atm &::=& \Int \mid \Var \\
  1552. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1553. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1554. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1555. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1556. \end{array}
  1557. \]
  1558. \end{minipage}
  1559. }
  1560. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1561. \label{fig:c0-concrete-syntax}
  1562. \end{figure}
  1563. \begin{figure}[tbp]
  1564. \fbox{
  1565. \begin{minipage}{0.96\textwidth}
  1566. \[
  1567. \begin{array}{lcl}
  1568. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1569. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1570. &\mid& \ADD{\Atm}{\Atm}\\
  1571. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1572. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1573. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1574. \end{array}
  1575. \]
  1576. \end{minipage}
  1577. }
  1578. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1579. \label{fig:c0-syntax}
  1580. \end{figure}
  1581. %% The \key{select-instructions} pass is optimistic in the sense that it
  1582. %% treats variables as if they were all mapped to registers. The
  1583. %% \key{select-instructions} pass generates a program that consists of
  1584. %% x86 instructions but that still uses variables, so it is an
  1585. %% intermediate language that is technically different than x86, which
  1586. %% explains the asterisks in the diagram above.
  1587. %% In this Chapter we shall take the easy road to implementing
  1588. %% \key{assign-homes} and simply map all variables to stack locations.
  1589. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1590. %% smarter approach in which we make a best-effort to map variables to
  1591. %% registers, resorting to the stack only when necessary.
  1592. %% Once variables have been assigned to their homes, we can finalize the
  1593. %% instruction selection by dealing with an idiosyncrasy of x86
  1594. %% assembly. Many x86 instructions have two arguments but only one of the
  1595. %% arguments may be a memory reference (and the stack is a part of
  1596. %% memory). Because some variables may get mapped to stack locations,
  1597. %% some of our generated instructions may violate this restriction. The
  1598. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1599. %% replacing every violating instruction with a short sequence of
  1600. %% instructions that use the \key{rax} register. Once we have implemented
  1601. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1602. %% need to patch instructions will be relatively rare.
  1603. \subsection{The dialects of x86}
  1604. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1605. the pass \key{select-instructions}. It extends $x86_0$ with an
  1606. unbounded number of program-scope variables and has looser rules
  1607. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1608. output of \key{print-x86}, is the concrete syntax for x86.
  1609. \section{Uniquify Variables}
  1610. \label{sec:uniquify-s0}
  1611. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1612. programs in which every \key{let} uses a unique variable name. For
  1613. example, the \code{uniquify} pass should translate the program on the
  1614. left into the program on the right. \\
  1615. \begin{tabular}{lll}
  1616. \begin{minipage}{0.4\textwidth}
  1617. \begin{lstlisting}
  1618. (let ([x 32])
  1619. (+ (let ([x 10]) x) x))
  1620. \end{lstlisting}
  1621. \end{minipage}
  1622. &
  1623. $\Rightarrow$
  1624. &
  1625. \begin{minipage}{0.4\textwidth}
  1626. \begin{lstlisting}
  1627. (let ([x.1 32])
  1628. (+ (let ([x.2 10]) x.2) x.1))
  1629. \end{lstlisting}
  1630. \end{minipage}
  1631. \end{tabular} \\
  1632. %
  1633. The following is another example translation, this time of a program
  1634. with a \key{let} nested inside the initializing expression of another
  1635. \key{let}.\\
  1636. \begin{tabular}{lll}
  1637. \begin{minipage}{0.4\textwidth}
  1638. \begin{lstlisting}
  1639. (let ([x (let ([x 4])
  1640. (+ x 1))])
  1641. (+ x 2))
  1642. \end{lstlisting}
  1643. \end{minipage}
  1644. &
  1645. $\Rightarrow$
  1646. &
  1647. \begin{minipage}{0.4\textwidth}
  1648. \begin{lstlisting}
  1649. (let ([x.2 (let ([x.1 4])
  1650. (+ x.1 1))])
  1651. (+ x.2 2))
  1652. \end{lstlisting}
  1653. \end{minipage}
  1654. \end{tabular}
  1655. We recommend implementing \code{uniquify} by creating a function named
  1656. \code{uniquify-exp} that is structurally recursive function and mostly
  1657. just copies the input program. However, when encountering a \key{let},
  1658. it should generate a unique name for the variable (the Racket function
  1659. \code{gensym} is handy for this) and associate the old name with the
  1660. new unique name in an alist. The \code{uniquify-exp}
  1661. function will need to access this alist when it gets to a
  1662. variable reference, so we add another parameter to \code{uniquify-exp}
  1663. for the alist.
  1664. The skeleton of the \code{uniquify-exp} function is shown in
  1665. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1666. convenient to partially apply it to a symbol table and then apply it
  1667. to different expressions, as in the last clause for primitive
  1668. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1669. is useful for applying a function to each element of a list to produce
  1670. a new list.
  1671. \begin{exercise}
  1672. \normalfont % I don't like the italics for exercises. -Jeremy
  1673. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1674. implement the clauses for variables and for the \key{let} form.
  1675. \end{exercise}
  1676. \begin{figure}[tbp]
  1677. \begin{lstlisting}
  1678. (define (uniquify-exp symtab)
  1679. (lambda (e)
  1680. (match e
  1681. [(Var x) ___]
  1682. [(Int n) (Int n)]
  1683. [(Let x e body) ___]
  1684. [(Prim op es)
  1685. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1686. )))
  1687. (define (uniquify p)
  1688. (match p
  1689. [(Program info e)
  1690. (Program info ((uniquify-exp '()) e))]
  1691. )))
  1692. \end{lstlisting}
  1693. \caption{Skeleton for the \key{uniquify} pass.}
  1694. \label{fig:uniquify-s0}
  1695. \end{figure}
  1696. \begin{exercise}
  1697. \normalfont % I don't like the italics for exercises. -Jeremy
  1698. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1699. and checking whether the output programs produce the same result as
  1700. the input programs. The $R_1$ programs should be designed to test the
  1701. most interesting parts of the \key{uniquify} pass, that is, the
  1702. programs should include \key{let} forms, variables, and variables
  1703. that overshadow each other. The five programs should be in a
  1704. subdirectory named \key{tests} and they should have the same file name
  1705. except for a different integer at the end of the name, followed by the
  1706. ending \key{.rkt}. Use the \key{interp-tests} function
  1707. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1708. your \key{uniquify} pass on the example programs. See the
  1709. \key{run-tests.rkt} script in the student support code for an example
  1710. of how to use \key{interp-tests}.
  1711. \end{exercise}
  1712. \section{Remove Complex Operands}
  1713. \label{sec:remove-complex-opera-r1}
  1714. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1715. $R_1$ programs in which the arguments of operations are atomic
  1716. expressions. Put another way, this pass removes complex operands,
  1717. such as the expression \code{(- 10)} in the program below. This is
  1718. accomplished by introducing a new \key{let}-bound variable, binding
  1719. the complex operand to the new variable, and then using the new
  1720. variable in place of the complex operand, as shown in the output of
  1721. \code{remove-complex-opera*} on the right.\\
  1722. \begin{tabular}{lll}
  1723. \begin{minipage}{0.4\textwidth}
  1724. % s0_19.rkt
  1725. \begin{lstlisting}
  1726. (+ 52 (- 10))
  1727. \end{lstlisting}
  1728. \end{minipage}
  1729. &
  1730. $\Rightarrow$
  1731. &
  1732. \begin{minipage}{0.4\textwidth}
  1733. \begin{lstlisting}
  1734. (let ([tmp.1 (- 10)])
  1735. (+ 52 tmp.1))
  1736. \end{lstlisting}
  1737. \end{minipage}
  1738. \end{tabular}
  1739. \begin{figure}[tp]
  1740. \centering
  1741. \fbox{
  1742. \begin{minipage}{0.96\textwidth}
  1743. \[
  1744. \begin{array}{rcl}
  1745. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1746. \Exp &::=& \Atm \mid \READ{} \\
  1747. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1748. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1749. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1750. \end{array}
  1751. \]
  1752. \end{minipage}
  1753. }
  1754. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1755. \label{fig:r1-anf-syntax}
  1756. \end{figure}
  1757. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1758. this pass, language $R_1^{\dagger}$. The main difference is that
  1759. operator arguments are required to be atomic expressions. In the
  1760. literature this is called \emph{administrative normal form}, or ANF
  1761. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1762. We recommend implementing this pass with two mutually recursive
  1763. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1764. \code{rco-atom} to subexpressions that are required to be atomic and
  1765. to apply \code{rco-exp} to subexpressions that can be atomic or
  1766. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1767. $R_1$ expression as input. The \code{rco-exp} function returns an
  1768. expression. The \code{rco-atom} function returns two things: an
  1769. atomic expression and alist mapping temporary variables to complex
  1770. subexpressions. You can return multiple things from a function using
  1771. Racket's \key{values} form and you can receive multiple things from a
  1772. function call using the \key{define-values} form. If you are not
  1773. familiar with these features, review the Racket documentation. Also,
  1774. the \key{for/lists} form is useful for applying a function to each
  1775. element of a list, in the case where the function returns multiple
  1776. values.
  1777. The following shows the output of \code{rco-atom} on the expression
  1778. \code{(- 10)} (using concrete syntax to be concise).
  1779. \begin{tabular}{lll}
  1780. \begin{minipage}{0.4\textwidth}
  1781. \begin{lstlisting}
  1782. (- 10)
  1783. \end{lstlisting}
  1784. \end{minipage}
  1785. &
  1786. $\Rightarrow$
  1787. &
  1788. \begin{minipage}{0.4\textwidth}
  1789. \begin{lstlisting}
  1790. tmp.1
  1791. ((tmp.1 . (- 10)))
  1792. \end{lstlisting}
  1793. \end{minipage}
  1794. \end{tabular}
  1795. Take special care of programs such as the next one that \key{let}-bind
  1796. variables with integers or other variables. You should leave them
  1797. unchanged, as shown in to the program on the right \\
  1798. \begin{tabular}{lll}
  1799. \begin{minipage}{0.4\textwidth}
  1800. % s0_20.rkt
  1801. \begin{lstlisting}
  1802. (let ([a 42])
  1803. (let ([b a])
  1804. b))
  1805. \end{lstlisting}
  1806. \end{minipage}
  1807. &
  1808. $\Rightarrow$
  1809. &
  1810. \begin{minipage}{0.4\textwidth}
  1811. \begin{lstlisting}
  1812. (let ([a 42])
  1813. (let ([b a])
  1814. b))
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. \end{tabular} \\
  1818. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1819. produce the following output.\\
  1820. \begin{minipage}{0.4\textwidth}
  1821. \begin{lstlisting}
  1822. (let ([tmp.1 42])
  1823. (let ([a tmp.1])
  1824. (let ([tmp.2 a])
  1825. (let ([b tmp.2])
  1826. b))))
  1827. \end{lstlisting}
  1828. \end{minipage}
  1829. \begin{exercise}
  1830. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1831. it on all of the example programs that you created to test the
  1832. \key{uniquify} pass and create three new example programs that are
  1833. designed to exercise the interesting code in the
  1834. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1835. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1836. your passes on the example programs.
  1837. \end{exercise}
  1838. \section{Explicate Control}
  1839. \label{sec:explicate-control-r1}
  1840. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1841. programs that make the order of execution explicit in their
  1842. syntax. For now this amounts to flattening \key{let} constructs into a
  1843. sequence of assignment statements. For example, consider the following
  1844. $R_1$ program.\\
  1845. % s0_11.rkt
  1846. \begin{minipage}{0.96\textwidth}
  1847. \begin{lstlisting}
  1848. (let ([y (let ([x 20])
  1849. (+ x (let ([x 22]) x)))])
  1850. y)
  1851. \end{lstlisting}
  1852. \end{minipage}\\
  1853. %
  1854. The output of the previous pass and of \code{explicate-control} is
  1855. shown below. Recall that the right-hand-side of a \key{let} executes
  1856. before its body, so the order of evaluation for this program is to
  1857. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1858. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1859. output of \code{explicate-control} makes this ordering explicit.\\
  1860. \begin{tabular}{lll}
  1861. \begin{minipage}{0.4\textwidth}
  1862. \begin{lstlisting}
  1863. (let ([y (let ([x.1 20])
  1864. (let ([x.2 22])
  1865. (+ x.1 x.2)))])
  1866. y)
  1867. \end{lstlisting}
  1868. \end{minipage}
  1869. &
  1870. $\Rightarrow$
  1871. &
  1872. \begin{minipage}{0.4\textwidth}
  1873. \begin{lstlisting}
  1874. locals: y x.1 x.2
  1875. start:
  1876. x.1 = 20;
  1877. x.2 = 22;
  1878. y = (+ x.1 x.2);
  1879. return y;
  1880. \end{lstlisting}
  1881. \end{minipage}
  1882. \end{tabular}
  1883. We recommend implementing \code{explicate-control} using two mutually
  1884. recursive functions: \code{explicate-tail} and
  1885. \code{explicate-assign}. The first function should be applied to
  1886. expressions in tail position whereas the second should be applied to
  1887. expressions that occur on the right-hand-side of a \key{let}. The
  1888. \code{explicate-tail} function takes an $R_1$ expression as input and
  1889. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1890. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1891. function takes an $R_1$ expression, the variable that it is to be
  1892. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1893. assignment (e.g., the code generated for the body of the \key{let}).
  1894. It returns a $\Tail$ and a list of variables. The top-level
  1895. \code{explicate-control} function should invoke \code{explicate-tail}
  1896. on the body of the \key{program} and then associate the \code{locals}
  1897. symbol with the resulting list of variables in the $\itm{info}$ field,
  1898. as in the above example.
  1899. \section{Select Instructions}
  1900. \label{sec:select-r1}
  1901. In the \code{select-instructions} pass we begin the work of
  1902. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1903. this pass is a variant of x86 that still uses variables, so we add an
  1904. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1905. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1906. \code{select-instructions} in terms of three auxiliary functions, one
  1907. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1908. The cases for $\Atm$ are straightforward, variables stay
  1909. the same and integer constants are changed to immediates:
  1910. $\INT{n}$ changes to $\IMM{n}$.
  1911. Next we consider the cases for $\Stmt$, starting with arithmetic
  1912. operations. For example, in $C_0$ an addition operation can take the
  1913. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1914. need to use the \key{addq} instruction which does an in-place
  1915. update. So we must first move \code{10} to \code{x}. \\
  1916. \begin{tabular}{lll}
  1917. \begin{minipage}{0.4\textwidth}
  1918. \begin{lstlisting}
  1919. x = (+ 10 32);
  1920. \end{lstlisting}
  1921. \end{minipage}
  1922. &
  1923. $\Rightarrow$
  1924. &
  1925. \begin{minipage}{0.4\textwidth}
  1926. \begin{lstlisting}
  1927. movq $10, x
  1928. addq $32, x
  1929. \end{lstlisting}
  1930. \end{minipage}
  1931. \end{tabular} \\
  1932. %
  1933. There are cases that require special care to avoid generating
  1934. needlessly complicated code. If one of the arguments of the addition
  1935. is the same as the left-hand side of the assignment, then there is no
  1936. need for the extra move instruction. For example, the following
  1937. assignment statement can be translated into a single \key{addq}
  1938. instruction.\\
  1939. \begin{tabular}{lll}
  1940. \begin{minipage}{0.4\textwidth}
  1941. \begin{lstlisting}
  1942. x = (+ 10 x);
  1943. \end{lstlisting}
  1944. \end{minipage}
  1945. &
  1946. $\Rightarrow$
  1947. &
  1948. \begin{minipage}{0.4\textwidth}
  1949. \begin{lstlisting}
  1950. addq $10, x
  1951. \end{lstlisting}
  1952. \end{minipage}
  1953. \end{tabular} \\
  1954. The \key{read} operation does not have a direct counterpart in x86
  1955. assembly, so we have instead implemented this functionality in the C
  1956. language, with the function \code{read\_int} in the file
  1957. \code{runtime.c}. In general, we refer to all of the functionality in
  1958. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1959. for short. When compiling your generated x86 assembly code, you need
  1960. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1961. using \code{gcc} option \code{-c}) and link it into the
  1962. executable. For our purposes of code generation, all you need to do is
  1963. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1964. (for left-hand side) into a call to the \code{read\_int} function
  1965. followed by a move from \code{rax} to the left-hand side. The move
  1966. from \code{rax} is needed because the return value from
  1967. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1968. \begin{tabular}{lll}
  1969. \begin{minipage}{0.3\textwidth}
  1970. \begin{lstlisting}
  1971. |$\itm{var}$| = (read);
  1972. \end{lstlisting}
  1973. \end{minipage}
  1974. &
  1975. $\Rightarrow$
  1976. &
  1977. \begin{minipage}{0.3\textwidth}
  1978. \begin{lstlisting}
  1979. callq read_int
  1980. movq %rax, |$\itm{var}$|
  1981. \end{lstlisting}
  1982. \end{minipage}
  1983. \end{tabular} \\
  1984. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1985. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1986. assignment to the \key{rax} register followed by a jump to the
  1987. conclusion of the program (so the conclusion needs to be labeled).
  1988. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1989. recursively and append the resulting instructions.
  1990. \begin{exercise}
  1991. \normalfont
  1992. Implement the \key{select-instructions} pass and test it on all of the
  1993. example programs that you created for the previous passes and create
  1994. three new example programs that are designed to exercise all of the
  1995. interesting code in this pass. Use the \key{interp-tests} function
  1996. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1997. your passes on the example programs.
  1998. \end{exercise}
  1999. \section{Assign Homes}
  2000. \label{sec:assign-r1}
  2001. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2002. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2003. Thus, the \key{assign-homes} pass is responsible for placing all of
  2004. the program variables in registers or on the stack. For runtime
  2005. efficiency, it is better to place variables in registers, but as there
  2006. are only 16 registers, some programs must necessarily resort to
  2007. placing some variables on the stack. In this chapter we focus on the
  2008. mechanics of placing variables on the stack. We study an algorithm for
  2009. placing variables in registers in
  2010. Chapter~\ref{ch:register-allocation-r1}.
  2011. Consider again the following $R_1$ program.
  2012. % s0_20.rkt
  2013. \begin{lstlisting}
  2014. (let ([a 42])
  2015. (let ([b a])
  2016. b))
  2017. \end{lstlisting}
  2018. For reference, we repeat the output of \code{select-instructions} on
  2019. the left and show the output of \code{assign-homes} on the right.
  2020. Recall that \key{explicate-control} associated the list of
  2021. variables with the \code{locals} symbol in the program's $\itm{info}$
  2022. field, so \code{assign-homes} has convenient access to the them. In
  2023. this example, we assign variable \code{a} to stack location
  2024. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2025. \begin{tabular}{l}
  2026. \begin{minipage}{0.4\textwidth}
  2027. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2028. locals: a b
  2029. start:
  2030. movq $42, a
  2031. movq a, b
  2032. movq b, %rax
  2033. jmp conclusion
  2034. \end{lstlisting}
  2035. \end{minipage}
  2036. {$\Rightarrow$}
  2037. \begin{minipage}{0.4\textwidth}
  2038. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2039. stack-space: 16
  2040. start:
  2041. movq $42, -8(%rbp)
  2042. movq -8(%rbp), -16(%rbp)
  2043. movq -16(%rbp), %rax
  2044. jmp conclusion
  2045. \end{lstlisting}
  2046. \end{minipage}
  2047. \end{tabular} \\
  2048. In the process of assigning variables to stack locations, it is
  2049. convenient to compute and store the size of the frame (in bytes) in
  2050. the $\itm{info}$ field of the \key{Program} node, with the key
  2051. \code{stack-space}, which will be needed later to generate the
  2052. procedure conclusion. Some operating systems place restrictions on
  2053. the frame size. For example, Mac OS X requires the frame size to be a
  2054. multiple of 16 bytes.
  2055. \begin{exercise}
  2056. \normalfont Implement the \key{assign-homes} pass and test it on all
  2057. of the example programs that you created for the previous passes pass.
  2058. We recommend that \key{assign-homes} take an extra parameter that is a
  2059. mapping of variable names to homes (stack locations for now). Use the
  2060. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2061. \key{utilities.rkt} to test your passes on the example programs.
  2062. \end{exercise}
  2063. \section{Patch Instructions}
  2064. \label{sec:patch-s0}
  2065. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2066. programs to $\text{x86}_0$ programs by making sure that each
  2067. instruction adheres to the restrictions of the x86 assembly language.
  2068. In particular, at most one argument of an instruction may be a memory
  2069. reference.
  2070. We return to the following running example.
  2071. % s0_20.rkt
  2072. \begin{lstlisting}
  2073. (let ([a 42])
  2074. (let ([b a])
  2075. b))
  2076. \end{lstlisting}
  2077. After the \key{assign-homes} pass, the above program has been translated to
  2078. the following. \\
  2079. \begin{minipage}{0.5\textwidth}
  2080. \begin{lstlisting}
  2081. stack-space: 16
  2082. start:
  2083. movq $42, -8(%rbp)
  2084. movq -8(%rbp), -16(%rbp)
  2085. movq -16(%rbp), %rax
  2086. jmp conclusion
  2087. \end{lstlisting}
  2088. \end{minipage}\\
  2089. The second \key{movq} instruction is problematic because both
  2090. arguments are stack locations. We suggest fixing this problem by
  2091. moving from the source location to the register \key{rax} and then
  2092. from \key{rax} to the destination location, as follows.
  2093. \begin{lstlisting}
  2094. movq -8(%rbp), %rax
  2095. movq %rax, -16(%rbp)
  2096. \end{lstlisting}
  2097. \begin{exercise}
  2098. \normalfont
  2099. Implement the \key{patch-instructions} pass and test it on all of the
  2100. example programs that you created for the previous passes and create
  2101. three new example programs that are designed to exercise all of the
  2102. interesting code in this pass. Use the \key{interp-tests} function
  2103. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2104. your passes on the example programs.
  2105. \end{exercise}
  2106. \section{Print x86}
  2107. \label{sec:print-x86}
  2108. The last step of the compiler from $R_1$ to x86 is to convert the
  2109. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2110. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2111. \key{format} and \key{string-append} functions are useful in this
  2112. regard. The main work that this step needs to perform is to create the
  2113. \key{main} function and the standard instructions for its prelude and
  2114. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2115. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2116. variables, so we suggest computing it in the \key{assign-homes} pass
  2117. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2118. of the \key{program} node.
  2119. %% Your compiled code should print the result of the program's execution
  2120. %% by using the \code{print\_int} function provided in
  2121. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2122. %% far, this final result should be stored in the \key{rax} register.
  2123. %% We'll talk more about how to perform function calls with arguments in
  2124. %% general later on, but for now, place the following after the compiled
  2125. %% code for the $R_1$ program but before the conclusion:
  2126. %% \begin{lstlisting}
  2127. %% movq %rax, %rdi
  2128. %% callq print_int
  2129. %% \end{lstlisting}
  2130. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2131. %% stores the first argument to be passed into \key{print\_int}.
  2132. If you want your program to run on Mac OS X, your code needs to
  2133. determine whether or not it is running on a Mac, and prefix
  2134. underscores to labels like \key{main}. You can determine the platform
  2135. with the Racket call \code{(system-type 'os)}, which returns
  2136. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2137. %% In addition to
  2138. %% placing underscores on \key{main}, you need to put them in front of
  2139. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2140. %% \_print\_int}).
  2141. \begin{exercise}
  2142. \normalfont Implement the \key{print-x86} pass and test it on all of
  2143. the example programs that you created for the previous passes. Use the
  2144. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2145. \key{utilities.rkt} to test your complete compiler on the example
  2146. programs. See the \key{run-tests.rkt} script in the student support
  2147. code for an example of how to use \key{compiler-tests}. Also, remember
  2148. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2149. \key{gcc}.
  2150. \end{exercise}
  2151. \section{Challenge: Partial Evaluator for $R_1$}
  2152. \label{sec:pe-R1}
  2153. This section describes optional challenge exercises that involve
  2154. adapting and improving the partial evaluator for $R_0$ that was
  2155. introduced in Section~\ref{sec:partial-evaluation}.
  2156. \begin{exercise}\label{ex:pe-R1}
  2157. \normalfont
  2158. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2159. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2160. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2161. and variables to the $R_0$ language, so you will need to add cases for
  2162. them in the \code{pe-exp} function. Also, note that the \key{program}
  2163. form changes slightly to include an $\itm{info}$ field. Once
  2164. complete, add the partial evaluation pass to the front of your
  2165. compiler and make sure that your compiler still passes all of the
  2166. tests.
  2167. \end{exercise}
  2168. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2169. \begin{exercise}
  2170. \normalfont
  2171. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2172. \code{pe-add} auxiliary functions with functions that know more about
  2173. arithmetic. For example, your partial evaluator should translate
  2174. \begin{lstlisting}
  2175. (+ 1 (+ (read) 1))
  2176. \end{lstlisting}
  2177. into
  2178. \begin{lstlisting}
  2179. (+ 2 (read))
  2180. \end{lstlisting}
  2181. To accomplish this, the \code{pe-exp} function should produce output
  2182. in the form of the $\itm{residual}$ non-terminal of the following
  2183. grammar.
  2184. \[
  2185. \begin{array}{lcl}
  2186. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2187. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2188. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2189. \end{array}
  2190. \]
  2191. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2192. that their inputs are $\itm{residual}$ expressions and they should
  2193. return $\itm{residual}$ expressions. Once the improvements are
  2194. complete, make sure that your compiler still passes all of the tests.
  2195. After all, fast code is useless if it produces incorrect results!
  2196. \end{exercise}
  2197. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2198. \chapter{Register Allocation}
  2199. \label{ch:register-allocation-r1}
  2200. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2201. make our life easier. However, we can improve the performance of the
  2202. generated code if we instead place some variables into registers. The
  2203. CPU can access a register in a single cycle, whereas accessing the
  2204. stack takes many cycles if the relevant data is in cache or many more
  2205. to access main memory if the data is not in cache.
  2206. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2207. serves as a running example. We show the source program and also the
  2208. output of instruction selection. At that point the program is almost
  2209. x86 assembly but not quite; it still contains variables instead of
  2210. stack locations or registers.
  2211. \begin{figure}
  2212. \begin{minipage}{0.45\textwidth}
  2213. Example $R_1$ program:
  2214. % s0_22.rkt
  2215. \begin{lstlisting}
  2216. (let ([v 1])
  2217. (let ([w 46])
  2218. (let ([x (+ v 7)])
  2219. (let ([y (+ 4 x)])
  2220. (let ([z (+ x w)])
  2221. (+ z (- y)))))))
  2222. \end{lstlisting}
  2223. \end{minipage}
  2224. \begin{minipage}{0.45\textwidth}
  2225. After instruction selection:
  2226. \begin{lstlisting}
  2227. locals: v w x y z t.1
  2228. start:
  2229. movq $1, v
  2230. movq $46, w
  2231. movq v, x
  2232. addq $7, x
  2233. movq x, y
  2234. addq $4, y
  2235. movq x, z
  2236. addq w, z
  2237. movq y, t.1
  2238. negq t.1
  2239. movq z, %rax
  2240. addq t.1, %rax
  2241. jmp conclusion
  2242. \end{lstlisting}
  2243. \end{minipage}
  2244. \caption{An example program for register allocation.}
  2245. \label{fig:reg-eg}
  2246. \end{figure}
  2247. The goal of register allocation is to fit as many variables into
  2248. registers as possible. A program sometimes has more variables than
  2249. registers, so we cannot map each variable to a different
  2250. register. Fortunately, it is common for different variables to be
  2251. needed during different periods of time during program execution, and
  2252. in such cases several variables can be mapped to the same register.
  2253. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2254. After the variable \code{x} is moved to \code{z} it is no longer
  2255. needed. Variable \code{y}, on the other hand, is used only after this
  2256. point, so \code{x} and \code{y} could share the same register. The
  2257. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2258. where a variable is needed. Once we have that information, we compute
  2259. which variables are needed at the same time, i.e., which ones
  2260. \emph{interfere}, and represent this relation as an undirected graph
  2261. whose vertices are variables and edges indicate when two variables
  2262. interfere with each other (Section~\ref{sec:build-interference}). We
  2263. then model register allocation as a graph coloring problem, which we
  2264. discuss in Section~\ref{sec:graph-coloring}.
  2265. In the event that we run out of registers despite these efforts, we
  2266. place the remaining variables on the stack, similar to what we did in
  2267. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2268. for assigning a variable to a stack location. The process of spilling
  2269. variables is handled as part of the graph coloring process described
  2270. in \ref{sec:graph-coloring}.
  2271. \section{Registers and Calling Conventions}
  2272. \label{sec:calling-conventions}
  2273. As we perform register allocation, we need to be aware of the
  2274. conventions that govern the way in which registers interact with
  2275. function calls, such as calls to the \code{read\_int} function. The
  2276. convention for x86 is that the caller is responsible for freeing up
  2277. some registers, the \emph{caller-saved registers}, prior to the
  2278. function call, and the callee is responsible for saving and restoring
  2279. some other registers, the \emph{callee-saved registers}, before and
  2280. after using them. The caller-saved registers are
  2281. \begin{lstlisting}
  2282. rax rdx rcx rsi rdi r8 r9 r10 r11
  2283. \end{lstlisting}
  2284. while the callee-saved registers are
  2285. \begin{lstlisting}
  2286. rsp rbp rbx r12 r13 r14 r15
  2287. \end{lstlisting}
  2288. Another way to think about this caller/callee convention is the
  2289. following. The caller should assume that all the caller-saved registers
  2290. get overwritten with arbitrary values by the callee. On the other
  2291. hand, the caller can safely assume that all the callee-saved registers
  2292. contain the same values after the call that they did before the call.
  2293. The callee can freely use any of the caller-saved registers. However,
  2294. if the callee wants to use a callee-saved register, the callee must
  2295. arrange to put the original value back in the register prior to
  2296. returning to the caller, which is usually accomplished by saving and
  2297. restoring the value from the stack.
  2298. \section{Liveness Analysis}
  2299. \label{sec:liveness-analysis-r1}
  2300. A variable is \emph{live} if the variable is used at some later point
  2301. in the program and there is not an intervening assignment to the
  2302. variable.
  2303. %
  2304. To understand the latter condition, consider the following code
  2305. fragment in which there are two writes to \code{b}. Are \code{a} and
  2306. \code{b} both live at the same time?
  2307. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2308. movq $5, a
  2309. movq $30, b
  2310. movq a, c
  2311. movq $10, b
  2312. addq b, c
  2313. \end{lstlisting}
  2314. The answer is no because the integer \code{30} written to \code{b} on
  2315. line 2 is never used. The variable \code{b} is read on line 5 and
  2316. there is an intervening write to \code{b} on line 4, so the read on
  2317. line 5 receives the value written on line 4, not line 2.
  2318. The live variables can be computed by traversing the instruction
  2319. sequence back to front (i.e., backwards in execution order). Let
  2320. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2321. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2322. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2323. variables before instruction $I_k$. The live variables after an
  2324. instruction are always the same as the live variables before the next
  2325. instruction.
  2326. \begin{equation} \label{eq:live-after-before-next}
  2327. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2328. \end{equation}
  2329. To start things off, there are no live variables after the last
  2330. instruction, so
  2331. \begin{equation}\label{eq:live-last-empty}
  2332. L_{\mathsf{after}}(n) = \emptyset
  2333. \end{equation}
  2334. We then apply the following rule repeatedly, traversing the
  2335. instruction sequence back to front.
  2336. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2337. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2338. \end{equation}
  2339. where $W(k)$ are the variables written to by instruction $I_k$ and
  2340. $R(k)$ are the variables read by instruction $I_k$.
  2341. Let us walk through the above example, applying these formulas
  2342. starting with the instruction on line 5. We collect the answers in the
  2343. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2344. instruction is $\emptyset$ because it is the last instruction
  2345. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2346. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2347. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2348. is
  2349. \[
  2350. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2351. \]
  2352. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2353. the live-before set from line 5 to be the live-after set for this
  2354. instruction (formula~\ref{eq:live-after-before-next}).
  2355. \[
  2356. L_{\mathsf{after}}(4) = \{ b, c \}
  2357. \]
  2358. This move instruction writes to $b$ and does not read from any
  2359. variables, so we have the following live-before set
  2360. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2361. \[
  2362. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2363. \]
  2364. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2365. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2366. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2367. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2368. variable that is not live and does not read from a variable.
  2369. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2370. because it writes to variable $a$.
  2371. \begin{center}
  2372. \begin{minipage}{0.45\textwidth}
  2373. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2374. movq $5, a
  2375. movq $30, b
  2376. movq a, c
  2377. movq $10, b
  2378. addq b, c
  2379. \end{lstlisting}
  2380. \end{minipage}
  2381. \vrule\hspace{10pt}
  2382. \begin{minipage}{0.45\textwidth}
  2383. \begin{align*}
  2384. L_{\mathsf{before}}(1)= \emptyset,
  2385. L_{\mathsf{after}}(1)= \{a\}\\
  2386. L_{\mathsf{before}}(2)= \{a\},
  2387. L_{\mathsf{after}}(2)= \{a\}\\
  2388. L_{\mathsf{before}}(3)= \{a\},
  2389. L_{\mathsf{after}}(2)= \{c\}\\
  2390. L_{\mathsf{before}}(4)= \{c\},
  2391. L_{\mathsf{after}}(4)= \{b,c\}\\
  2392. L_{\mathsf{before}}(5)= \{b,c\},
  2393. L_{\mathsf{after}}(5)= \emptyset
  2394. \end{align*}
  2395. \end{minipage}
  2396. \end{center}
  2397. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2398. for the running example program, with each instruction aligned with
  2399. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2400. \begin{figure}[tbp]
  2401. \hspace{20pt}
  2402. \begin{minipage}{0.45\textwidth}
  2403. \begin{lstlisting}[numbers=left]
  2404. movq $1, v
  2405. movq $46, w
  2406. movq v, x
  2407. addq $7, x
  2408. movq x, y
  2409. addq $4, y
  2410. movq x, z
  2411. addq w, z
  2412. movq y, t.1
  2413. negq t.1)
  2414. movq z, %rax
  2415. addq t.1, %rax
  2416. jmp conclusion
  2417. \end{lstlisting}
  2418. \end{minipage}
  2419. \vrule\hspace{10pt}
  2420. \begin{minipage}{0.45\textwidth}
  2421. \begin{lstlisting}
  2422. |$\{\}$|
  2423. |$\{v \}$|
  2424. |$\{v,w\}$|
  2425. |$\{w,x\}$|
  2426. |$\{w,x\}$|
  2427. |$\{w,x,y\}$|
  2428. |$\{w,x,y\}$|
  2429. |$\{w,y,z\}$|
  2430. |$\{y,z\}$|
  2431. |$\{z,t.1\}$|
  2432. |$\{z,t.1\}$|
  2433. |$\{t.1\}$|
  2434. |$\{\}$|
  2435. |$\{\}$|
  2436. \end{lstlisting}
  2437. \end{minipage}
  2438. \caption{The running example annotated with live-after sets.}
  2439. \label{fig:live-eg}
  2440. \end{figure}
  2441. \begin{exercise}\normalfont
  2442. Implement the compiler pass named \code{uncover-live} that computes
  2443. the live-after sets. We recommend storing the live-after sets (a list
  2444. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2445. structure.
  2446. %
  2447. We recommend organizing your code to use a helper function that takes
  2448. a list of instructions and an initial live-after set (typically empty)
  2449. and returns the list of live-after sets.
  2450. %
  2451. We recommend creating helper functions to 1) compute the set of
  2452. variables that appear in an argument (of an instruction), 2) compute
  2453. the variables read by an instruction which corresponds to the $R$
  2454. function discussed above, and 3) the variables written by an
  2455. instruction which corresponds to $W$.
  2456. \end{exercise}
  2457. \section{Building the Interference Graph}
  2458. \label{sec:build-interference}
  2459. Based on the liveness analysis, we know where each variable is needed.
  2460. However, during register allocation, we need to answer questions of
  2461. the specific form: are variables $u$ and $v$ live at the same time?
  2462. (And therefore cannot be assigned to the same register.) To make this
  2463. question easier to answer, we create an explicit data structure, an
  2464. \emph{interference graph}. An interference graph is an undirected
  2465. graph that has an edge between two variables if they are live at the
  2466. same time, that is, if they interfere with each other.
  2467. The most obvious way to compute the interference graph is to look at
  2468. the set of live variables between each statement in the program and
  2469. add an edge to the graph for every pair of variables in the same set.
  2470. This approach is less than ideal for two reasons. First, it can be
  2471. expensive because it takes $O(n^2)$ time to look at every pair in a
  2472. set of $n$ live variables. Second, there is a special case in which
  2473. two variables that are live at the same time do not actually interfere
  2474. with each other: when they both contain the same value because we have
  2475. assigned one to the other.
  2476. A better way to compute the interference graph is to focus on the
  2477. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2478. instruction to overwrite something in a live variable. So for each
  2479. instruction, we create an edge between the variable being written to
  2480. and all the \emph{other} live variables. (One should not create self
  2481. edges.) For a \key{callq} instruction, think of all caller-saved
  2482. registers as being written to, so an edge must be added between every
  2483. live variable and every caller-saved register. For \key{movq}, we deal
  2484. with the above-mentioned special case by not adding an edge between a
  2485. live variable $v$ and destination $d$ if $v$ matches the source of the
  2486. move. So we have the following three rules.
  2487. \begin{enumerate}
  2488. \item If instruction $I_k$ is an arithmetic instruction such as
  2489. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2490. L_{\mathsf{after}}(k)$ unless $v = d$.
  2491. \item If instruction $I_k$ is of the form \key{callq}
  2492. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2493. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2494. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2495. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2496. d$ or $v = s$.
  2497. \end{enumerate}
  2498. \margincomment{JM: I think you could give examples of each one of these
  2499. using the example program and use those to help explain why these
  2500. rules are correct.\\
  2501. JS: Agreed.}
  2502. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2503. the following interference for the instruction at the specified line
  2504. number.
  2505. \begin{quote}
  2506. Line 2: no interference,\\
  2507. Line 3: $w$ interferes with $v$,\\
  2508. Line 4: $x$ interferes with $w$,\\
  2509. Line 5: $x$ interferes with $w$,\\
  2510. Line 6: $y$ interferes with $w$,\\
  2511. Line 7: $y$ interferes with $w$ and $x$,\\
  2512. Line 8: $z$ interferes with $w$ and $y$,\\
  2513. Line 9: $z$ interferes with $y$, \\
  2514. Line 10: $t.1$ interferes with $z$, \\
  2515. Line 11: $t.1$ interferes with $z$, \\
  2516. Line 12: no interference, \\
  2517. Line 13: no interference. \\
  2518. Line 14: no interference.
  2519. \end{quote}
  2520. The resulting interference graph is shown in
  2521. Figure~\ref{fig:interfere}.
  2522. \begin{figure}[tbp]
  2523. \large
  2524. \[
  2525. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2526. \node (v) at (0,0) {$v$};
  2527. \node (w) at (2,0) {$w$};
  2528. \node (x) at (4,0) {$x$};
  2529. \node (t1) at (6,-2) {$t.1$};
  2530. \node (y) at (2,-2) {$y$};
  2531. \node (z) at (4,-2) {$z$};
  2532. \draw (v) to (w);
  2533. \foreach \i in {w,x,y}
  2534. {
  2535. \foreach \j in {w,x,y}
  2536. {
  2537. \draw (\i) to (\j);
  2538. }
  2539. }
  2540. \draw (z) to (w);
  2541. \draw (z) to (y);
  2542. \draw (t1) to (z);
  2543. \end{tikzpicture}
  2544. \]
  2545. \caption{The interference graph of the example program.}
  2546. \label{fig:interfere}
  2547. \end{figure}
  2548. %% Our next concern is to choose a data structure for representing the
  2549. %% interference graph. There are many choices for how to represent a
  2550. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2551. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2552. %% data structure is to study the algorithm that uses the data structure,
  2553. %% determine what operations need to be performed, and then choose the
  2554. %% data structure that provide the most efficient implementations of
  2555. %% those operations. Often times the choice of data structure can have an
  2556. %% effect on the time complexity of the algorithm, as it does here. If
  2557. %% you skim the next section, you will see that the register allocation
  2558. %% algorithm needs to ask the graph for all of its vertices and, given a
  2559. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2560. %% correct choice of graph representation is that of an adjacency
  2561. %% list. There are helper functions in \code{utilities.rkt} for
  2562. %% representing graphs using the adjacency list representation:
  2563. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2564. %% (Appendix~\ref{appendix:utilities}).
  2565. %% %
  2566. %% \margincomment{\footnotesize To do: change to use the
  2567. %% Racket graph library. \\ --Jeremy}
  2568. %% %
  2569. %% In particular, those functions use a hash table to map each vertex to
  2570. %% the set of adjacent vertices, and the sets are represented using
  2571. %% Racket's \key{set}, which is also a hash table.
  2572. \begin{exercise}\normalfont
  2573. Implement the compiler pass named \code{build-interference} according
  2574. to the algorithm suggested above. We recommend using the Racket
  2575. \code{graph} package to create and inspect the interference graph.
  2576. The output graph of this pass should be stored in the $\itm{info}$
  2577. field of the program, under the key \code{conflicts}.
  2578. \end{exercise}
  2579. \section{Graph Coloring via Sudoku}
  2580. \label{sec:graph-coloring}
  2581. We come to the main event, mapping variables to registers (or to stack
  2582. locations in the event that we run out of registers). We need to make
  2583. sure that two variables do not get mapped to the same register if the
  2584. two variables interfere with each other. Thinking about the
  2585. interference graph, this means that adjacent vertices must be mapped
  2586. to different registers. If we think of registers as colors, the
  2587. register allocation problem becomes the widely-studied graph coloring
  2588. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2589. The reader may be more familiar with the graph coloring problem than he
  2590. or she realizes; the popular game of Sudoku is an instance of the
  2591. graph coloring problem. The following describes how to build a graph
  2592. out of an initial Sudoku board.
  2593. \begin{itemize}
  2594. \item There is one vertex in the graph for each Sudoku square.
  2595. \item There is an edge between two vertices if the corresponding squares
  2596. are in the same row, in the same column, or if the squares are in
  2597. the same $3\times 3$ region.
  2598. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2599. \item Based on the initial assignment of numbers to squares in the
  2600. Sudoku board, assign the corresponding colors to the corresponding
  2601. vertices in the graph.
  2602. \end{itemize}
  2603. If you can color the remaining vertices in the graph with the nine
  2604. colors, then you have also solved the corresponding game of Sudoku.
  2605. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2606. the corresponding graph with colored vertices. We map the Sudoku
  2607. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2608. sampling of the vertices (the colored ones) because showing edges for
  2609. all of the vertices would make the graph unreadable.
  2610. \begin{figure}[tbp]
  2611. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2612. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2613. \caption{A Sudoku game board and the corresponding colored graph.}
  2614. \label{fig:sudoku-graph}
  2615. \end{figure}
  2616. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2617. strategies to come up with an algorithm for allocating registers. For
  2618. example, one of the basic techniques for Sudoku is called Pencil
  2619. Marks. The idea is to use a process of elimination to determine what
  2620. numbers no longer make sense for a square and write down those
  2621. numbers in the square (writing very small). For example, if the number
  2622. $1$ is assigned to a square, then by process of elimination, you can
  2623. write the pencil mark $1$ in all the squares in the same row, column,
  2624. and region. Many Sudoku computer games provide automatic support for
  2625. Pencil Marks.
  2626. %
  2627. The Pencil Marks technique corresponds to the notion of
  2628. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2629. vertex, in Sudoku terms, is the set of numbers that are no longer
  2630. available. In graph terminology, we have the following definition:
  2631. \begin{equation*}
  2632. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2633. \text{ and } \mathrm{color}(v) = c \}
  2634. \end{equation*}
  2635. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2636. edge with $u$.
  2637. Using the Pencil Marks technique leads to a simple strategy for
  2638. filling in numbers: if there is a square with only one possible number
  2639. left, then choose that number! But what if there are no squares with
  2640. only one possibility left? One brute-force approach is to try them
  2641. all: choose the first and if it ultimately leads to a solution,
  2642. great. If not, backtrack and choose the next possibility. One good
  2643. thing about Pencil Marks is that it reduces the degree of branching in
  2644. the search tree. Nevertheless, backtracking can be horribly time
  2645. consuming. One way to reduce the amount of backtracking is to use the
  2646. most-constrained-first heuristic. That is, when choosing a square,
  2647. always choose one with the fewest possibilities left (the vertex with
  2648. the highest saturation). The idea is that choosing highly constrained
  2649. squares earlier rather than later is better because later on there may
  2650. not be any possibilities left for those squares.
  2651. In some sense, register allocation is easier than Sudoku because the
  2652. register allocator can choose to map variables to stack locations when
  2653. the registers run out. Thus, it makes sense to drop backtracking in
  2654. favor of greedy search, that is, make the best choice at the time and
  2655. keep going. We still wish to minimize the number of colors needed, so
  2656. keeping the most-constrained-first heuristic is a good idea.
  2657. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2658. algorithm for register allocation based on saturation and the
  2659. most-constrained-first heuristic. It is roughly equivalent to the
  2660. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2661. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2662. Sudoku, the algorithm represents colors with integers. The first $k$
  2663. colors corresponding to the $k$ registers in a given machine and the
  2664. rest of the integers corresponding to stack locations.
  2665. \begin{figure}[btp]
  2666. \centering
  2667. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2668. Algorithm: DSATUR
  2669. Input: a graph |$G$|
  2670. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2671. |$W \gets \mathit{vertices}(G)$|
  2672. while |$W \neq \emptyset$| do
  2673. pick a vertex |$u$| from |$W$| with the highest saturation,
  2674. breaking ties randomly
  2675. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2676. |$\mathrm{color}[u] \gets c$|
  2677. |$W \gets W - \{u\}$|
  2678. \end{lstlisting}
  2679. \caption{The saturation-based greedy graph coloring algorithm.}
  2680. \label{fig:satur-algo}
  2681. \end{figure}
  2682. With this algorithm in hand, let us return to the running example and
  2683. consider how to color the interference graph in
  2684. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2685. colored and they are unsaturated, so we annotate each of them with a
  2686. dash for their color and an empty set for the saturation.
  2687. \[
  2688. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2689. \node (v) at (0,0) {$v:-,\{\}$};
  2690. \node (w) at (3,0) {$w:-,\{\}$};
  2691. \node (x) at (6,0) {$x:-,\{\}$};
  2692. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2693. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2694. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2695. \draw (v) to (w);
  2696. \foreach \i in {w,x,y}
  2697. {
  2698. \foreach \j in {w,x,y}
  2699. {
  2700. \draw (\i) to (\j);
  2701. }
  2702. }
  2703. \draw (z) to (w);
  2704. \draw (z) to (y);
  2705. \draw (t1) to (z);
  2706. \end{tikzpicture}
  2707. \]
  2708. The algorithm says to select a maximally saturated vertex and color it
  2709. $0$. In this case we have a 7-way tie, so we arbitrarily pick
  2710. $t.1$. We then mark color $0$ as no longer available for $z$ because
  2711. it interferes with $t.1$.
  2712. \[
  2713. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2714. \node (v) at (0,0) {$v:-,\{\}$};
  2715. \node (w) at (3,0) {$w:-,\{\}$};
  2716. \node (x) at (6,0) {$x:-,\{\}$};
  2717. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2718. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2719. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2720. \draw (v) to (w);
  2721. \foreach \i in {w,x,y}
  2722. {
  2723. \foreach \j in {w,x,y}
  2724. {
  2725. \draw (\i) to (\j);
  2726. }
  2727. }
  2728. \draw (z) to (w);
  2729. \draw (z) to (y);
  2730. \draw (t1) to (z);
  2731. \end{tikzpicture}
  2732. \]
  2733. Next we repeat the process, selecting another maximally saturated
  2734. vertex, which is $z$, and color it with the first available number,
  2735. which is $1$.
  2736. \[
  2737. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2738. \node (v) at (0,0) {$v:-,\{\}$};
  2739. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2740. \node (x) at (6,0) {$x:-,\{\}$};
  2741. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2742. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2743. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2744. \draw (t1) to (z);
  2745. \draw (v) to (w);
  2746. \foreach \i in {w,x,y}
  2747. {
  2748. \foreach \j in {w,x,y}
  2749. {
  2750. \draw (\i) to (\j);
  2751. }
  2752. }
  2753. \draw (z) to (w);
  2754. \draw (z) to (y);
  2755. \end{tikzpicture}
  2756. \]
  2757. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2758. first available color, which is $0$.
  2759. \[
  2760. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2761. \node (v) at (0,0) {$v:-,\{\}$};
  2762. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2763. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2764. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2765. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2766. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2767. \draw (t1) to (z);
  2768. \draw (v) to (w);
  2769. \foreach \i in {w,x,y}
  2770. {
  2771. \foreach \j in {w,x,y}
  2772. {
  2773. \draw (\i) to (\j);
  2774. }
  2775. }
  2776. \draw (z) to (w);
  2777. \draw (z) to (y);
  2778. \end{tikzpicture}
  2779. \]
  2780. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2781. We cannot choose $0$ or $1$ because those numbers are in $w$'s
  2782. saturation set. Indeed, $w$ interferes with $y$ and $z$, whose colors
  2783. are $0$ and $1$ respectively.
  2784. \[
  2785. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2786. \node (v) at (0,0) {$v:-,\{2\}$};
  2787. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2788. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2789. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2790. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2791. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2792. \draw (t1) to (z);
  2793. \draw (v) to (w);
  2794. \foreach \i in {w,x,y}
  2795. {
  2796. \foreach \j in {w,x,y}
  2797. {
  2798. \draw (\i) to (\j);
  2799. }
  2800. }
  2801. \draw (z) to (w);
  2802. \draw (z) to (y);
  2803. \end{tikzpicture}
  2804. \]
  2805. Now $x$ has the highest saturation, so we color it $1$.
  2806. \[
  2807. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2808. \node (v) at (0,0) {$v:-,\{2\}$};
  2809. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2810. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2811. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2812. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2813. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2814. \draw (t1) to (z);
  2815. \draw (v) to (w);
  2816. \foreach \i in {w,x,y}
  2817. {
  2818. \foreach \j in {w,x,y}
  2819. {
  2820. \draw (\i) to (\j);
  2821. }
  2822. }
  2823. \draw (z) to (w);
  2824. \draw (z) to (y);
  2825. \end{tikzpicture}
  2826. \]
  2827. In the last step of the algorithm, we color $v$ with $0$.
  2828. \[
  2829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2830. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2831. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2832. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2833. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2834. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2835. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2836. \draw (t1) to (z);
  2837. \draw (v) to (w);
  2838. \foreach \i in {w,x,y}
  2839. {
  2840. \foreach \j in {w,x,y}
  2841. {
  2842. \draw (\i) to (\j);
  2843. }
  2844. }
  2845. \draw (z) to (w);
  2846. \draw (z) to (y);
  2847. \end{tikzpicture}
  2848. \]
  2849. With the coloring complete, we finalize the assignment of variables to
  2850. registers and stack locations. Recall that if we have $k$ registers,
  2851. we map the first $k$ colors to registers and the rest to stack
  2852. locations. Suppose for the moment that we have just one register to
  2853. use for register allocation, \key{rcx}. Then the following is the
  2854. mapping of colors to registers and stack allocations.
  2855. \[
  2856. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2857. \]
  2858. Putting this mapping together with the above coloring of the
  2859. variables, we arrive at the following assignment of variables to
  2860. registers and stack locations.
  2861. \begin{gather*}
  2862. \{ v \mapsto \key{\%rcx}, \,
  2863. w \mapsto \key{-16(\%rbp)}, \,
  2864. x \mapsto \key{-8(\%rbp)}, \\
  2865. y \mapsto \key{\%rcx}, \,
  2866. z\mapsto \key{-8(\%rbp)},
  2867. t.1\mapsto \key{\%rcx} \}
  2868. \end{gather*}
  2869. Applying this assignment to our running example, on the left, yields
  2870. the program on the right.
  2871. % why frame size of 32? -JGS
  2872. \begin{center}
  2873. \begin{minipage}{0.3\textwidth}
  2874. \begin{lstlisting}
  2875. movq $1, v
  2876. movq $46, w
  2877. movq v, x
  2878. addq $7, x
  2879. movq x, y
  2880. addq $4, y
  2881. movq x, z
  2882. addq w, z
  2883. movq y, t.1
  2884. negq t.1
  2885. movq z, %rax
  2886. addq t.1, %rax
  2887. jmp conclusion
  2888. \end{lstlisting}
  2889. \end{minipage}
  2890. $\Rightarrow\qquad$
  2891. \begin{minipage}{0.45\textwidth}
  2892. \begin{lstlisting}
  2893. movq $1, %rcx
  2894. movq $46, -16(%rbp)
  2895. movq %rcx, -8(%rbp)
  2896. addq $7, -8(%rbp)
  2897. movq -8(%rbp), %rcx
  2898. addq $4, %rcx
  2899. movq -8(%rbp), -8(%rbp)
  2900. addq -16(%rbp), -8(%rbp)
  2901. movq %rcx, %rcx
  2902. negq %rcx
  2903. movq -8(%rbp), %rax
  2904. addq %rcx, %rax
  2905. jmp conclusion
  2906. \end{lstlisting}
  2907. \end{minipage}
  2908. \end{center}
  2909. The resulting program is almost an x86 program. The remaining step is
  2910. the patch instructions pass. In this example, the trivial move of
  2911. \code{-8(\%rbp)} to itself is deleted and the addition of
  2912. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2913. \code{rax} as follows.
  2914. \begin{lstlisting}
  2915. movq -16(%rbp), %rax
  2916. addq %rax, -8(%rbp)
  2917. \end{lstlisting}
  2918. An overview of all of the passes involved in register allocation is
  2919. shown in Figure~\ref{fig:reg-alloc-passes}.
  2920. \begin{figure}[tbp]
  2921. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2922. \node (R1) at (0,2) {\large $R_1$};
  2923. \node (R1-2) at (3,2) {\large $R_1$};
  2924. \node (R1-3) at (6,2) {\large $R_1$};
  2925. \node (C0-1) at (6,0) {\large $C_0$};
  2926. \node (C0-2) at (3,0) {\large $C_0$};
  2927. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2928. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2929. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2930. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2931. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2932. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2933. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2934. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2935. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2936. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2937. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2938. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2939. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2940. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2941. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2942. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2943. \end{tikzpicture}
  2944. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2945. \label{fig:reg-alloc-passes}
  2946. \end{figure}
  2947. \begin{exercise}\normalfont
  2948. Implement the pass \code{allocate-registers}, which should come
  2949. after the \code{build-interference} pass. The three new passes,
  2950. \code{uncover-live}, \code{build-interference}, and
  2951. \code{allocate-registers} replace the \code{assign-homes} pass of
  2952. Section~\ref{sec:assign-r1}.
  2953. We recommend that you create a helper function named
  2954. \code{color-graph} that takes an interference graph and a list of
  2955. all the variables in the program. This function should return a
  2956. mapping of variables to their colors (represented as natural
  2957. numbers). By creating this helper function, you will be able to
  2958. reuse it in Chapter~\ref{ch:functions} when you add support for
  2959. functions.
  2960. Once you have obtained the coloring from \code{color-graph}, you can
  2961. assign the variables to registers or stack locations and then reuse
  2962. code from the \code{assign-homes} pass from
  2963. Section~\ref{sec:assign-r1} to replace the variables with their
  2964. assigned location.
  2965. Test your updated compiler by creating new example programs that
  2966. exercise all of the register allocation algorithm, such as forcing
  2967. variables to be spilled to the stack.
  2968. \end{exercise}
  2969. \section{Print x86 and Conventions for Registers}
  2970. \label{sec:print-x86-reg-alloc}
  2971. Recall that the \code{print-x86} pass generates the prelude and
  2972. conclusion instructions for the \code{main} function.
  2973. %
  2974. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2975. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2976. reason for this is that our \code{main} function must adhere to the
  2977. x86 calling conventions that we described in
  2978. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2979. function needs to restore (in the conclusion) any callee-saved
  2980. registers that get used during register allocation. The simplest
  2981. approach is to save and restore all of the callee-saved registers. The
  2982. more efficient approach is to keep track of which callee-saved
  2983. registers were used and only save and restore them. Either way, make
  2984. sure to take this use of stack space into account when you are
  2985. calculating the size of the frame. Also, don't forget that the size of
  2986. the frame needs to be a multiple of 16 bytes.
  2987. \section{Challenge: Move Biasing}
  2988. \label{sec:move-biasing}
  2989. This section describes an optional enhancement to register allocation
  2990. for those students who are looking for an extra challenge or who have
  2991. a deeper interest in register allocation.
  2992. We return to the running example, but we remove the supposition that
  2993. we only have one register to use. So we have the following mapping of
  2994. color numbers to registers.
  2995. \[
  2996. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2997. \]
  2998. Using the same assignment of variables to color numbers that was
  2999. produced by the register allocator described in the last section, we
  3000. get the following program.
  3001. \begin{minipage}{0.3\textwidth}
  3002. \begin{lstlisting}
  3003. movq $1, v
  3004. movq $46, w
  3005. movq v, x
  3006. addq $7, x
  3007. movq x, y
  3008. addq $4, y
  3009. movq x, z
  3010. addq w, z
  3011. movq y, t.1
  3012. negq t.1
  3013. movq z, %rax
  3014. addq t.1, %rax
  3015. jmp conclusion
  3016. \end{lstlisting}
  3017. \end{minipage}
  3018. $\Rightarrow\qquad$
  3019. \begin{minipage}{0.45\textwidth}
  3020. \begin{lstlisting}
  3021. movq $1, %rbx
  3022. movq $46, %rdx
  3023. movq %rbx, %rcx
  3024. addq $7, %rcx
  3025. movq %rcx, %rbx
  3026. addq $4, %rbx
  3027. movq %rcx, %rcx
  3028. addq %rdx, %rcx
  3029. movq %rbx, %rbx
  3030. negq %rbx
  3031. movq %rcx, %rax
  3032. addq %rbx, %rax
  3033. jmp conclusion
  3034. \end{lstlisting}
  3035. \end{minipage}
  3036. While this allocation is quite good, we could do better. For example,
  3037. the variables \key{v} and \key{x} ended up in different registers, but
  3038. if they had been placed in the same register, then the move from
  3039. \key{v} to \key{x} could be removed.
  3040. We say that two variables $p$ and $q$ are \emph{move related} if they
  3041. participate together in a \key{movq} instruction, that is, \key{movq}
  3042. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3043. allocator chooses a color for a variable, it should prefer a color
  3044. that has already been used for a move-related variable (assuming that
  3045. they do not interfere). Of course, this preference should not override
  3046. the preference for registers over stack locations. This preference
  3047. should be used as a tie breaker when choosing between registers or
  3048. when choosing between stack locations.
  3049. We recommend representing the move relationships in a graph, similar
  3050. to how we represented interference. The following is the \emph{move
  3051. graph} for our running example.
  3052. \[
  3053. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3054. \node (v) at (0,0) {$v$};
  3055. \node (w) at (3,0) {$w$};
  3056. \node (x) at (6,0) {$x$};
  3057. \node (y) at (3,-1.5) {$y$};
  3058. \node (z) at (6,-1.5) {$z$};
  3059. \node (t1) at (9,-1.5) {$t.1$};
  3060. \draw[bend left=15] (t1) to (y);
  3061. \draw[bend left=15] (v) to (x);
  3062. \draw (x) to (y);
  3063. \draw (x) to (z);
  3064. \end{tikzpicture}
  3065. \]
  3066. Now we replay the graph coloring, pausing to see the coloring of $x$
  3067. and $v$. So we have the following coloring and the most saturated
  3068. vertex is $x$.
  3069. \[
  3070. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3071. \node (v) at (0,0) {$v:-,\{2\}$};
  3072. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3073. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3074. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3075. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3076. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3077. \draw (t1) to (z);
  3078. \draw (v) to (w);
  3079. \foreach \i in {w,x,y}
  3080. {
  3081. \foreach \j in {w,x,y}
  3082. {
  3083. \draw (\i) to (\j);
  3084. }
  3085. }
  3086. \draw (z) to (w);
  3087. \draw (z) to (y);
  3088. \end{tikzpicture}
  3089. \]
  3090. Last time we chose to color $x$ with $1$,
  3091. %
  3092. which so happens to be the color of $z$, and $x$ is move related to
  3093. $z$. This was lucky, and if the program had been a little different,
  3094. and say $z$ had been already assigned to $2$, then $x$ would still get
  3095. $1$ and our luck would have run out. With move biasing, we use the
  3096. fact that $x$ and $z$ are move related to influence the choice of
  3097. color for $x$, in this case choosing $1$ because that is the color of
  3098. $z$.
  3099. \[
  3100. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3101. \node (v) at (0,0) {$v:-,\{2\}$};
  3102. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3103. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3104. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3105. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3106. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3107. \draw (t1) to (z);
  3108. \draw (v) to (w);
  3109. \foreach \i in {w,x,y}
  3110. {
  3111. \foreach \j in {w,x,y}
  3112. {
  3113. \draw (\i) to (\j);
  3114. }
  3115. }
  3116. \draw (z) to (w);
  3117. \draw (z) to (y);
  3118. \end{tikzpicture}
  3119. \]
  3120. Next we consider coloring the variable $v$. We need to avoid choosing
  3121. $2$ because of the interference with $w$. Last time we chose the color
  3122. $0$ because it was the lowest, but this time we know that $v$ is move
  3123. related to $x$, so we choose the color $1$.
  3124. \[
  3125. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3126. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3127. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3128. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3129. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3130. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3131. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3132. \draw (t1) to (z);
  3133. \draw (v) to (w);
  3134. \foreach \i in {w,x,y}
  3135. {
  3136. \foreach \j in {w,x,y}
  3137. {
  3138. \draw (\i) to (\j);
  3139. }
  3140. }
  3141. \draw (z) to (w);
  3142. \draw (z) to (y);
  3143. \end{tikzpicture}
  3144. \]
  3145. We apply this register assignment to the running example, on the left,
  3146. to obtain the code on right.
  3147. \begin{minipage}{0.3\textwidth}
  3148. \begin{lstlisting}
  3149. movq $1, v
  3150. movq $46, w
  3151. movq v, x
  3152. addq $7, x
  3153. movq x, y
  3154. addq $4, y
  3155. movq x, z
  3156. addq w, z
  3157. movq y, t.1
  3158. negq t.1
  3159. movq z, %rax
  3160. addq t.1, %rax
  3161. jmp conclusion
  3162. \end{lstlisting}
  3163. \end{minipage}
  3164. $\Rightarrow\qquad$
  3165. \begin{minipage}{0.45\textwidth}
  3166. \begin{lstlisting}
  3167. movq $1, %rcx
  3168. movq $46, %rbx
  3169. movq %rcx, %rcx
  3170. addq $7, %rcx
  3171. movq %rcx, %rdx
  3172. addq $4, %rdx
  3173. movq %rcx, %rcx
  3174. addq %rbx, %rcx
  3175. movq %rdx, %rbx
  3176. negq %rbx
  3177. movq %rcx, %rax
  3178. addq %rbx, %rax
  3179. jmp conclusion
  3180. \end{lstlisting}
  3181. \end{minipage}
  3182. The \code{patch-instructions} then removes the trivial moves from
  3183. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3184. result.
  3185. \begin{minipage}{0.45\textwidth}
  3186. \begin{lstlisting}
  3187. movq $1 %rcx
  3188. movq $46 %rbx
  3189. addq $7 %rcx
  3190. movq %rcx %rdx
  3191. addq $4 %rdx
  3192. addq %rbx %rcx
  3193. movq %rdx %rbx
  3194. negq %rbx
  3195. movq %rcx %rax
  3196. addq %rbx %rax
  3197. jmp conclusion
  3198. \end{lstlisting}
  3199. \end{minipage}
  3200. \begin{exercise}\normalfont
  3201. Change your implementation of \code{allocate-registers} to take move
  3202. biasing into account. Make sure that your compiler still passes all of
  3203. the previous tests. Create two new tests that include at least one
  3204. opportunity for move biasing and visually inspect the output x86
  3205. programs to make sure that your move biasing is working properly.
  3206. \end{exercise}
  3207. \margincomment{\footnotesize To do: another neat challenge would be to do
  3208. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3209. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3210. \chapter{Booleans and Control Flow}
  3211. \label{ch:bool-types}
  3212. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3213. integers. In this chapter we add a second kind of value, the Booleans,
  3214. to create the $R_2$ language. The Boolean values \emph{true} and
  3215. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3216. Racket. The $R_2$ language includes several operations that involve
  3217. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3218. conditional \key{if} expression. With the addition of \key{if}
  3219. expressions, programs can have non-trivial control flow which which
  3220. significantly impacts the \code{explicate-control} and the liveness
  3221. analysis for register allocation. Also, because we now have two kinds
  3222. of values, we need to handle programs that apply an operation to the
  3223. wrong kind of value, such as \code{(not 1)}.
  3224. There are two language design options for such situations. One option
  3225. is to signal an error and the other is to provide a wider
  3226. interpretation of the operation. The Racket language uses a mixture of
  3227. these two options, depending on the operation and the kind of
  3228. value. For example, the result of \code{(not 1)} in Racket is
  3229. \code{\#f} because Racket treats non-zero integers as if they were
  3230. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3231. error in Racket stating that \code{car} expects a pair.
  3232. The Typed Racket language makes similar design choices as Racket,
  3233. except much of the error detection happens at compile time instead of
  3234. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3235. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3236. reports a compile-time error because Typed Racket expects the type of
  3237. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3238. For the $R_2$ language we choose to be more like Typed Racket in that
  3239. we shall perform type checking during compilation. In
  3240. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3241. is, how to compile a dynamically typed language like Racket. The
  3242. $R_2$ language is a subset of Typed Racket but by no means includes
  3243. all of Typed Racket. For many operations we take a narrower
  3244. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3245. This chapter is organized as follows. We begin by defining the syntax
  3246. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3247. then introduce the idea of type checking and build a type checker for
  3248. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3249. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3250. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3251. how our compiler passes need to change to accommodate Booleans and
  3252. conditional control flow.
  3253. \section{The $R_2$ Language}
  3254. \label{sec:r2-lang}
  3255. The concrete syntax of the $R_2$ language is defined in
  3256. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3257. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3258. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3259. and the conditional \code{if} expression. Also, we expand the
  3260. operators to include
  3261. \begin{enumerate}
  3262. \item subtraction on integers,
  3263. \item the logical operators \key{and}, \key{or} and \key{not},
  3264. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3265. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3266. comparing integers.
  3267. \end{enumerate}
  3268. \begin{figure}[tp]
  3269. \centering
  3270. \fbox{
  3271. \begin{minipage}{0.96\textwidth}
  3272. \[
  3273. \begin{array}{lcl}
  3274. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3275. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3276. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3277. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3278. &\mid& \itm{bool}
  3279. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3280. \mid (\key{not}\;\Exp) \\
  3281. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3282. R_2 &::=& \Exp
  3283. \end{array}
  3284. \]
  3285. \end{minipage}
  3286. }
  3287. \caption{The concrete syntax of $R_2$, extending $R_1$
  3288. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3289. \label{fig:r2-concrete-syntax}
  3290. \end{figure}
  3291. \begin{figure}[tp]
  3292. \centering
  3293. \fbox{
  3294. \begin{minipage}{0.96\textwidth}
  3295. \[
  3296. \begin{array}{lcl}
  3297. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3298. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3299. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3300. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3301. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3302. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3303. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3304. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3305. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3306. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3307. \end{array}
  3308. \]
  3309. \end{minipage}
  3310. }
  3311. \caption{The abstract syntax of $R_2$.}
  3312. \label{fig:r2-syntax}
  3313. \end{figure}
  3314. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3315. the parts that are the same as the interpreter for $R_1$
  3316. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3317. evaluate to the corresponding Boolean values. The conditional
  3318. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3319. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3320. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3321. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3322. you might expect, but note that the \code{and} operation is
  3323. short-circuiting. That is, given the expression
  3324. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3325. $e_1$ evaluates to \code{\#f}.
  3326. With the addition of the comparison operations, there are quite a few
  3327. primitive operations and the interpreter code for them could become
  3328. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3329. out the different parts of the code for primitive operations into the
  3330. \code{interp-op} function and the similar parts of the code into the
  3331. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3332. do not use \code{interp-op} for the \code{and} operation because of
  3333. the short-circuiting behavior in the order of evaluation of its
  3334. arguments.
  3335. \begin{figure}[tbp]
  3336. \begin{lstlisting}
  3337. (define (interp-op op)
  3338. (match op
  3339. ...
  3340. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3341. ['eq? (lambda (v1 v2)
  3342. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3343. (and (boolean? v1) (boolean? v2)))
  3344. (eq? v1 v2)]))]
  3345. ['< (lambda (v1 v2)
  3346. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3347. ['<= (lambda (v1 v2)
  3348. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3349. ['> (lambda (v1 v2)
  3350. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3351. ['>= (lambda (v1 v2)
  3352. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3353. [else (error 'interp-op "unknown operator")]))
  3354. (define (interp-exp env)
  3355. (lambda (e)
  3356. (define recur (interp-exp env))
  3357. (match e
  3358. ...
  3359. [(Bool b) b]
  3360. [(If cnd thn els)
  3361. (define b (recur cnd))
  3362. (match b
  3363. [#t (recur thn)]
  3364. [#f (recur els)])]
  3365. [(Prim 'and (list e1 e2))
  3366. (define v1 (recur e1))
  3367. (match v1
  3368. [#t (match (recur e2) [#t #t] [#f #f])]
  3369. [#f #f])]
  3370. [(Prim op args)
  3371. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3372. )))
  3373. (define (interp-R2 p)
  3374. (match p
  3375. [(Program info e)
  3376. ((interp-exp '()) e)]
  3377. ))
  3378. \end{lstlisting}
  3379. \caption{Interpreter for the $R_2$ language.}
  3380. \label{fig:interp-R2}
  3381. \end{figure}
  3382. \section{Type Checking $R_2$ Programs}
  3383. \label{sec:type-check-r2}
  3384. It is helpful to think about type checking in two complementary
  3385. ways. A type checker predicts the type of value that will be produced
  3386. by each expression in the program. For $R_2$, we have just two types,
  3387. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3388. \begin{lstlisting}
  3389. (+ 10 (- (+ 12 20)))
  3390. \end{lstlisting}
  3391. produces an \key{Integer} while
  3392. \begin{lstlisting}
  3393. (and (not #f) #t)
  3394. \end{lstlisting}
  3395. produces a \key{Boolean}.
  3396. Another way to think about type checking is that it enforces a set of
  3397. rules about which operators can be applied to which kinds of
  3398. values. For example, our type checker for $R_2$ will signal an error
  3399. for the below expression because, as we have seen above, the
  3400. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3401. checker enforces the rule that the argument of \code{not} must be a
  3402. \key{Boolean}.
  3403. \begin{lstlisting}
  3404. (not (+ 10 (- (+ 12 20))))
  3405. \end{lstlisting}
  3406. The type checker for $R_2$ is a structurally recursive function over
  3407. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3408. the \code{type-check-exp} function. Given an input expression
  3409. \code{e}, the type checker either returns a type (\key{Integer} or
  3410. \key{Boolean}) or it signals an error. The type of an integer literal
  3411. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3412. To handle variables, the type checker uses an environment that maps
  3413. variables to types. Consider the clause for \key{let}. We type check
  3414. the initializing expression to obtain its type \key{T} and then
  3415. associate type \code{T} with the variable \code{x} in the
  3416. environment. When the type checker encounters a use of variable
  3417. \code{x} in the body of the \key{let}, it can find its type in the
  3418. environment.
  3419. \begin{figure}[tbp]
  3420. \begin{lstlisting}
  3421. (define (type-check-exp env)
  3422. (lambda (e)
  3423. (match e
  3424. [(Var x) (dict-ref env x)]
  3425. [(Int n) 'Integer]
  3426. [(Bool b) 'Boolean]
  3427. [(Let x e body)
  3428. (define Te ((type-check-exp env) e))
  3429. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3430. Tb]
  3431. ...
  3432. [else
  3433. (error "type-check-exp couldn't match" e)])))
  3434. (define (type-check env)
  3435. (lambda (e)
  3436. (match e
  3437. [(Program info body)
  3438. (define Tb ((type-check-exp '()) body))
  3439. (unless (equal? Tb 'Integer)
  3440. (error "result of the program must be an integer, not " Tb))
  3441. (Program info body)]
  3442. )))
  3443. \end{lstlisting}
  3444. \caption{Skeleton of a type checker for the $R_2$ language.}
  3445. \label{fig:type-check-R2}
  3446. \end{figure}
  3447. \begin{exercise}\normalfont
  3448. Complete the implementation of \code{type-check-R2} and test it on 10
  3449. new example programs in $R_2$ that you choose based on how thoroughly
  3450. they test the type checking function. Half of the example programs
  3451. should have a type error to make sure that your type checker properly
  3452. rejects them. The other half of the example programs should not have
  3453. type errors. Your testing should check that the result of the type
  3454. checker agrees with the value returned by the interpreter, that is, if
  3455. the type checker returns \key{Integer}, then the interpreter should
  3456. return an integer. Likewise, if the type checker returns
  3457. \key{Boolean}, then the interpreter should return \code{\#t} or
  3458. \code{\#f}. Note that if your type checker does not signal an error
  3459. for a program, then interpreting that program should not encounter an
  3460. error. If it does, there is something wrong with your type checker.
  3461. \end{exercise}
  3462. \section{Shrink the $R_2$ Language}
  3463. \label{sec:shrink-r2}
  3464. The $R_2$ language includes several operators that are easily
  3465. expressible in terms of other operators. For example, subtraction is
  3466. expressible in terms of addition and negation.
  3467. \[
  3468. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3469. \]
  3470. Several of the comparison operations are expressible in terms of
  3471. less-than and logical negation.
  3472. \[
  3473. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3474. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3475. \]
  3476. The \key{let} is needed in the above translation to ensure that
  3477. expression $e_1$ is evaluated before $e_2$.
  3478. By performing these translations near the front-end of the compiler,
  3479. the later passes of the compiler do not need to deal with these
  3480. constructs, making those passes shorter. On the other hand, sometimes
  3481. these translations make it more difficult to generate the most
  3482. efficient code with respect to the number of instructions. However,
  3483. these differences typically do not affect the number of accesses to
  3484. memory, which is the primary factor that determines execution time on
  3485. modern computer architectures.
  3486. \begin{exercise}\normalfont
  3487. Implement the pass \code{shrink} that removes subtraction,
  3488. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3489. by translating them to other constructs in $R_2$. Create tests to
  3490. make sure that the behavior of all of these constructs stays the
  3491. same after translation.
  3492. \end{exercise}
  3493. \section{XOR, Comparisons, and Control Flow in x86}
  3494. \label{sec:x86-1}
  3495. To implement the new logical operations, the comparison operations,
  3496. and the \key{if} expression, we need to delve further into the x86
  3497. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3498. larger subset of x86 that includes instructions for logical
  3499. operations, comparisons, and jumps.
  3500. One small challenge is that x86 does not provide an instruction that
  3501. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3502. However, the \code{xorq} instruction can be used to encode \code{not}.
  3503. The \key{xorq} instruction takes two arguments, performs a pairwise
  3504. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3505. and writes the results into its second argument. Recall the truth
  3506. table for exclusive-or:
  3507. \begin{center}
  3508. \begin{tabular}{l|cc}
  3509. & 0 & 1 \\ \hline
  3510. 0 & 0 & 1 \\
  3511. 1 & 1 & 0
  3512. \end{tabular}
  3513. \end{center}
  3514. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3515. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3516. for the bit $1$, the result is the opposite of the second bit. Thus,
  3517. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3518. the first argument:
  3519. \[
  3520. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3521. \qquad\Rightarrow\qquad
  3522. \begin{array}{l}
  3523. \key{movq}~ \Arg\key{,} \Var\\
  3524. \key{xorq}~ \key{\$1,} \Var
  3525. \end{array}
  3526. \]
  3527. \begin{figure}[tp]
  3528. \fbox{
  3529. \begin{minipage}{0.96\textwidth}
  3530. \small
  3531. \[
  3532. \begin{array}{lcl}
  3533. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3534. \mid \BYTEREG{\code{'}\Reg} \\
  3535. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3536. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3537. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3538. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3539. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3540. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3541. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3542. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3543. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3544. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3545. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3546. &\mid& \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3547. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3548. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3549. \end{array}
  3550. \]
  3551. \end{minipage}
  3552. }
  3553. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3554. \label{fig:x86-1}
  3555. \end{figure}
  3556. Next we consider the x86 instructions that are relevant for compiling
  3557. the comparison operations. The \key{cmpq} instruction compares its two
  3558. arguments to determine whether one argument is less than, equal, or
  3559. greater than the other argument. The \key{cmpq} instruction is unusual
  3560. regarding the order of its arguments and where the result is
  3561. placed. The argument order is backwards: if you want to test whether
  3562. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3563. \key{cmpq} is placed in the special EFLAGS register. This register
  3564. cannot be accessed directly but it can be queried by a number of
  3565. instructions, including the \key{set} instruction. The \key{set}
  3566. instruction puts a \key{1} or \key{0} into its destination depending
  3567. on whether the comparison came out according to the condition code
  3568. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3569. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3570. The \key{set} instruction has an annoying quirk in that its
  3571. destination argument must be single byte register, such as \code{al},
  3572. which is part of the \code{rax} register. Thankfully, the
  3573. \key{movzbq} instruction can then be used to move from a single byte
  3574. register to a normal 64-bit register.
  3575. The x86 instruction for conditional jump are relevant to the
  3576. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3577. updates the program counter to point to the instruction after the
  3578. indicated label depending on whether the result in the EFLAGS register
  3579. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3580. instruction falls through to the next instruction. The abstract
  3581. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3582. that it separates the instruction name from the condition code. For
  3583. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3584. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3585. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3586. instruction to set the EFLAGS register.
  3587. \section{The $C_1$ Intermediate Language}
  3588. \label{sec:c1}
  3589. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3590. we need to grow that intermediate language to handle the new features
  3591. in $R_2$: Booleans and conditional expressions.
  3592. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3593. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3594. particular, we add logical and comparison operators to the $\Exp$
  3595. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3596. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3597. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3598. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3599. sequence of statements may now end with a \code{goto} or a conditional
  3600. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3601. depending on the outcome of the comparison. In
  3602. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3603. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3604. and \key{goto}'s.
  3605. \begin{figure}[tbp]
  3606. \fbox{
  3607. \begin{minipage}{0.96\textwidth}
  3608. \small
  3609. \[
  3610. \begin{array}{lcl}
  3611. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3612. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3613. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3614. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3615. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3616. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3617. \mid \key{goto}~\itm{label}\key{;}\\
  3618. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3619. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)^{+} }
  3620. \end{array}
  3621. \]
  3622. \end{minipage}
  3623. }
  3624. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3625. \label{fig:c1-concrete-syntax}
  3626. \end{figure}
  3627. \begin{figure}[tp]
  3628. \fbox{
  3629. \begin{minipage}{0.96\textwidth}
  3630. \small
  3631. \[
  3632. \begin{array}{lcl}
  3633. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3634. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3635. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3636. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3637. &\mid& \UNIOP{\key{'not}}{\Atm}
  3638. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3639. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3640. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3641. \mid \GOTO{\itm{label}} \\
  3642. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3643. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3644. \end{array}
  3645. \]
  3646. \end{minipage}
  3647. }
  3648. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3649. \label{fig:c1-syntax}
  3650. \end{figure}
  3651. \section{Explicate Control}
  3652. \label{sec:explicate-control-r2}
  3653. Recall that the purpose of \code{explicate-control} is to make the
  3654. order of evaluation explicit in the syntax of the program. With the
  3655. addition of \key{if} in $R_2$ this get more interesting.
  3656. As a motivating example, consider the following program that has an
  3657. \key{if} expression nested in the predicate of another \key{if}.
  3658. % s1_38.rkt
  3659. \begin{center}
  3660. \begin{minipage}{0.96\textwidth}
  3661. \begin{lstlisting}
  3662. (if (if (eq? (read) 1)
  3663. (eq? (read) 0)
  3664. (eq? (read) 2))
  3665. (+ 10 32)
  3666. (+ 700 77))
  3667. \end{lstlisting}
  3668. \end{minipage}
  3669. \end{center}
  3670. %
  3671. The naive way to compile \key{if} and \key{eq?} would be to handle
  3672. each of them in isolation, regardless of their context. Each
  3673. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3674. by a couple instructions to move the result from the EFLAGS register
  3675. into a general purpose register or stack location. Each \key{if} would
  3676. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3677. However, if we take context into account we can do better and reduce
  3678. the use of \key{cmpq} and EFLAG-accessing instructions.
  3679. One idea is to try and reorganize the code at the level of $R_2$,
  3680. pushing the outer \key{if} inside the inner one. This would yield the
  3681. following code.
  3682. \begin{center}
  3683. \begin{minipage}{0.96\textwidth}
  3684. \begin{lstlisting}
  3685. (if (eq? (read) 1)
  3686. (if (eq? (read) 0)
  3687. (+ 10 32)
  3688. (+ 700 77))
  3689. (if (eq? (read) 2))
  3690. (+ 10 32)
  3691. (+ 700 77))
  3692. \end{lstlisting}
  3693. \end{minipage}
  3694. \end{center}
  3695. Unfortunately, this approach duplicates the two branches, and a
  3696. compiler must never duplicate code!
  3697. We need a way to perform the above transformation, but without
  3698. duplicating code. The solution is straightforward if we think at the
  3699. level of x86 assembly: we can label the code for each of the branches
  3700. and insert jumps in all the places that need to execute the
  3701. branches. Put another way, we need to move away from abstract syntax
  3702. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3703. use a standard program representation called a \emph{control flow
  3704. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3705. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3706. each edge represents a jump to another block. The \key{Program}
  3707. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3708. as an alist mapping labels to basic blocks. Each block is
  3709. represented by the $\Tail$ non-terminal.
  3710. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3711. \code{remove-complex-opera*} pass and then the
  3712. \code{explicate-control} pass on the example program. We walk through
  3713. the output program and then discuss the algorithm.
  3714. %
  3715. Following the order of evaluation in the output of
  3716. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3717. comparison to \code{1} from the predicate of the inner \key{if}. In
  3718. the output of \code{explicate-control}, in the \code{start} block,
  3719. this becomes a \code{(read)} followed by a conditional \key{goto} to
  3720. either \code{block61} or \code{block62}. Each of these contains the
  3721. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3722. 1)}, respectively. Regarding \code{block61}, we start with the
  3723. \code{(read)} and comparison to \code{0} and then have a conditional
  3724. goto, either to \code{block59} or \code{block60}, which indirectly
  3725. take us to \code{block55} and \code{block56}, the two branches of the
  3726. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3727. story for \code{block62} is similar.
  3728. \begin{figure}[tbp]
  3729. \begin{tabular}{lll}
  3730. \begin{minipage}{0.4\textwidth}
  3731. \begin{lstlisting}
  3732. (if (if (eq? (read) 1)
  3733. (eq? (read) 0)
  3734. (eq? (read) 2))
  3735. (+ 10 32)
  3736. (+ 700 77))
  3737. \end{lstlisting}
  3738. \hspace{40pt}$\Downarrow$
  3739. \begin{lstlisting}
  3740. (if (if (let ([tmp52 (read)])
  3741. (eq? tmp52 1))
  3742. (let ([tmp53 (read)])
  3743. (eq? tmp53 0))
  3744. (let ([tmp54 (read)])
  3745. (eq? tmp54 2)))
  3746. (+ 10 32)
  3747. (+ 700 77))
  3748. \end{lstlisting}
  3749. \end{minipage}
  3750. &
  3751. $\Rightarrow$
  3752. &
  3753. \begin{minipage}{0.55\textwidth}
  3754. \begin{lstlisting}
  3755. block62:
  3756. tmp54 = (read);
  3757. if (eq? tmp54 2) then
  3758. goto block59;
  3759. else
  3760. goto block60;
  3761. block61:
  3762. tmp53 = (read);
  3763. if (eq? tmp53 0) then
  3764. goto block57;
  3765. else
  3766. goto block58;
  3767. block60:
  3768. goto block56;
  3769. block59:
  3770. goto block55;
  3771. block58:
  3772. goto block56;
  3773. block57:
  3774. goto block55;
  3775. block56:
  3776. return (+ 700 77);
  3777. block55:
  3778. return (+ 10 32);
  3779. start:
  3780. tmp52 = (read);
  3781. if (eq? tmp52 1) then
  3782. goto block61;
  3783. else
  3784. goto block62;
  3785. \end{lstlisting}
  3786. \end{minipage}
  3787. \end{tabular}
  3788. \caption{Example translation from $R_2$ to $C_1$
  3789. via the \code{explicate-control}.}
  3790. \label{fig:explicate-control-s1-38}
  3791. \end{figure}
  3792. The nice thing about the output of \code{explicate-control} is that
  3793. there are no unnecessary uses of \code{eq?} and every use of
  3794. \code{eq?} is part of a conditional jump. The down-side of this output
  3795. is that it includes trivial blocks, such as \code{block57} through
  3796. \code{block60}, that only jump to another block. We discuss a solution
  3797. to this problem in Section~\ref{sec:opt-jumps}.
  3798. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3799. \code{explicate-control} for $R_1$ using two mutually recursive
  3800. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3801. former function translates expressions in tail position whereas the
  3802. later function translates expressions on the right-hand-side of a
  3803. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3804. new kind of context to deal with: the predicate position of the
  3805. \key{if}. We need another function, \code{explicate-pred}, that takes
  3806. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3807. the then-branch and else-branch. The output of \code{explicate-pred}
  3808. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3809. Note that the three explicate functions need to construct a
  3810. control-flow graph, which we recommend they do via updates to a global
  3811. variable.
  3812. In the following paragraphs we consider the specific additions to the
  3813. \code{explicate-tail} and \code{explicate-assign} functions, and some
  3814. of cases for the \code{explicate-pred} function.
  3815. The \code{explicate-tail} function needs an additional case for
  3816. \key{if}. The branches of the \key{if} inherit the current context, so
  3817. they are in tail position. Let $B_1$ be the result of
  3818. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3819. be the result of apply \code{explicate-tail} to the ``else''
  3820. branch. Then the \key{if} as a whole translates to the block $B_3$
  3821. which is the result of applying \code{explicate-pred} to the predicate
  3822. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3823. \[
  3824. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3825. \]
  3826. Next we consider the case for \key{if} in the \code{explicate-assign}
  3827. function. The context of the \key{if} is an assignment to some
  3828. variable $x$ and then the control continues to some block $B_1$. The
  3829. code that we generate for the ``then'' and ``else'' branches needs to
  3830. continue to $B_1$, so we add $B_1$ to the control flow graph with a
  3831. fresh label $\ell_1$. Again, the branches of the \key{if} inherit the
  3832. current context, so that are in assignment positions. Let $B_2$ be
  3833. the result of applying \code{explicate-assign} to the ``then'' branch,
  3834. variable $x$, and the block \GOTO{$\ell_1$}. Let $B_3$ be the result
  3835. of applying \code{explicate-assign} to the ``else'' branch, variable
  3836. $x$, and the block \GOTO{$\ell_1$}. The \key{if} translates to the
  3837. block $B_4$ which is the result of applying \code{explicate-pred} to
  3838. the predicate $\itm{cnd}$ and the blocks $B_2$ and $B_3$.
  3839. \[
  3840. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3841. \]
  3842. The function \code{explicate-pred} will need a case for every
  3843. expression that can have type \code{Boolean}. We detail a few cases
  3844. here and leave the rest for the reader. The input to this function is
  3845. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  3846. the enclosing \key{if}. Suppose the expression is the Boolean
  3847. \code{\#t}. Then we can perform a kind of partial evaluation and
  3848. translate it to the ``then'' branch $B_1$. Likewise, we translate
  3849. \code{\#f} to the ``else`` branch $B_2$.
  3850. \[
  3851. \key{\#t} \quad\Rightarrow\quad B_1,
  3852. \qquad\qquad\qquad
  3853. \key{\#f} \quad\Rightarrow\quad B_2
  3854. \]
  3855. Next, suppose the expression is a less-than comparison. We translate
  3856. it to a conditional \code{goto}. We need labels for the two branches
  3857. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  3858. obtain some labels $\ell_1$ and $\ell_2$. The translation of the
  3859. less-than comparison is as follows.
  3860. \[
  3861. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3862. \begin{array}{l}
  3863. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3864. \qquad\key{goto}~\ell_1\key{;}\\
  3865. \key{else}\\
  3866. \qquad\key{goto}~\ell_2\key{;}
  3867. \end{array}
  3868. \]
  3869. The case for \key{if} in \code{explicate-pred} is particularly
  3870. illuminating as it deals with the challenges that we discussed above
  3871. regarding the example of the nested \key{if} expressions. Again, we
  3872. add the two branches $B_1$ and $B_2$ to the control flow graph and
  3873. obtain the labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  3874. branches of the current \key{if} inherit their context from the
  3875. current one, that is, predicate context. So we apply
  3876. \code{explicate-pred} to the ``then'' branch with the two blocks
  3877. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  3878. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  3879. apply \code{explicate-pred} to the predicate of hte \code{if} and the
  3880. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  3881. \[
  3882. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3883. \quad\Rightarrow\quad
  3884. B_5
  3885. \]
  3886. \begin{exercise}\normalfont
  3887. Implement the pass \code{explicate-control} by adding the cases for
  3888. \key{if} to the functions for tail and assignment contexts, and
  3889. implement \code{explicate-pred} for predicate contexts. Create test
  3890. cases that exercise all of the new cases in the code for this pass.
  3891. \end{exercise}
  3892. \section{Select Instructions}
  3893. \label{sec:select-r2}
  3894. Recall that the \code{select-instructions} pass lowers from our
  3895. $C$-like intermediate representation to the pseudo-x86 language, which
  3896. is suitable for conducting register allocation. The pass is
  3897. implemented using three auxiliary functions, one for each of the
  3898. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3899. For $\Atm$, we have new cases for the Booleans. We take the usual
  3900. approach of encoding them as integers, with true as 1 and false as 0.
  3901. \[
  3902. \key{\#t} \Rightarrow \key{1}
  3903. \qquad
  3904. \key{\#f} \Rightarrow \key{0}
  3905. \]
  3906. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3907. be implemented in terms of \code{xorq} as we discussed at the
  3908. beginning of this section. Given an assignment
  3909. $\itm{var}$ \key{=} \key{(not} $\Arg$\key{);},
  3910. if the left-hand side $\itm{var}$ is
  3911. the same as $\Arg$, then just the \code{xorq} suffices.
  3912. \[
  3913. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  3914. \quad\Rightarrow\quad
  3915. \key{xorq}~\key{\$}1\key{,}~\Var
  3916. \]
  3917. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3918. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3919. $\Arg$. Then we have
  3920. \[
  3921. \Var~\key{=}~ \key{(not}\; \Arg\key{);}
  3922. \quad\Rightarrow\quad
  3923. \begin{array}{l}
  3924. \key{movq}~\Arg'\key{,}~\Var\\
  3925. \key{xorq}~\key{\$}1\key{,}~\Var
  3926. \end{array}
  3927. \]
  3928. Next consider the cases for \code{eq?} and less-than comparison.
  3929. Translating these operations to x86 is slightly involved due to the
  3930. unusual nature of the \key{cmpq} instruction discussed above. We
  3931. recommend translating an assignment from \code{eq?} into the following
  3932. sequence of three instructions. \\
  3933. \begin{tabular}{lll}
  3934. \begin{minipage}{0.4\textwidth}
  3935. \begin{lstlisting}
  3936. |$\Var$| = (eq? |$\Arg_1$| |$\Arg_2$|);
  3937. \end{lstlisting}
  3938. \end{minipage}
  3939. &
  3940. $\Rightarrow$
  3941. &
  3942. \begin{minipage}{0.4\textwidth}
  3943. \begin{lstlisting}
  3944. cmpq |$\Arg'_2$|, |$\Arg'_1$|
  3945. sete %al
  3946. movzbq %al, |$\Var$|
  3947. \end{lstlisting}
  3948. \end{minipage}
  3949. \end{tabular} \\
  3950. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  3951. and conditional \key{goto}. Both are straightforward to handle. A
  3952. \key{goto} becomes a jump instruction.
  3953. \[
  3954. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  3955. \]
  3956. A conditional \key{goto} becomes a compare instruction followed
  3957. by a conditional jump (for ``then'') and the fall-through is
  3958. to a regular jump (for ``else'').\\
  3959. \begin{tabular}{lll}
  3960. \begin{minipage}{0.4\textwidth}
  3961. \begin{lstlisting}
  3962. if (eq? |$\Arg_1$| |$\Arg_2$|) then
  3963. goto |$\ell_1$|;
  3964. else
  3965. goto |$\ell_2$|;
  3966. \end{lstlisting}
  3967. \end{minipage}
  3968. &
  3969. $\Rightarrow$
  3970. &
  3971. \begin{minipage}{0.4\textwidth}
  3972. \begin{lstlisting}
  3973. cmpq |$\Arg'_2$| |$\Arg'_1$|
  3974. je |$\ell_1$|
  3975. jmp |$\ell_2$|
  3976. \end{lstlisting}
  3977. \end{minipage}
  3978. \end{tabular} \\
  3979. \begin{exercise}\normalfont
  3980. Expand your \code{select-instructions} pass to handle the new features
  3981. of the $R_2$ language. Test the pass on all the examples you have
  3982. created and make sure that you have some test programs that use the
  3983. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3984. the output using the \code{interp-x86} interpreter
  3985. (Appendix~\ref{appendix:interp}).
  3986. \end{exercise}
  3987. \section{Register Allocation}
  3988. \label{sec:register-allocation-r2}
  3989. The changes required for $R_2$ affect liveness analysis, building the
  3990. interference graph, and assigning homes, but the graph coloring
  3991. algorithm itself does not change.
  3992. \subsection{Liveness Analysis}
  3993. \label{sec:liveness-analysis-r2}
  3994. Recall that for $R_1$ we implemented liveness analysis for a single
  3995. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3996. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3997. produces many basic blocks arranged in a control-flow graph. The first
  3998. question we need to consider is: what order should we process the
  3999. basic blocks? Recall that to perform liveness analysis, we need to
  4000. know the live-after set. If a basic block has no successor blocks
  4001. (i.e. no out-edges in the control flow graph), then it has an empty
  4002. live-after set and we can immediately apply liveness analysis to
  4003. it. If a basic block has some successors, then we need to complete
  4004. liveness analysis on those blocks first. Furthermore, we know that
  4005. the control flow graph does not contain any cycles because $R_2$ does
  4006. not include loops
  4007. %
  4008. \footnote{If we were to add loops to the language, then the CFG could
  4009. contain cycles and we would instead need to use the classic worklist
  4010. algorithm for computing the fixed point of the liveness
  4011. analysis~\citep{Aho:1986qf}.}.
  4012. %
  4013. Returning to the question of what order should we process the basic
  4014. blocks, the answer is reverse topological order. We recommend using
  4015. the \code{tsort} (topological sort) and \code{transpose} functions of
  4016. the Racket \code{graph} package to obtain this ordering.
  4017. The next question is how to compute the live-after set of a block
  4018. given the live-before sets of all its successor blocks. (There can be
  4019. more than one because of conditional jumps.) During compilation we do
  4020. not know which way a conditional jump will go, so we do not know which
  4021. of the successor's live-before set to use. The solution to this
  4022. challenge is based on the observation that there is no harm to the
  4023. correctness of the compiler if we classify more variables as live than
  4024. the ones that are truly live during a particular execution of the
  4025. block. Thus, we can take the union of the live-before sets from all
  4026. the successors to be the live-after set for the block. Once we have
  4027. computed the live-after set, we can proceed to perform liveness
  4028. analysis on the block just as we did in
  4029. Section~\ref{sec:liveness-analysis-r1}.
  4030. The helper functions for computing the variables in an instruction's
  4031. argument and for computing the variables read-from ($R$) or written-to
  4032. ($W$) by an instruction need to be updated to handle the new kinds of
  4033. arguments and instructions in x86$_1$.
  4034. \subsection{Build Interference}
  4035. \label{sec:build-interference-r2}
  4036. Many of the new instructions in x86$_1$ can be handled in the same way
  4037. as the instructions in x86$_0$. Thus, if your code was already quite
  4038. general, it will not need to be changed to handle the new
  4039. instructions. If you code is not general enough, I recommend that you
  4040. change your code to be more general. For example, you can factor out
  4041. the computing of the the read and write sets for each kind of
  4042. instruction into two auxiliary functions.
  4043. Note that the \key{movzbq} instruction requires some special care,
  4044. just like the \key{movq} instruction. See rule number 3 in
  4045. Section~\ref{sec:build-interference}.
  4046. %% \subsection{Assign Homes}
  4047. %% \label{sec:assign-homes-r2}
  4048. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4049. %% to be updated to handle the \key{if} statement, simply by recursively
  4050. %% processing the child nodes. Hopefully your code already handles the
  4051. %% other new instructions, but if not, you can generalize your code.
  4052. \begin{exercise}\normalfont
  4053. Update the \code{register-allocation} pass so that it works for $R_2$
  4054. and test your compiler using your previously created programs on the
  4055. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4056. \end{exercise}
  4057. \section{Patch Instructions}
  4058. The second argument of the \key{cmpq} instruction must not be an
  4059. immediate value (such as an integer). So if you are comparing two
  4060. immediates, we recommend inserting a \key{movq} instruction to put the
  4061. second argument in \key{rax}.
  4062. %
  4063. The second argument of the \key{movzbq} must be a register.
  4064. %
  4065. There are no special restrictions on the x86 instructions \key{JmpIf}
  4066. and \key{Jmp}.
  4067. \begin{exercise}\normalfont
  4068. Update \code{patch-instructions} to handle the new x86 instructions.
  4069. Test your compiler using your previously created programs on the
  4070. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4071. \end{exercise}
  4072. \section{An Example Translation}
  4073. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4074. $R_2$ translated to x86, showing the results of
  4075. \code{explicate-control}, \code{select-instructions}, and the final
  4076. x86 assembly code.
  4077. \begin{figure}[tbp]
  4078. \begin{tabular}{lll}
  4079. \begin{minipage}{0.5\textwidth}
  4080. % s1_20.rkt
  4081. \begin{lstlisting}
  4082. (if (eq? (read) 1) 42 0)
  4083. \end{lstlisting}
  4084. $\Downarrow$
  4085. \begin{lstlisting}
  4086. start:
  4087. tmp7951 = (read);
  4088. if (eq? tmp7951 1) then
  4089. goto block7952;
  4090. else
  4091. goto block7953;
  4092. block7952:
  4093. return 42;
  4094. block7953:
  4095. return 0;
  4096. \end{lstlisting}
  4097. $\Downarrow$
  4098. \begin{lstlisting}
  4099. start:
  4100. callq read_int
  4101. movq %rax, tmp7951
  4102. cmpq $1, tmp7951
  4103. je block7952
  4104. jmp block7953
  4105. block7953:
  4106. movq $0, %rax
  4107. jmp conclusion
  4108. block7952:
  4109. movq $42, %rax
  4110. jmp conclusion
  4111. \end{lstlisting}
  4112. \end{minipage}
  4113. &
  4114. $\Rightarrow\qquad$
  4115. \begin{minipage}{0.4\textwidth}
  4116. \begin{lstlisting}
  4117. start:
  4118. callq read_int
  4119. movq %rax, %rcx
  4120. cmpq $1, %rcx
  4121. je block7952
  4122. jmp block7953
  4123. block7953:
  4124. movq $0, %rax
  4125. jmp conclusion
  4126. block7952:
  4127. movq $42, %rax
  4128. jmp conclusion
  4129. .globl main
  4130. main:
  4131. pushq %rbp
  4132. movq %rsp, %rbp
  4133. pushq %r13
  4134. pushq %r12
  4135. pushq %rbx
  4136. pushq %r14
  4137. subq $0, %rsp
  4138. jmp start
  4139. conclusion:
  4140. addq $0, %rsp
  4141. popq %r14
  4142. popq %rbx
  4143. popq %r12
  4144. popq %r13
  4145. popq %rbp
  4146. retq
  4147. \end{lstlisting}
  4148. \end{minipage}
  4149. \end{tabular}
  4150. \caption{Example compilation of an \key{if} expression to x86.}
  4151. \label{fig:if-example-x86}
  4152. \end{figure}
  4153. \begin{figure}[p]
  4154. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4155. \node (R2) at (0,2) {\large $R_2$};
  4156. \node (R2-2) at (3,2) {\large $R_2$};
  4157. \node (R2-3) at (6,2) {\large $R_2$};
  4158. \node (R2-4) at (9,2) {\large $R_2$};
  4159. \node (R2-5) at (12,2) {\large $R_2$};
  4160. \node (C1-1) at (6,0) {\large $C_1$};
  4161. %\node (C1-2) at (3,0) {\large $C_1$};
  4162. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4163. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4164. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4165. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4166. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4167. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4168. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4169. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4170. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4171. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4172. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4173. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4174. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4175. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4176. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4177. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4178. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4179. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4180. \end{tikzpicture}
  4181. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4182. \label{fig:R2-passes}
  4183. \end{figure}
  4184. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4185. compilation of $R_2$.
  4186. \section{Challenge: Optimize Jumps}
  4187. \label{sec:opt-jumps}
  4188. Recall that in the example output of \code{explicate-control} in
  4189. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4190. \code{block60} are trivial blocks, they do nothing but jump to another
  4191. block. The first goal of this challenge assignment is to remove those
  4192. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4193. \code{explicate-control} on the left and shows the result of bypassing
  4194. the trivial blocks on the right. Let us focus on \code{block61}. The
  4195. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4196. \code{block55}. The optimized code on the right of
  4197. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4198. \code{then} branch jumping directly to \code{block55}. The story is
  4199. similar for the \code{else} branch, as well as for the two branches in
  4200. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4201. have been optimized in this way, there are no longer any jumps to
  4202. blocks \code{block57} through \code{block60}, so they can be removed.
  4203. \begin{figure}[tbp]
  4204. \begin{tabular}{lll}
  4205. \begin{minipage}{0.4\textwidth}
  4206. \begin{lstlisting}
  4207. block62:
  4208. tmp54 = (read);
  4209. if (eq? tmp54 2) then
  4210. goto block59;
  4211. else
  4212. goto block60;
  4213. block61:
  4214. tmp53 = (read);
  4215. if (eq? tmp53 0) then
  4216. goto block57;
  4217. else
  4218. goto block58;
  4219. block60:
  4220. goto block56;
  4221. block59:
  4222. goto block55;
  4223. block58:
  4224. goto block56;
  4225. block57:
  4226. goto block55;
  4227. block56:
  4228. return (+ 700 77);
  4229. block55:
  4230. return (+ 10 32);
  4231. start:
  4232. tmp52 = (read);
  4233. if (eq? tmp52 1) then
  4234. goto block61;
  4235. else
  4236. goto block62;
  4237. \end{lstlisting}
  4238. \end{minipage}
  4239. &
  4240. $\Rightarrow$
  4241. &
  4242. \begin{minipage}{0.55\textwidth}
  4243. \begin{lstlisting}
  4244. block62:
  4245. tmp54 = (read);
  4246. if (eq? tmp54 2) then
  4247. goto block55;
  4248. else
  4249. goto block56;
  4250. block61:
  4251. tmp53 = (read);
  4252. if (eq? tmp53 0) then
  4253. goto block55;
  4254. else
  4255. goto block56;
  4256. block56:
  4257. return (+ 700 77);
  4258. block55:
  4259. return (+ 10 32);
  4260. start:
  4261. tmp52 = (read);
  4262. if (eq? tmp52 1) then
  4263. goto block61;
  4264. else
  4265. goto block62;
  4266. \end{lstlisting}
  4267. \end{minipage}
  4268. \end{tabular}
  4269. \caption{Optimize jumps by removing trivial blocks.}
  4270. \label{fig:optimize-jumps}
  4271. \end{figure}
  4272. The name of this pass is \code{optimize-jumps}. We recommend
  4273. implementing this pass in two phases. The first phrase builds a hash
  4274. table that maps labels to possibly improved labels. The second phase
  4275. changes the target of each \code{goto} to use the improved label. If
  4276. the label is for a trivial block, then the hash table should map the
  4277. label to the first non-trivial block that can be reached from this
  4278. label by jumping through trivial blocks. If the label is for a
  4279. non-trivial block, then the hash table should map the label to itself;
  4280. we do not want to change jumps to non-trivial blocks.
  4281. The first phase can be accomplished by constructing an empty hash
  4282. table, call it \code{short-cut}, and then iterating over the control
  4283. flow graph. Each time you encouter a block that is just a \code{goto},
  4284. then update the hash table, mapping the block's source to the target
  4285. of the \code{goto}. Also, the hash table may already have mapped some
  4286. labels to the block's source, to you must iterate through the hash
  4287. table and update all of those so that they instead map to the target
  4288. of the \code{goto}.
  4289. For the second phase, we recommend iterating through the $\Tail$ of
  4290. each block in the program, updating the target of every \code{goto}
  4291. according to the mapping in \code{short-cut}.
  4292. \begin{exercise}\normalfont
  4293. Implement the \code{optimize-jumps} pass and check that it remove
  4294. trivial blocks in a few example programs. Then check that your
  4295. compiler still passes all of your tests.
  4296. \end{exercise}
  4297. There is another opportunity for optimizing jumps that is apparent in
  4298. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4299. end with a jump to \code{block7953} and there are no other jumps to
  4300. \code{block7953} in the rest of the program. In this situation we can
  4301. avoid the runtime overhead of this jump by merging \code{block7953}
  4302. into the preceeding block, in this case the \code{start} block.
  4303. Figure~\ref{fig:remove-jumps} shows the output of
  4304. \code{select-instructions} on the left and the result of this
  4305. optimization on the right.
  4306. \begin{figure}[tbp]
  4307. \begin{tabular}{lll}
  4308. \begin{minipage}{0.5\textwidth}
  4309. % s1_20.rkt
  4310. \begin{lstlisting}
  4311. start:
  4312. callq read_int
  4313. movq %rax, tmp7951
  4314. cmpq $1, tmp7951
  4315. je block7952
  4316. jmp block7953
  4317. block7953:
  4318. movq $0, %rax
  4319. jmp conclusion
  4320. block7952:
  4321. movq $42, %rax
  4322. jmp conclusion
  4323. \end{lstlisting}
  4324. \end{minipage}
  4325. &
  4326. $\Rightarrow\qquad$
  4327. \begin{minipage}{0.4\textwidth}
  4328. \begin{lstlisting}
  4329. start:
  4330. callq read_int
  4331. movq %rax, tmp7951
  4332. cmpq $1, tmp7951
  4333. je block7952
  4334. movq $0, %rax
  4335. jmp conclusion
  4336. block7952:
  4337. movq $42, %rax
  4338. jmp conclusion
  4339. \end{lstlisting}
  4340. \end{minipage}
  4341. \end{tabular}
  4342. \caption{Merging basic blocks by removing unnecessary jumps.}
  4343. \label{fig:remove-jumps}
  4344. \end{figure}
  4345. \begin{exercise}\normalfont
  4346. Implement a pass named \code{remove-jumps} that merges basic blocks
  4347. into their preceeding basic block, when there is only one preceeding
  4348. block. Check that your pass accomplishes this goal on several test
  4349. programs and check that your compiler passes all of your tests.
  4350. \end{exercise}
  4351. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4352. \chapter{Tuples and Garbage Collection}
  4353. \label{ch:tuples}
  4354. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4355. things to discuss in this chapter. \\ --Jeremy}
  4356. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4357. all the IR grammars are spelled out! \\ --Jeremy}
  4358. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4359. but keep type annotations on vector creation and local variables, function
  4360. parameters, etc. \\ --Jeremy}
  4361. \margincomment{\scriptsize Be more explicit about how to deal with
  4362. the root stack. \\ --Jeremy}
  4363. In this chapter we study the implementation of mutable tuples (called
  4364. ``vectors'' in Racket). This language feature is the first to use the
  4365. computer's \emph{heap} because the lifetime of a Racket tuple is
  4366. indefinite, that is, a tuple lives forever from the programmer's
  4367. viewpoint. Of course, from an implementer's viewpoint, it is important
  4368. to reclaim the space associated with a tuple when it is no longer
  4369. needed, which is why we also study \emph{garbage collection}
  4370. techniques in this chapter.
  4371. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4372. interpreter and type checker. The $R_3$ language extends the $R_2$
  4373. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4374. \code{void} value. The reason for including the later is that the
  4375. \code{vector-set!} operation returns a value of type
  4376. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4377. called the \code{Unit} type in the programming languages
  4378. literature. Racket's \code{Void} type is inhabited by a single value
  4379. \code{void} which corresponds to \code{unit} or \code{()} in the
  4380. literature~\citep{Pierce:2002hj}.}.
  4381. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4382. copying live objects back and forth between two halves of the
  4383. heap. The garbage collector requires coordination with the compiler so
  4384. that it can see all of the \emph{root} pointers, that is, pointers in
  4385. registers or on the procedure call stack.
  4386. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4387. discuss all the necessary changes and additions to the compiler
  4388. passes, including a new compiler pass named \code{expose-allocation}.
  4389. \section{The $R_3$ Language}
  4390. \label{sec:r3}
  4391. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4392. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4393. $R_3$ language includes three new forms for creating a tuple, reading
  4394. an element of a tuple, and writing to an element of a tuple. The
  4395. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4396. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4397. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4398. first-class values. The element at index $1$ of \code{t} is
  4399. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4400. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4401. element at index $0$ of the 1-tuple. So the result of the program is
  4402. $42$.
  4403. \begin{figure}[tbp]
  4404. \begin{lstlisting}
  4405. (let ([t (vector 40 #t (vector 2))])
  4406. (if (vector-ref t 1)
  4407. (+ (vector-ref t 0)
  4408. (vector-ref (vector-ref t 2) 0))
  4409. 44))
  4410. \end{lstlisting}
  4411. \caption{Example program that creates tuples and reads from them.}
  4412. \label{fig:vector-eg}
  4413. \end{figure}
  4414. \begin{figure}[tbp]
  4415. \centering
  4416. \fbox{
  4417. \begin{minipage}{0.96\textwidth}
  4418. \[
  4419. \begin{array}{lcl}
  4420. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4421. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4422. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4423. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4424. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4425. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4426. \mid (\key{and}\;\Exp\;\Exp)
  4427. \mid (\key{or}\;\Exp\;\Exp)
  4428. \mid (\key{not}\;\Exp) } \\
  4429. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4430. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4431. &\mid& (\key{vector}\;\Exp^{+})
  4432. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4433. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4434. &\mid& (\key{void}) \\
  4435. R_3 &::=& \Exp
  4436. \end{array}
  4437. \]
  4438. \end{minipage}
  4439. }
  4440. \caption{The concrete syntax of $R_3$, extending $R_2$
  4441. (Figure~\ref{fig:r2-concrete-syntax}).}
  4442. \label{fig:r3-concrete-syntax}
  4443. \end{figure}
  4444. \begin{figure}[tp]
  4445. \centering
  4446. \fbox{
  4447. \begin{minipage}{0.96\textwidth}
  4448. \[
  4449. \begin{array}{lcl}
  4450. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4451. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4452. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4453. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4454. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4455. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4456. &\mid& \gray{ \BOOL{\itm{bool}}
  4457. \mid \AND{\Exp}{\Exp} }\\
  4458. &\mid& \gray{ \OR{\Exp}{\Exp}
  4459. \mid \NOT{\Exp} } \\
  4460. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4461. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4462. &\mid& \VECTOR{\Exp} \\
  4463. &\mid& \VECREF{\Exp}{\Int}\\
  4464. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4465. &\mid& \VOID{} \\
  4466. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4467. \end{array}
  4468. \]
  4469. \end{minipage}
  4470. }
  4471. \caption{The abstract syntax of $R_3$.}
  4472. \label{fig:r3-syntax}
  4473. \end{figure}
  4474. Tuples are our first encounter with heap-allocated data, which raises
  4475. several interesting issues. First, variable binding performs a
  4476. shallow-copy when dealing with tuples, which means that different
  4477. variables can refer to the same tuple, i.e., different variables can
  4478. be \emph{aliases} for the same thing. Consider the following example
  4479. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4480. the mutation through \code{t2} is visible when referencing the tuple
  4481. from \code{t1}, so the result of this program is \code{42}.
  4482. \begin{center}
  4483. \begin{minipage}{0.96\textwidth}
  4484. \begin{lstlisting}
  4485. (let ([t1 (vector 3 7)])
  4486. (let ([t2 t1])
  4487. (let ([_ (vector-set! t2 0 42)])
  4488. (vector-ref t1 0))))
  4489. \end{lstlisting}
  4490. \end{minipage}
  4491. \end{center}
  4492. The next issue concerns the lifetime of tuples. Of course, they are
  4493. created by the \code{vector} form, but when does their lifetime end?
  4494. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4495. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4496. is not tied to any notion of static scoping. For example, the
  4497. following program returns \code{3} even though the variable \code{t}
  4498. goes out of scope prior to accessing the vector.
  4499. \begin{center}
  4500. \begin{minipage}{0.96\textwidth}
  4501. \begin{lstlisting}
  4502. (vector-ref
  4503. (let ([t (vector 3 7)])
  4504. t)
  4505. 0)
  4506. \end{lstlisting}
  4507. \end{minipage}
  4508. \end{center}
  4509. From the perspective of programmer-observable behavior, tuples live
  4510. forever. Of course, if they really lived forever, then many programs
  4511. would run out of memory.\footnote{The $R_3$ language does not have
  4512. looping or recursive function, so it is nigh impossible to write a
  4513. program in $R_3$ that will run out of memory. However, we add
  4514. recursive functions in the next Chapter!} A Racket implementation
  4515. must therefore perform automatic garbage collection.
  4516. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4517. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4518. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4519. operations in Racket. One subtle point is that the \code{vector-set!}
  4520. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4521. can be passed around just like other values inside an $R_3$ program,
  4522. but there are no operations specific to the the \code{\#<void>} value
  4523. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4524. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4525. otherwise.
  4526. \begin{figure}[tbp]
  4527. \begin{lstlisting}
  4528. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4529. (define (interp-op op)
  4530. (match op
  4531. ...
  4532. ['vector vector]
  4533. ['vector-ref vector-ref]
  4534. ['vector-set! vector-set!]
  4535. [else (error 'interp-op "unknown operator")]))
  4536. (define (interp-R3 env)
  4537. (lambda (e)
  4538. (match e
  4539. ...
  4540. [else (error 'interp-R3 "unrecognized expression")]
  4541. )))
  4542. \end{lstlisting}
  4543. \caption{Interpreter for the $R_3$ language.}
  4544. \label{fig:interp-R3}
  4545. \end{figure}
  4546. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4547. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4548. need to know which variables are pointers into the heap, that is,
  4549. which variables are vectors. Also, when allocating a vector, we need
  4550. to know which elements of the vector are pointers. We can obtain this
  4551. information during type checking. The type checker in
  4552. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4553. expression, it also wraps every sub-expression $e$ with the form
  4554. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4555. % TODO: UPDATE? -Jeremy
  4556. Subsequently, in the \code{uncover-locals} pass
  4557. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4558. propagated to all variables (including the temporaries generated by
  4559. \code{remove-complex-opera*}).
  4560. \begin{figure}[tbp]
  4561. \begin{lstlisting}
  4562. (define (type-check-exp env)
  4563. (lambda (e)
  4564. (define recur (type-check-exp env))
  4565. (match e
  4566. ...
  4567. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4568. [(Prim 'vector es)
  4569. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4570. (recur e)))
  4571. (let ([t `(Vector ,@t*)])
  4572. (values (HasType (Prim 'vector e*) t) t))]
  4573. [(Prim 'vector-ref (list e (Int i)))
  4574. (define-values (e^ t) (recur e))
  4575. (match t
  4576. [`(Vector ,ts ...)
  4577. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4578. (error 'type-check-exp "invalid index ~a" i))
  4579. (let ([t (list-ref ts i)])
  4580. (values
  4581. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4582. t))]
  4583. [else (error "expected a vector in vector-ref, not" t)])]
  4584. [(Prim 'eq? (list e1 e2))
  4585. (define-values (e1^ T1) (recur e1))
  4586. (define-values (e2^ T2) (recur e2))
  4587. (unless (equal? T1 T2)
  4588. (error "arguments of eq? must have the same type, but are not"
  4589. (list T1 T2)))
  4590. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4591. ...
  4592. )))
  4593. \end{lstlisting}
  4594. \caption{Type checker for the $R_3$ language.}
  4595. \label{fig:typecheck-R3}
  4596. \end{figure}
  4597. \section{Garbage Collection}
  4598. \label{sec:GC}
  4599. Here we study a relatively simple algorithm for garbage collection
  4600. that is the basis of state-of-the-art garbage
  4601. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4602. particular, we describe a two-space copying
  4603. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4604. perform the
  4605. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4606. coarse-grained depiction of what happens in a two-space collector,
  4607. showing two time steps, prior to garbage collection on the top and
  4608. after garbage collection on the bottom. In a two-space collector, the
  4609. heap is divided into two parts, the FromSpace and the
  4610. ToSpace. Initially, all allocations go to the FromSpace until there is
  4611. not enough room for the next allocation request. At that point, the
  4612. garbage collector goes to work to make more room.
  4613. The garbage collector must be careful not to reclaim tuples that will
  4614. be used by the program in the future. Of course, it is impossible in
  4615. general to predict what a program will do, but we can over approximate
  4616. the will-be-used tuples by preserving all tuples that could be
  4617. accessed by \emph{any} program given the current computer state. A
  4618. program could access any tuple whose address is in a register or on
  4619. the procedure call stack. These addresses are called the \emph{root
  4620. set}. In addition, a program could access any tuple that is
  4621. transitively reachable from the root set. Thus, it is safe for the
  4622. garbage collector to reclaim the tuples that are not reachable in this
  4623. way.
  4624. So the goal of the garbage collector is twofold:
  4625. \begin{enumerate}
  4626. \item preserve all tuple that are reachable from the root set via a
  4627. path of pointers, that is, the \emph{live} tuples, and
  4628. \item reclaim the memory of everything else, that is, the
  4629. \emph{garbage}.
  4630. \end{enumerate}
  4631. A copying collector accomplishes this by copying all of the live
  4632. objects from the FromSpace into the ToSpace and then performs a slight
  4633. of hand, treating the ToSpace as the new FromSpace and the old
  4634. FromSpace as the new ToSpace. In the example of
  4635. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4636. root set, one in a register and two on the stack. All of the live
  4637. objects have been copied to the ToSpace (the right-hand side of
  4638. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4639. pointer relationships. For example, the pointer in the register still
  4640. points to a 2-tuple whose first element is a 3-tuple and second
  4641. element is a 2-tuple. There are four tuples that are not reachable
  4642. from the root set and therefore do not get copied into the ToSpace.
  4643. (The situation in Figure~\ref{fig:copying-collector}, with a
  4644. cycle, cannot be created by a well-typed program in $R_3$. However,
  4645. creating cycles will be possible once we get to $R_6$. We design
  4646. the garbage collector to deal with cycles to begin with, so we will
  4647. not need to revisit this issue.)
  4648. \begin{figure}[tbp]
  4649. \centering
  4650. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4651. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4652. \caption{A copying collector in action.}
  4653. \label{fig:copying-collector}
  4654. \end{figure}
  4655. There are many alternatives to copying collectors (and their older
  4656. siblings, the generational collectors) when its comes to garbage
  4657. collection, such as mark-and-sweep and reference counting. The
  4658. strengths of copying collectors are that allocation is fast (just a
  4659. test and pointer increment), there is no fragmentation, cyclic garbage
  4660. is collected, and the time complexity of collection only depends on
  4661. the amount of live data, and not on the amount of
  4662. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4663. copying collectors is that they use a lot of space, though that
  4664. problem is ameliorated in generational collectors. Racket and Scheme
  4665. programs tend to allocate many small objects and generate a lot of
  4666. garbage, so copying and generational collectors are a good fit. Of
  4667. course, garbage collection is an active research topic, especially
  4668. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4669. continuously developing new techniques and revisiting old
  4670. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4671. \subsection{Graph Copying via Cheney's Algorithm}
  4672. \label{sec:cheney}
  4673. Let us take a closer look at how the copy works. The allocated objects
  4674. and pointers can be viewed as a graph and we need to copy the part of
  4675. the graph that is reachable from the root set. To make sure we copy
  4676. all of the reachable vertices in the graph, we need an exhaustive
  4677. graph traversal algorithm, such as depth-first search or breadth-first
  4678. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4679. take into account the possibility of cycles by marking which vertices
  4680. have already been visited, so as to ensure termination of the
  4681. algorithm. These search algorithms also use a data structure such as a
  4682. stack or queue as a to-do list to keep track of the vertices that need
  4683. to be visited. We shall use breadth-first search and a trick due to
  4684. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4685. copying tuples into the ToSpace.
  4686. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4687. copy progresses. The queue is represented by a chunk of contiguous
  4688. memory at the beginning of the ToSpace, using two pointers to track
  4689. the front and the back of the queue. The algorithm starts by copying
  4690. all tuples that are immediately reachable from the root set into the
  4691. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4692. old tuple to indicate that it has been visited. (We discuss the
  4693. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4694. inside the copied tuples in the queue still point back to the
  4695. FromSpace. Once the initial queue has been created, the algorithm
  4696. enters a loop in which it repeatedly processes the tuple at the front
  4697. of the queue and pops it off the queue. To process a tuple, the
  4698. algorithm copies all the tuple that are directly reachable from it to
  4699. the ToSpace, placing them at the back of the queue. The algorithm then
  4700. updates the pointers in the popped tuple so they point to the newly
  4701. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4702. step we copy the tuple whose second element is $42$ to the back of the
  4703. queue. The other pointer goes to a tuple that has already been copied,
  4704. so we do not need to copy it again, but we do need to update the
  4705. pointer to the new location. This can be accomplished by storing a
  4706. \emph{forwarding} pointer to the new location in the old tuple, back
  4707. when we initially copied the tuple into the ToSpace. This completes
  4708. one step of the algorithm. The algorithm continues in this way until
  4709. the front of the queue is empty, that is, until the front catches up
  4710. with the back.
  4711. \begin{figure}[tbp]
  4712. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4713. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4714. \label{fig:cheney}
  4715. \end{figure}
  4716. \subsection{Data Representation}
  4717. \label{sec:data-rep-gc}
  4718. The garbage collector places some requirements on the data
  4719. representations used by our compiler. First, the garbage collector
  4720. needs to distinguish between pointers and other kinds of data. There
  4721. are several ways to accomplish this.
  4722. \begin{enumerate}
  4723. \item Attached a tag to each object that identifies what type of
  4724. object it is~\citep{McCarthy:1960dz}.
  4725. \item Store different types of objects in different
  4726. regions~\citep{Steele:1977ab}.
  4727. \item Use type information from the program to either generate
  4728. type-specific code for collecting or to generate tables that can
  4729. guide the
  4730. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4731. \end{enumerate}
  4732. Dynamically typed languages, such as Lisp, need to tag objects
  4733. anyways, so option 1 is a natural choice for those languages.
  4734. However, $R_3$ is a statically typed language, so it would be
  4735. unfortunate to require tags on every object, especially small and
  4736. pervasive objects like integers and Booleans. Option 3 is the
  4737. best-performing choice for statically typed languages, but comes with
  4738. a relatively high implementation complexity. To keep this chapter to a
  4739. 2-week time budget, we recommend a combination of options 1 and 2,
  4740. with separate strategies used for the stack and the heap.
  4741. Regarding the stack, we recommend using a separate stack for
  4742. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4743. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4744. local variable needs to be spilled and is of type \code{(Vector
  4745. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4746. of the normal procedure call stack. Furthermore, we always spill
  4747. vector-typed variables if they are live during a call to the
  4748. collector, thereby ensuring that no pointers are in registers during a
  4749. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4750. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4751. layout using a root stack. The root stack contains the two pointers
  4752. from the regular stack and also the pointer in the second
  4753. register.
  4754. \begin{figure}[tbp]
  4755. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4756. \caption{Maintaining a root stack to facilitate garbage collection.}
  4757. \label{fig:shadow-stack}
  4758. \end{figure}
  4759. The problem of distinguishing between pointers and other kinds of data
  4760. also arises inside of each tuple. We solve this problem by attaching a
  4761. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4762. in on the tags for two of the tuples in the example from
  4763. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4764. in a big-endian way, from right-to-left, with bit location 0 (the
  4765. least significant bit) on the far right, which corresponds to the
  4766. directional of the x86 shifting instructions \key{salq} (shift
  4767. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4768. specifying which elements of the tuple are pointers, the part labeled
  4769. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4770. a pointer and a 0 bit indicates some other kind of data. The pointer
  4771. mask starts at bit location 7. We have limited tuples to a maximum
  4772. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4773. tag also contains two other pieces of information. The length of the
  4774. tuple (number of elements) is stored in bits location 1 through
  4775. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4776. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4777. has not yet been copied. If the bit has value 0 then the entire tag
  4778. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4779. always zero anyways because our tuples are 8-byte aligned.)
  4780. \begin{figure}[tbp]
  4781. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4782. \caption{Representation for tuples in the heap.}
  4783. \label{fig:tuple-rep}
  4784. \end{figure}
  4785. \subsection{Implementation of the Garbage Collector}
  4786. \label{sec:organize-gz}
  4787. The implementation of the garbage collector needs to do a lot of
  4788. bit-level data manipulation and we need to link it with our
  4789. compiler-generated x86 code. Thus, we recommend implementing the
  4790. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4791. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4792. interface to the garbage collector. The \code{initialize} function
  4793. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4794. function is meant to be called near the beginning of \code{main},
  4795. before the rest of the program executes. The \code{initialize}
  4796. function puts the address of the beginning of the FromSpace into the
  4797. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4798. points to the address that is 1-past the last element of the
  4799. FromSpace. (We use half-open intervals to represent chunks of
  4800. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4801. points to the first element of the root stack.
  4802. As long as there is room left in the FromSpace, your generated code
  4803. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4804. %
  4805. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4806. --Jeremy}
  4807. %
  4808. The amount of room left in FromSpace is the difference between the
  4809. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4810. function should be called when there is not enough room left in the
  4811. FromSpace for the next allocation. The \code{collect} function takes
  4812. a pointer to the current top of the root stack (one past the last item
  4813. that was pushed) and the number of bytes that need to be
  4814. allocated. The \code{collect} function performs the copying collection
  4815. and leaves the heap in a state such that the next allocation will
  4816. succeed.
  4817. \begin{figure}[tbp]
  4818. \begin{lstlisting}
  4819. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4820. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4821. int64_t* free_ptr;
  4822. int64_t* fromspace_begin;
  4823. int64_t* fromspace_end;
  4824. int64_t** rootstack_begin;
  4825. \end{lstlisting}
  4826. \caption{The compiler's interface to the garbage collector.}
  4827. \label{fig:gc-header}
  4828. \end{figure}
  4829. \begin{exercise}
  4830. In the file \code{runtime.c} you will find the implementation of
  4831. \code{initialize} and a partial implementation of \code{collect}.
  4832. The \code{collect} function calls another function, \code{cheney},
  4833. to perform the actual copy, and that function is left to the reader
  4834. to implement. The following is the prototype for \code{cheney}.
  4835. \begin{lstlisting}
  4836. static void cheney(int64_t** rootstack_ptr);
  4837. \end{lstlisting}
  4838. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4839. rootstack (which is an array of pointers). The \code{cheney} function
  4840. also communicates with \code{collect} through the global
  4841. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4842. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4843. the ToSpace:
  4844. \begin{lstlisting}
  4845. static int64_t* tospace_begin;
  4846. static int64_t* tospace_end;
  4847. \end{lstlisting}
  4848. The job of the \code{cheney} function is to copy all the live
  4849. objects (reachable from the root stack) into the ToSpace, update
  4850. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4851. update the root stack so that it points to the objects in the
  4852. ToSpace, and finally to swap the global pointers for the FromSpace
  4853. and ToSpace.
  4854. \end{exercise}
  4855. %% \section{Compiler Passes}
  4856. %% \label{sec:code-generation-gc}
  4857. The introduction of garbage collection has a non-trivial impact on our
  4858. compiler passes. We introduce one new compiler pass called
  4859. \code{expose-allocation} and make non-trivial changes to
  4860. \code{type-check}, \code{flatten}, \code{select-instructions},
  4861. \code{allocate-registers}, and \code{print-x86}. The following
  4862. program will serve as our running example. It creates two tuples, one
  4863. nested inside the other. Both tuples have length one. The example then
  4864. accesses the element in the inner tuple tuple via two vector
  4865. references.
  4866. % tests/s2_17.rkt
  4867. \begin{lstlisting}
  4868. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4869. \end{lstlisting}
  4870. Next we proceed to discuss the new \code{expose-allocation} pass.
  4871. \section{Expose Allocation}
  4872. \label{sec:expose-allocation}
  4873. The pass \code{expose-allocation} lowers the \code{vector} creation
  4874. form into a conditional call to the collector followed by the
  4875. allocation. We choose to place the \code{expose-allocation} pass
  4876. before \code{flatten} because \code{expose-allocation} introduces new
  4877. variables, which can be done locally with \code{let}, but \code{let}
  4878. is gone after \code{flatten}. In the following, we show the
  4879. transformation for the \code{vector} form into let-bindings for the
  4880. initializing expressions, by a conditional \code{collect}, an
  4881. \code{allocate}, and the initialization of the vector.
  4882. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4883. total bytes need to be allocated for the vector, which is 8 for the
  4884. tag plus \itm{len} times 8.)
  4885. \begin{lstlisting}
  4886. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4887. |$\Longrightarrow$|
  4888. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4889. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4890. (global-value fromspace_end))
  4891. (void)
  4892. (collect |\itm{bytes}|))])
  4893. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4894. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4895. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4896. |$v$|) ... )))) ...)
  4897. \end{lstlisting}
  4898. (In the above, we suppressed all of the \code{has-type} forms in the
  4899. output for the sake of readability.) The placement of the initializing
  4900. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4901. the sequence of \code{vector-set!}'s is important, as those expressions
  4902. may trigger garbage collection and we do not want an allocated but
  4903. uninitialized tuple to be present during a garbage collection.
  4904. The output of \code{expose-allocation} is a language that extends
  4905. $R_3$ with the three new forms that we use above in the translation of
  4906. \code{vector}.
  4907. \[
  4908. \begin{array}{lcl}
  4909. \Exp &::=& \cdots
  4910. \mid (\key{collect} \,\itm{int})
  4911. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4912. \mid (\key{global-value} \,\itm{name})
  4913. \end{array}
  4914. \]
  4915. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4916. %% the beginning of the program which will instruct the garbage collector
  4917. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4918. %% two arguments of \code{initialize} specify the initial allocated space
  4919. %% for the root stack and for the heap.
  4920. %
  4921. %% The \code{expose-allocation} pass annotates all of the local variables
  4922. %% in the \code{program} form with their type.
  4923. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4924. \code{expose-allocation} pass on our running example.
  4925. \begin{figure}[tbp]
  4926. % tests/s2_17.rkt
  4927. \begin{lstlisting}
  4928. (vector-ref
  4929. (vector-ref
  4930. (let ([vecinit7976
  4931. (let ([vecinit7972 42])
  4932. (let ([collectret7974
  4933. (if (< (+ free_ptr 16) fromspace_end)
  4934. (void)
  4935. (collect 16);
  4936. )])
  4937. (let ([alloc7971 (allocate 1 (Vector Integer))])
  4938. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  4939. alloc7971)
  4940. )
  4941. )
  4942. )
  4943. ])
  4944. (let ([collectret7978
  4945. (if (< (+ free_ptr 16) fromspace_end)
  4946. (void)
  4947. (collect 16);
  4948. )])
  4949. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  4950. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  4951. alloc7975)
  4952. )
  4953. )
  4954. )
  4955. 0)
  4956. 0)
  4957. \end{lstlisting}
  4958. \caption{Output of the \code{expose-allocation} pass, minus
  4959. all of the \code{HasType} forms.}
  4960. \label{fig:expose-alloc-output}
  4961. \end{figure}
  4962. %\clearpage
  4963. \section{Explicate Control and the $C_2$ language}
  4964. \label{sec:explicate-control-r3}
  4965. \begin{figure}[tp]
  4966. \fbox{
  4967. \begin{minipage}{0.96\textwidth}
  4968. \small
  4969. \[
  4970. \begin{array}{lcl}
  4971. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  4972. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4973. \Exp &::= & \gray{ \Atm \mid \READ{} \mid \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  4974. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  4975. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type})
  4976. \mid \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  4977. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  4978. &\mid& (\key{GlobalValue} \,\itm{name}) \mid (\key{Void}) \\
  4979. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} \mid \RETURN{\Exp} }
  4980. \mid (\key{Collect} \,\itm{int}) \\
  4981. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }\\
  4982. &\mid& \gray{ \GOTO{\itm{label}} }\\
  4983. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  4984. C_2 & ::= & \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)^{+}}}
  4985. \end{array}
  4986. \]
  4987. \end{minipage}
  4988. }
  4989. \caption{The abstract syntax of the $C_2$ language.
  4990. TODO: UPDATE}
  4991. \label{fig:c2-syntax}
  4992. \end{figure}
  4993. The output of \code{explicate-control} is a program in the
  4994. intermediate language $C_2$, whose syntax is defined in
  4995. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4996. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4997. \key{global-value} expressions and the \code{collect} statement. The
  4998. \code{explicate-control} pass can treat these new forms much like the
  4999. other forms.
  5000. \section{Uncover Locals}
  5001. \label{sec:uncover-locals-r3}
  5002. Recall that the \code{explicate-control} function collects all of the
  5003. local variables so that it can store them in the $\itm{info}$ field of
  5004. the \code{Program} structure. Also recall that we need to know the
  5005. types of all the local variables for purposes of identifying the root
  5006. set for the garbage collector. Thus, we create a pass named
  5007. \code{uncover-locals} to collect not just the variables but the
  5008. variables and their types in the form of an alist. Thanks
  5009. to the \code{HasType} nodes, the types are readily available in the
  5010. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  5011. \code{uncover-locals} pass on the running example.
  5012. \begin{figure}[tbp]
  5013. % tests/s2_17.rkt
  5014. \begin{lstlisting}
  5015. program:
  5016. locals:
  5017. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5018. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5019. collectret7974 : 'Void, initret7977 : 'Void,
  5020. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5021. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5022. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  5023. initret7973 : 'Void,
  5024. block7991:
  5025. (collect 16);
  5026. goto block7989;
  5027. block7990:
  5028. collectret7974 = (void);
  5029. goto block7989;
  5030. block7989:
  5031. alloc7971 = (allocate 1 (Vector Integer));
  5032. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5033. vecinit7976 = alloc7971;
  5034. tmp7982 = free_ptr;
  5035. tmp7983 = (+ tmp7982 16);
  5036. tmp7984 = fromspace_end;
  5037. if (< tmp7983 tmp7984) then
  5038. goto block7987;
  5039. else
  5040. goto block7988;
  5041. block7988:
  5042. (collect 16);
  5043. goto block7986;
  5044. block7987:
  5045. collectret7978 = (void);
  5046. goto block7986;
  5047. block7986:
  5048. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5049. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5050. tmp7985 = (vector-ref alloc7975 0);
  5051. return (vector-ref tmp7985 0);
  5052. start:
  5053. vecinit7972 = 42;
  5054. tmp7979 = free_ptr;
  5055. tmp7980 = (+ tmp7979 16);
  5056. tmp7981 = fromspace_end;
  5057. if (< tmp7980 tmp7981) then
  5058. goto block7990;
  5059. else
  5060. goto block7991;
  5061. \end{lstlisting}
  5062. \caption{Output of \code{uncover-locals} for the running example.}
  5063. \label{fig:uncover-locals-r3}
  5064. \end{figure}
  5065. \clearpage
  5066. \section{Select Instructions}
  5067. \label{sec:select-instructions-gc}
  5068. %% void (rep as zero)
  5069. %% allocate
  5070. %% collect (callq collect)
  5071. %% vector-ref
  5072. %% vector-set!
  5073. %% global-value (postpone)
  5074. In this pass we generate x86 code for most of the new operations that
  5075. were needed to compile tuples, including \code{allocate},
  5076. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  5077. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  5078. The \code{vector-ref} and \code{vector-set!} forms translate into
  5079. \code{movq} instructions with the appropriate \key{deref}. (The
  5080. plus one is to get past the tag at the beginning of the tuple
  5081. representation.)
  5082. \begin{lstlisting}
  5083. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  5084. |$\Longrightarrow$|
  5085. (movq |$\itm{vec}'$| (reg r11))
  5086. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  5087. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  5088. |$\Longrightarrow$|
  5089. (movq |$\itm{vec}'$| (reg r11))
  5090. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  5091. (movq (int 0) |$\itm{lhs}$|)
  5092. \end{lstlisting}
  5093. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  5094. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  5095. register \code{r11} ensures that offsets are only performed with
  5096. register operands. This requires removing \code{r11} from
  5097. consideration by the register allocating.
  5098. We compile the \code{allocate} form to operations on the
  5099. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5100. is the next free address in the FromSpace, so we move it into the
  5101. \itm{lhs} and then move it forward by enough space for the tuple being
  5102. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5103. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5104. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5105. how the tag is organized. We recommend using the Racket operations
  5106. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  5107. The type annotation in the \code{vector} form is used to determine the
  5108. pointer mask region of the tag.
  5109. \begin{lstlisting}
  5110. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5111. |$\Longrightarrow$|
  5112. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5113. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5114. (movq |$\itm{lhs}'$| (reg r11))
  5115. (movq (int |$\itm{tag}$|) (deref r11 0))
  5116. \end{lstlisting}
  5117. The \code{collect} form is compiled to a call to the \code{collect}
  5118. function in the runtime. The arguments to \code{collect} are the top
  5119. of the root stack and the number of bytes that need to be allocated.
  5120. We shall use a dedicated register, \code{r15}, to store the pointer to
  5121. the top of the root stack. So \code{r15} is not available for use by
  5122. the register allocator.
  5123. \begin{lstlisting}
  5124. (collect |$\itm{bytes}$|)
  5125. |$\Longrightarrow$|
  5126. (movq (reg r15) (reg rdi))
  5127. (movq |\itm{bytes}| (reg rsi))
  5128. (callq collect)
  5129. \end{lstlisting}
  5130. \begin{figure}[tp]
  5131. \fbox{
  5132. \begin{minipage}{0.96\textwidth}
  5133. \[
  5134. \begin{array}{lcl}
  5135. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5136. \mid (\key{deref}\,\Reg\,\Int) } \\
  5137. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5138. \mid (\key{global-value}\; \itm{name}) \\
  5139. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5140. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5141. (\key{subq} \; \Arg\; \Arg) \mid
  5142. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5143. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5144. (\key{pushq}\;\Arg) \mid
  5145. (\key{popq}\;\Arg) \mid
  5146. (\key{retq})} \\
  5147. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5148. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5149. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5150. \mid (\key{jmp} \; \itm{label})
  5151. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5152. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5153. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5154. \end{array}
  5155. \]
  5156. \end{minipage}
  5157. }
  5158. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5159. \label{fig:x86-2}
  5160. \end{figure}
  5161. The syntax of the $x86_2$ language is defined in
  5162. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5163. of the form for global variables.
  5164. %
  5165. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5166. \code{select-instructions} pass on the running example.
  5167. \begin{figure}[tbp]
  5168. \centering
  5169. \begin{minipage}{0.75\textwidth}
  5170. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5171. (program
  5172. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5173. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5174. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5175. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5176. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5177. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5178. ((block63 . (block ()
  5179. (movq (reg r15) (reg rdi))
  5180. (movq (int 16) (reg rsi))
  5181. (callq collect)
  5182. (jmp block61)))
  5183. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5184. (block61 . (block ()
  5185. (movq (global-value free_ptr) (var alloc43))
  5186. (addq (int 16) (global-value free_ptr))
  5187. (movq (var alloc43) (reg r11))
  5188. (movq (int 3) (deref r11 0))
  5189. (movq (var alloc43) (reg r11))
  5190. (movq (var vecinit44) (deref r11 8))
  5191. (movq (int 0) (var initret45))
  5192. (movq (var alloc43) (var vecinit48))
  5193. (movq (global-value free_ptr) (var tmp54))
  5194. (movq (var tmp54) (var tmp55))
  5195. (addq (int 16) (var tmp55))
  5196. (movq (global-value fromspace_end) (var tmp56))
  5197. (cmpq (var tmp56) (var tmp55))
  5198. (jmp-if l block59)
  5199. (jmp block60)))
  5200. (block60 . (block ()
  5201. (movq (reg r15) (reg rdi))
  5202. (movq (int 16) (reg rsi))
  5203. (callq collect)
  5204. (jmp block58))
  5205. (block59 . (block ()
  5206. (movq (int 0) (var collectret50))
  5207. (jmp block58)))
  5208. (block58 . (block ()
  5209. (movq (global-value free_ptr) (var alloc47))
  5210. (addq (int 16) (global-value free_ptr))
  5211. (movq (var alloc47) (reg r11))
  5212. (movq (int 131) (deref r11 0))
  5213. (movq (var alloc47) (reg r11))
  5214. (movq (var vecinit48) (deref r11 8))
  5215. (movq (int 0) (var initret49))
  5216. (movq (var alloc47) (reg r11))
  5217. (movq (deref r11 8) (var tmp57))
  5218. (movq (var tmp57) (reg r11))
  5219. (movq (deref r11 8) (reg rax))
  5220. (jmp conclusion)))
  5221. (start . (block ()
  5222. (movq (int 42) (var vecinit44))
  5223. (movq (global-value free_ptr) (var tmp51))
  5224. (movq (var tmp51) (var tmp52))
  5225. (addq (int 16) (var tmp52))
  5226. (movq (global-value fromspace_end) (var tmp53))
  5227. (cmpq (var tmp53) (var tmp52))
  5228. (jmp-if l block62)
  5229. (jmp block63))))))
  5230. \end{lstlisting}
  5231. \end{minipage}
  5232. \caption{Output of the \code{select-instructions} pass.}
  5233. \label{fig:select-instr-output-gc}
  5234. \end{figure}
  5235. \clearpage
  5236. \section{Register Allocation}
  5237. \label{sec:reg-alloc-gc}
  5238. As discussed earlier in this chapter, the garbage collector needs to
  5239. access all the pointers in the root set, that is, all variables that
  5240. are vectors. It will be the responsibility of the register allocator
  5241. to make sure that:
  5242. \begin{enumerate}
  5243. \item the root stack is used for spilling vector-typed variables, and
  5244. \item if a vector-typed variable is live during a call to the
  5245. collector, it must be spilled to ensure it is visible to the
  5246. collector.
  5247. \end{enumerate}
  5248. The later responsibility can be handled during construction of the
  5249. inference graph, by adding interference edges between the call-live
  5250. vector-typed variables and all the callee-saved registers. (They
  5251. already interfere with the caller-saved registers.) The type
  5252. information for variables is in the \code{program} form, so we
  5253. recommend adding another parameter to the \code{build-interference}
  5254. function to communicate this alist.
  5255. The spilling of vector-typed variables to the root stack can be
  5256. handled after graph coloring, when choosing how to assign the colors
  5257. (integers) to registers and stack locations. The \code{program} output
  5258. of this pass changes to also record the number of spills to the root
  5259. stack.
  5260. % build-interference
  5261. %
  5262. % callq
  5263. % extra parameter for var->type assoc. list
  5264. % update 'program' and 'if'
  5265. % allocate-registers
  5266. % allocate spilled vectors to the rootstack
  5267. % don't change color-graph
  5268. \section{Print x86}
  5269. \label{sec:print-x86-gc}
  5270. \margincomment{\scriptsize We need to show the translation to x86 and what
  5271. to do about global-value. \\ --Jeremy}
  5272. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5273. \code{print-x86} pass on the running example. In the prelude and
  5274. conclusion of the \code{main} function, we treat the root stack very
  5275. much like the regular stack in that we move the root stack pointer
  5276. (\code{r15}) to make room for all of the spills to the root stack,
  5277. except that the root stack grows up instead of down. For the running
  5278. example, there was just one spill so we increment \code{r15} by 8
  5279. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5280. One issue that deserves special care is that there may be a call to
  5281. \code{collect} prior to the initializing assignments for all the
  5282. variables in the root stack. We do not want the garbage collector to
  5283. accidentally think that some uninitialized variable is a pointer that
  5284. needs to be followed. Thus, we zero-out all locations on the root
  5285. stack in the prelude of \code{main}. In
  5286. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5287. %
  5288. \lstinline{movq $0, (%r15)}
  5289. %
  5290. accomplishes this task. The garbage collector tests each root to see
  5291. if it is null prior to dereferencing it.
  5292. \begin{figure}[htbp]
  5293. \begin{minipage}[t]{0.5\textwidth}
  5294. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5295. _block58:
  5296. movq _free_ptr(%rip), %rcx
  5297. addq $16, _free_ptr(%rip)
  5298. movq %rcx, %r11
  5299. movq $131, 0(%r11)
  5300. movq %rcx, %r11
  5301. movq -8(%r15), %rax
  5302. movq %rax, 8(%r11)
  5303. movq $0, %rdx
  5304. movq %rcx, %r11
  5305. movq 8(%r11), %rcx
  5306. movq %rcx, %r11
  5307. movq 8(%r11), %rax
  5308. jmp _conclusion
  5309. _block59:
  5310. movq $0, %rcx
  5311. jmp _block58
  5312. _block62:
  5313. movq $0, %rcx
  5314. jmp _block61
  5315. _block60:
  5316. movq %r15, %rdi
  5317. movq $16, %rsi
  5318. callq _collect
  5319. jmp _block58
  5320. _block63:
  5321. movq %r15, %rdi
  5322. movq $16, %rsi
  5323. callq _collect
  5324. jmp _block61
  5325. _start:
  5326. movq $42, %rbx
  5327. movq _free_ptr(%rip), %rdx
  5328. addq $16, %rdx
  5329. movq _fromspace_end(%rip), %rcx
  5330. cmpq %rcx, %rdx
  5331. jl _block62
  5332. jmp _block63
  5333. \end{lstlisting}
  5334. \end{minipage}
  5335. \begin{minipage}[t]{0.45\textwidth}
  5336. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5337. _block61:
  5338. movq _free_ptr(%rip), %rcx
  5339. addq $16, _free_ptr(%rip)
  5340. movq %rcx, %r11
  5341. movq $3, 0(%r11)
  5342. movq %rcx, %r11
  5343. movq %rbx, 8(%r11)
  5344. movq $0, %rdx
  5345. movq %rcx, -8(%r15)
  5346. movq _free_ptr(%rip), %rcx
  5347. addq $16, %rcx
  5348. movq _fromspace_end(%rip), %rdx
  5349. cmpq %rdx, %rcx
  5350. jl _block59
  5351. jmp _block60
  5352. .globl _main
  5353. _main:
  5354. pushq %rbp
  5355. movq %rsp, %rbp
  5356. pushq %r12
  5357. pushq %rbx
  5358. pushq %r13
  5359. pushq %r14
  5360. subq $0, %rsp
  5361. movq $16384, %rdi
  5362. movq $16, %rsi
  5363. callq _initialize
  5364. movq _rootstack_begin(%rip), %r15
  5365. movq $0, (%r15)
  5366. addq $8, %r15
  5367. jmp _start
  5368. _conclusion:
  5369. subq $8, %r15
  5370. addq $0, %rsp
  5371. popq %r14
  5372. popq %r13
  5373. popq %rbx
  5374. popq %r12
  5375. popq %rbp
  5376. retq
  5377. \end{lstlisting}
  5378. \end{minipage}
  5379. \caption{Output of the \code{print-x86} pass.}
  5380. \label{fig:print-x86-output-gc}
  5381. \end{figure}
  5382. \margincomment{\scriptsize Suggest an implementation strategy
  5383. in which the students first do the code gen and test that
  5384. without GC (just use a big heap), then after that is debugged,
  5385. implement the GC. \\ --Jeremy}
  5386. \begin{figure}[p]
  5387. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5388. \node (R3) at (0,2) {\large $R_3$};
  5389. \node (R3-2) at (3,2) {\large $R_3$};
  5390. \node (R3-3) at (6,2) {\large $R_3$};
  5391. \node (R3-4) at (9,2) {\large $R_3$};
  5392. \node (R3-5) at (12,2) {\large $R_3$};
  5393. \node (C2-4) at (3,0) {\large $C_2$};
  5394. \node (C2-3) at (6,0) {\large $C_2$};
  5395. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5396. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5397. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5398. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5399. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5400. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5401. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5402. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5403. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5404. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5405. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5406. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5407. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5408. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5409. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5410. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5411. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5412. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5413. \end{tikzpicture}
  5414. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5415. \label{fig:R3-passes}
  5416. \end{figure}
  5417. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5418. for the compilation of $R_3$.
  5419. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5420. \chapter{Functions}
  5421. \label{ch:functions}
  5422. This chapter studies the compilation of functions at the level of
  5423. abstraction of the C language. This corresponds to a subset of Typed
  5424. Racket in which only top-level function definitions are allowed. These
  5425. kind of functions are an important stepping stone to implementing
  5426. lexically-scoped functions in the form of \key{lambda} abstractions,
  5427. which is the topic of Chapter~\ref{ch:lambdas}.
  5428. \section{The $R_4$ Language}
  5429. The syntax for function definitions and function application is shown
  5430. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5431. Programs in $R_4$ start with zero or more function definitions. The
  5432. function names from these definitions are in-scope for the entire
  5433. program, including all other function definitions (so the ordering of
  5434. function definitions does not matter). The syntax for function
  5435. application does not include an explicit keyword, which is error prone
  5436. when using \code{match}. To alleviate this problem, we change the
  5437. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5438. during type checking.
  5439. Functions are first-class in the sense that a function pointer is data
  5440. and can be stored in memory or passed as a parameter to another
  5441. function. Thus, we introduce a function type, written
  5442. \begin{lstlisting}
  5443. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5444. \end{lstlisting}
  5445. for a function whose $n$ parameters have the types $\Type_1$ through
  5446. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5447. these functions (with respect to Racket functions) is that they are
  5448. not lexically scoped. That is, the only external entities that can be
  5449. referenced from inside a function body are other globally-defined
  5450. functions. The syntax of $R_4$ prevents functions from being nested
  5451. inside each other.
  5452. \begin{figure}[tp]
  5453. \centering
  5454. \fbox{
  5455. \begin{minipage}{0.96\textwidth}
  5456. \[
  5457. \begin{array}{lcl}
  5458. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5459. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5460. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5461. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5462. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5463. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5464. \mid (\key{and}\;\Exp\;\Exp)
  5465. \mid (\key{or}\;\Exp\;\Exp)
  5466. \mid (\key{not}\;\Exp)} \\
  5467. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5468. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5469. (\key{vector-ref}\;\Exp\;\Int)} \\
  5470. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5471. &\mid& (\Exp \; \Exp^{*}) \\
  5472. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5473. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5474. \end{array}
  5475. \]
  5476. \end{minipage}
  5477. }
  5478. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5479. with functions.}
  5480. \label{fig:r4-syntax}
  5481. \end{figure}
  5482. The program in Figure~\ref{fig:r4-function-example} is a
  5483. representative example of defining and using functions in $R_4$. We
  5484. define a function \code{map-vec} that applies some other function
  5485. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5486. vector containing the results. We also define a function \code{add1}
  5487. that does what its name suggests. The program then applies
  5488. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5489. \code{(vector 1 42)}, from which we return the \code{42}.
  5490. \begin{figure}[tbp]
  5491. \begin{lstlisting}
  5492. (program ()
  5493. (define (map-vec [f : (Integer -> Integer)]
  5494. [v : (Vector Integer Integer)])
  5495. : (Vector Integer Integer)
  5496. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5497. (define (add1 [x : Integer]) : Integer
  5498. (+ x 1))
  5499. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5500. )
  5501. \end{lstlisting}
  5502. \caption{Example of using functions in $R_4$.}
  5503. \label{fig:r4-function-example}
  5504. \end{figure}
  5505. The definitional interpreter for $R_4$ is in
  5506. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5507. responsible for setting up the mutual recursion between the top-level
  5508. function definitions. We use the classic back-patching approach that
  5509. uses mutable variables and makes two passes over the function
  5510. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5511. top-level environment using a mutable cons cell for each function
  5512. definition. Note that the \code{lambda} value for each function is
  5513. incomplete; it does not yet include the environment. Once the
  5514. top-level environment is constructed, we then iterate over it and
  5515. update the \code{lambda} value's to use the top-level environment.
  5516. \begin{figure}[tp]
  5517. \begin{lstlisting}
  5518. (define (interp-exp env)
  5519. (lambda (e)
  5520. (define recur (interp-exp env))
  5521. (match e
  5522. ...
  5523. [`(,fun ,args ...)
  5524. (define arg-vals (for/list ([e args]) (recur e)))
  5525. (define fun-val (recur fun))
  5526. (match fun-val
  5527. [`(lambda (,xs ...) ,body ,fun-env)
  5528. (define new-env (append (map cons xs arg-vals) fun-env))
  5529. ((interp-exp new-env) body)]
  5530. [else (error "interp-exp, expected function, not" fun-val)])]
  5531. [else (error 'interp-exp "unrecognized expression")]
  5532. )))
  5533. (define (interp-def d)
  5534. (match d
  5535. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5536. (mcons f `(lambda ,xs ,body ()))]
  5537. ))
  5538. (define (interp-R4 p)
  5539. (match p
  5540. [`(program ,ds ... ,body)
  5541. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5542. (for/list ([b top-level])
  5543. (set-mcdr! b (match (mcdr b)
  5544. [`(lambda ,xs ,body ())
  5545. `(lambda ,xs ,body ,top-level)])))
  5546. ((interp-exp top-level) body))]
  5547. ))
  5548. \end{lstlisting}
  5549. \caption{Interpreter for the $R_4$ language.}
  5550. \label{fig:interp-R4}
  5551. \end{figure}
  5552. \section{Functions in x86}
  5553. \label{sec:fun-x86}
  5554. \margincomment{\tiny Make sure callee-saved registers are discussed
  5555. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5556. \margincomment{\tiny Talk about the return address on the
  5557. stack and what callq and retq does.\\ --Jeremy }
  5558. The x86 architecture provides a few features to support the
  5559. implementation of functions. We have already seen that x86 provides
  5560. labels so that one can refer to the location of an instruction, as is
  5561. needed for jump instructions. Labels can also be used to mark the
  5562. beginning of the instructions for a function. Going further, we can
  5563. obtain the address of a label by using the \key{leaq} instruction and
  5564. \key{rip}-relative addressing. For example, the following puts the
  5565. address of the \code{add1} label into the \code{rbx} register.
  5566. \begin{lstlisting}
  5567. leaq add1(%rip), %rbx
  5568. \end{lstlisting}
  5569. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5570. instruction for jumping to a function whose location is given by a
  5571. label. Here we instead will be jumping to a function whose location is
  5572. given by an address, that is, we need to make an \emph{indirect
  5573. function call}. The x86 syntax is to give the register name prefixed
  5574. with an asterisk.
  5575. \begin{lstlisting}
  5576. callq *%rbx
  5577. \end{lstlisting}
  5578. \subsection{Calling Conventions}
  5579. The \code{callq} instruction provides partial support for implementing
  5580. functions, but it does not handle (1) parameter passing, (2) saving
  5581. and restoring frames on the procedure call stack, or (3) determining
  5582. how registers are shared by different functions. These issues require
  5583. coordination between the caller and the callee, which is often
  5584. assembly code written by different programmers or generated by
  5585. different compilers. As a result, people have developed
  5586. \emph{conventions} that govern how functions calls are performed.
  5587. Here we shall use the same conventions used by the \code{gcc}
  5588. compiler~\citep{Matz:2013aa}.
  5589. Regarding (1) parameter passing, the convention is to use the
  5590. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5591. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5592. than six arguments, then the convention is to use space on the frame
  5593. of the caller for the rest of the arguments. However, to ease the
  5594. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5595. we shall arrange to never have more than six arguments.
  5596. %
  5597. The register \code{rax} is for the return value of the function.
  5598. Regarding (2) frames and the procedure call stack, the convention is
  5599. that the stack grows down, with each function call using a chunk of
  5600. space called a frame. The caller sets the stack pointer, register
  5601. \code{rsp}, to the last data item in its frame. The callee must not
  5602. change anything in the caller's frame, that is, anything that is at or
  5603. above the stack pointer. The callee is free to use locations that are
  5604. below the stack pointer.
  5605. Regarding (3) the sharing of registers between different functions,
  5606. recall from Section~\ref{sec:calling-conventions} that the registers
  5607. are divided into two groups, the caller-saved registers and the
  5608. callee-saved registers. The caller should assume that all the
  5609. caller-saved registers get overwritten with arbitrary values by the
  5610. callee. Thus, the caller should either 1) not put values that are live
  5611. across a call in caller-saved registers, or 2) save and restore values
  5612. that are live across calls. We shall recommend option 1). On the flip
  5613. side, if the callee wants to use a callee-saved register, the callee
  5614. must save the contents of those registers on their stack frame and
  5615. then put them back prior to returning to the caller. The base
  5616. pointer, register \code{rbp}, is used as a point-of-reference within a
  5617. frame, so that each local variable can be accessed at a fixed offset
  5618. from the base pointer.
  5619. %
  5620. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5621. frames.
  5622. %% If we were to use stack arguments, they would be between the
  5623. %% caller locals and the callee return address.
  5624. \begin{figure}[tbp]
  5625. \centering
  5626. \begin{tabular}{r|r|l|l} \hline
  5627. Caller View & Callee View & Contents & Frame \\ \hline
  5628. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5629. 0(\key{\%rbp}) & & old \key{rbp} \\
  5630. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5631. \ldots & & \ldots \\
  5632. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5633. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5634. \ldots & & \ldots \\
  5635. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5636. %% & & \\
  5637. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5638. %% & \ldots & \ldots \\
  5639. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5640. \hline
  5641. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5642. & 0(\key{\%rbp}) & old \key{rbp} \\
  5643. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5644. & \ldots & \ldots \\
  5645. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5646. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5647. & \ldots & \ldots \\
  5648. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5649. \end{tabular}
  5650. \caption{Memory layout of caller and callee frames.}
  5651. \label{fig:call-frames}
  5652. \end{figure}
  5653. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5654. %% local variables and for storing the values of callee-saved registers
  5655. %% (we shall refer to all of these collectively as ``locals''), and that
  5656. %% at the beginning of a function we move the stack pointer \code{rsp}
  5657. %% down to make room for them.
  5658. %% We recommend storing the local variables
  5659. %% first and then the callee-saved registers, so that the local variables
  5660. %% can be accessed using \code{rbp} the same as before the addition of
  5661. %% functions.
  5662. %% To make additional room for passing arguments, we shall
  5663. %% move the stack pointer even further down. We count how many stack
  5664. %% arguments are needed for each function call that occurs inside the
  5665. %% body of the function and find their maximum. Adding this number to the
  5666. %% number of locals gives us how much the \code{rsp} should be moved at
  5667. %% the beginning of the function. In preparation for a function call, we
  5668. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5669. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5670. %% so on.
  5671. %% Upon calling the function, the stack arguments are retrieved by the
  5672. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5673. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5674. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5675. %% the layout of the caller and callee frames. Notice how important it is
  5676. %% that we correctly compute the maximum number of arguments needed for
  5677. %% function calls; if that number is too small then the arguments and
  5678. %% local variables will smash into each other!
  5679. \subsection{Efficient Tail Calls}
  5680. \label{sec:tail-call}
  5681. In general, the amount of stack space used by a program is determined
  5682. by the longest chain of nested function calls. That is, if function
  5683. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5684. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5685. $n$ can grow quite large in the case of recursive or mutually
  5686. recursive functions. However, in some cases we can arrange to use only
  5687. constant space, i.e. $O(1)$, instead of $O(n)$.
  5688. If a function call is the last action in a function body, then that
  5689. call is said to be a \emph{tail call}. In such situations, the frame
  5690. of the caller is no longer needed, so we can pop the caller's frame
  5691. before making the tail call. With this approach, a recursive function
  5692. that only makes tail calls will only use $O(1)$ stack space.
  5693. Functional languages like Racket typically rely heavily on recursive
  5694. functions, so they typically guarantee that all tail calls will be
  5695. optimized in this way.
  5696. However, some care is needed with regards to argument passing in tail
  5697. calls. As mentioned above, for arguments beyond the sixth, the
  5698. convention is to use space in the caller's frame for passing
  5699. arguments. But here we've popped the caller's frame and can no longer
  5700. use it. Another alternative is to use space in the callee's frame for
  5701. passing arguments. However, this option is also problematic because
  5702. the caller and callee's frame overlap in memory. As we begin to copy
  5703. the arguments from their sources in the caller's frame, the target
  5704. locations in the callee's frame might overlap with the sources for
  5705. later arguments! We solve this problem by not using the stack for
  5706. parameter passing but instead use the heap, as we describe in the
  5707. Section~\ref{sec:limit-functions-r4}.
  5708. As mentioned above, for a tail call we pop the caller's frame prior to
  5709. making the tail call. The instructions for popping a frame are the
  5710. instructions that we usually place in the conclusion of a
  5711. function. Thus, we also need to place such code immediately before
  5712. each tail call. These instructions include restoring the callee-saved
  5713. registers, so it is good that the argument passing registers are all
  5714. caller-saved registers.
  5715. One last note regarding which instruction to use to make the tail
  5716. call. When the callee is finished, it should not return to the current
  5717. function, but it should return to the function that called the current
  5718. one. Thus, the return address that is already on the stack is the
  5719. right one, and we should not use \key{callq} to make the tail call, as
  5720. that would unnecessarily overwrite the return address. Instead we can
  5721. simply use the \key{jmp} instruction. Like the indirect function call,
  5722. we write an indirect jump with a register prefixed with an asterisk.
  5723. We recommend using \code{rax} to hold the jump target because the
  5724. preceding ``conclusion'' overwrites just about everything else.
  5725. \begin{lstlisting}
  5726. jmp *%rax
  5727. \end{lstlisting}
  5728. %% Now that we have a good understanding of functions as they appear in
  5729. %% $R_4$ and the support for functions in x86, we need to plan the
  5730. %% changes to our compiler, that is, do we need any new passes and/or do
  5731. %% we need to change any existing passes? Also, do we need to add new
  5732. %% kinds of AST nodes to any of the intermediate languages?
  5733. \section{Shrink $R_4$}
  5734. \label{sec:shrink-r4}
  5735. The \code{shrink} pass performs a couple minor modifications to the
  5736. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5737. field to each function definition:
  5738. \begin{lstlisting}
  5739. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5740. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5741. \end{lstlisting}
  5742. and introduces an explicit \code{main} function.\\
  5743. \begin{tabular}{lll}
  5744. \begin{minipage}{0.45\textwidth}
  5745. \begin{lstlisting}
  5746. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5747. \end{lstlisting}
  5748. \end{minipage}
  5749. &
  5750. $\Rightarrow$
  5751. &
  5752. \begin{minipage}{0.45\textwidth}
  5753. \begin{lstlisting}
  5754. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5755. \end{lstlisting}
  5756. \end{minipage}
  5757. \end{tabular} \\
  5758. where $\itm{mainDef}$ is
  5759. \begin{lstlisting}
  5760. (define (main) : Integer () |$\Exp'$|)
  5761. \end{lstlisting}
  5762. \section{Reveal Functions}
  5763. \label{sec:reveal-functions-r4}
  5764. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5765. compilation because it conflates the use of function names and local
  5766. variables. This is a problem because we need to compile the use of a
  5767. function name differently than the use of a local variable; we need to
  5768. use \code{leaq} to convert the function name (a label in x86) to an
  5769. address in a register. Thus, it is a good idea to create a new pass
  5770. that changes function references from just a symbol $f$ to
  5771. \code{(fun-ref $f$)}. A good name for this pass is
  5772. \code{reveal-functions} and the output language, $F_1$, is defined in
  5773. Figure~\ref{fig:f1-syntax}.
  5774. \begin{figure}[tp]
  5775. \centering
  5776. \fbox{
  5777. \begin{minipage}{0.96\textwidth}
  5778. \[
  5779. \begin{array}{lcl}
  5780. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5781. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5782. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5783. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5784. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5785. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5786. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5787. (\key{vector-ref}\;\Exp\;\Int)} \\
  5788. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5789. (\key{app}\; \Exp \; \Exp^{*})} \\
  5790. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5791. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5792. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5793. \end{array}
  5794. \]
  5795. \end{minipage}
  5796. }
  5797. \caption{The $F_1$ language, an extension of $R_4$
  5798. (Figure~\ref{fig:r4-syntax}).}
  5799. \label{fig:f1-syntax}
  5800. \end{figure}
  5801. %% Distinguishing between calls in tail position and non-tail position
  5802. %% requires the pass to have some notion of context. We recommend using
  5803. %% two mutually recursive functions, one for processing expressions in
  5804. %% tail position and another for the rest.
  5805. Placing this pass after \code{uniquify} is a good idea, because it
  5806. will make sure that there are no local variables and functions that
  5807. share the same name. On the other hand, \code{reveal-functions} needs
  5808. to come before the \code{explicate-control} pass because that pass
  5809. will help us compile \code{fun-ref} into assignment statements.
  5810. \section{Limit Functions}
  5811. \label{sec:limit-functions-r4}
  5812. This pass transforms functions so that they have at most six
  5813. parameters and transforms all function calls so that they pass at most
  5814. six arguments. A simple strategy for imposing an argument limit of
  5815. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5816. into a vector, making that subsequent vector the $n$th argument.
  5817. \begin{tabular}{lll}
  5818. \begin{minipage}{0.2\textwidth}
  5819. \begin{lstlisting}
  5820. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5821. \end{lstlisting}
  5822. \end{minipage}
  5823. &
  5824. $\Rightarrow$
  5825. &
  5826. \begin{minipage}{0.4\textwidth}
  5827. \begin{lstlisting}
  5828. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5829. \end{lstlisting}
  5830. \end{minipage}
  5831. \end{tabular}
  5832. In the body of the function, all occurrences of the $i$th argument in
  5833. which $i>5$ must be replaced with a \code{vector-ref}.
  5834. \section{Remove Complex Operators and Operands}
  5835. \label{sec:rco-r4}
  5836. The primary decisions to make for this pass is whether to classify
  5837. \code{fun-ref} and \code{app} as either simple or complex
  5838. expressions. Recall that a simple expression will eventually end up as
  5839. just an ``immediate'' argument of an x86 instruction. Function
  5840. application will be translated to a sequence of instructions, so
  5841. \code{app} must be classified as complex expression. Regarding
  5842. \code{fun-ref}, as discussed above, the function label needs to
  5843. be converted to an address using the \code{leaq} instruction. Thus,
  5844. even though \code{fun-ref} seems rather simple, it needs to be
  5845. classified as a complex expression so that we generate an assignment
  5846. statement with a left-hand side that can serve as the target of the
  5847. \code{leaq}.
  5848. \section{Explicate Control and the $C_3$ language}
  5849. \label{sec:explicate-control-r4}
  5850. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5851. \key{explicate-control}. The three mutually recursive functions for
  5852. this pass, for assignment, tail, and predicate contexts, must all be
  5853. updated with cases for \code{fun-ref} and \code{app}. In
  5854. assignment and predicate contexts, \code{app} becomes \code{call},
  5855. whereas in tail position \code{app} becomes \code{tailcall}. We
  5856. recommend defining a new function for processing function definitions.
  5857. This code is similar to the case for \code{program} in $R_3$. The
  5858. top-level \code{explicate-control} function that handles the
  5859. \code{program} form of $R_4$ can then apply this new function to all
  5860. the function definitions.
  5861. \begin{figure}[tp]
  5862. \fbox{
  5863. \begin{minipage}{0.96\textwidth}
  5864. \[
  5865. \begin{array}{lcl}
  5866. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5867. \\
  5868. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5869. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5870. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5871. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5872. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5873. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5874. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5875. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5876. \mid (\key{collect} \,\itm{int}) }\\
  5877. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5878. &\mid& \gray{(\key{goto}\,\itm{label})
  5879. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5880. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5881. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5882. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5883. \end{array}
  5884. \]
  5885. \end{minipage}
  5886. }
  5887. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5888. \label{fig:c3-syntax}
  5889. \end{figure}
  5890. \section{Uncover Locals}
  5891. \label{sec:uncover-locals-r4}
  5892. The function for processing $\Tail$ should be updated with a case for
  5893. \code{tailcall}. We also recommend creating a new function for
  5894. processing function definitions. Each function definition in $C_3$ has
  5895. its own set of local variables, so the code for function definitions
  5896. should be similar to the case for the \code{program} form in $C_2$.
  5897. \section{Select Instructions}
  5898. \label{sec:select-r4}
  5899. The output of select instructions is a program in the x86$_3$
  5900. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5901. \begin{figure}[tp]
  5902. \fbox{
  5903. \begin{minipage}{0.96\textwidth}
  5904. \[
  5905. \begin{array}{lcl}
  5906. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5907. \mid (\key{deref}\,\Reg\,\Int) } \\
  5908. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5909. \mid (\key{global-value}\; \itm{name}) } \\
  5910. &\mid& (\key{fun-ref}\; \itm{label})\\
  5911. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5912. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5913. (\key{subq} \; \Arg\; \Arg) \mid
  5914. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5915. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5916. (\key{pushq}\;\Arg) \mid
  5917. (\key{popq}\;\Arg) \mid
  5918. (\key{retq}) } \\
  5919. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5920. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5921. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5922. \mid (\key{jmp} \; \itm{label})
  5923. \mid (\key{j}\itm{cc} \; \itm{label})
  5924. \mid (\key{label} \; \itm{label}) } \\
  5925. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5926. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5927. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5928. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5929. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5930. \end{array}
  5931. \]
  5932. \end{minipage}
  5933. }
  5934. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5935. \label{fig:x86-3}
  5936. \end{figure}
  5937. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5938. as follows: \\
  5939. \begin{tabular}{lll}
  5940. \begin{minipage}{0.45\textwidth}
  5941. \begin{lstlisting}
  5942. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5943. \end{lstlisting}
  5944. \end{minipage}
  5945. &
  5946. $\Rightarrow$
  5947. &
  5948. \begin{minipage}{0.4\textwidth}
  5949. \begin{lstlisting}
  5950. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5951. \end{lstlisting}
  5952. \end{minipage}
  5953. \end{tabular} \\
  5954. Regarding function definitions, we need to remove their parameters and
  5955. instead perform parameter passing in terms of the conventions
  5956. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5957. in the argument passing registers, and inside the function we should
  5958. generate a \code{movq} instruction for each parameter, to move the
  5959. argument value from the appropriate register to a new local variable
  5960. with the same name as the old parameter.
  5961. Next, consider the compilation of function calls, which have the
  5962. following form upon input to \code{select-instructions}.
  5963. \begin{lstlisting}
  5964. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5965. \end{lstlisting}
  5966. In the mirror image of handling the parameters of function
  5967. definitions, the arguments \itm{args} need to be moved to the argument
  5968. passing registers.
  5969. %
  5970. Once the instructions for parameter passing have been generated, the
  5971. function call itself can be performed with an indirect function call,
  5972. for which I recommend creating the new instruction
  5973. \code{indirect-callq}. Of course, the return value from the function
  5974. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5975. \begin{lstlisting}
  5976. (indirect-callq |\itm{fun}|)
  5977. (movq (reg rax) |\itm{lhs}|)
  5978. \end{lstlisting}
  5979. Regarding tail calls, the parameter passing is the same as non-tail
  5980. calls: generate instructions to move the arguments into to the
  5981. argument passing registers. After that we need to pop the frame from
  5982. the procedure call stack. However, we do not yet know how big the
  5983. frame is; that gets determined during register allocation. So instead
  5984. of generating those instructions here, we invent a new instruction
  5985. that means ``pop the frame and then do an indirect jump'', which we
  5986. name \code{tail-jmp}.
  5987. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5988. using the label \code{start} for the initial block of a program, and
  5989. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5990. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5991. can be compiled to an assignment to \code{rax} followed by a jump to
  5992. \code{conclusion}. With the addition of function definitions, we will
  5993. have a starting block and conclusion for each function, but their
  5994. labels need to be unique. We recommend prepending the function's name
  5995. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5996. labels. (Alternatively, one could \code{gensym} labels for the start
  5997. and conclusion and store them in the $\itm{info}$ field of the
  5998. function definition.)
  5999. \section{Uncover Live}
  6000. %% The rest of the passes need only minor modifications to handle the new
  6001. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6002. %% \code{leaq}.
  6003. Inside \code{uncover-live}, when computing the $W$ set (written
  6004. variables) for an \code{indirect-callq} instruction, we recommend
  6005. including all the caller-saved registers, which will have the affect
  6006. of making sure that no caller-saved register actually needs to be
  6007. saved.
  6008. \section{Build Interference Graph}
  6009. With the addition of function definitions, we compute an interference
  6010. graph for each function (not just one for the whole program).
  6011. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6012. spill vector-typed variables that are live during a call to the
  6013. \code{collect}. With the addition of functions to our language, we
  6014. need to revisit this issue. Many functions will perform allocation and
  6015. therefore have calls to the collector inside of them. Thus, we should
  6016. not only spill a vector-typed variable when it is live during a call
  6017. to \code{collect}, but we should spill the variable if it is live
  6018. during any function call. Thus, in the \code{build-interference} pass,
  6019. we recommend adding interference edges between call-live vector-typed
  6020. variables and the callee-saved registers (in addition to the usual
  6021. addition of edges between call-live variables and the caller-saved
  6022. registers).
  6023. \section{Patch Instructions}
  6024. In \code{patch-instructions}, you should deal with the x86
  6025. idiosyncrasy that the destination argument of \code{leaq} must be a
  6026. register. Additionally, you should ensure that the argument of
  6027. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6028. code generation more convenient, because we will be trampling many
  6029. registers before the tail call (as explained below).
  6030. \section{Print x86}
  6031. For the \code{print-x86} pass, we recommend the following translations:
  6032. \begin{lstlisting}
  6033. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6034. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6035. \end{lstlisting}
  6036. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6037. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6038. is what we will want to do, but before the jump we need to pop the
  6039. current frame. So we need to restore the state of the registers to the
  6040. point they were at when the current function was called. This
  6041. sequence of instructions is the same as the code for the conclusion of
  6042. a function.
  6043. Note that your \code{print-x86} pass needs to add the code for saving
  6044. and restoring callee-saved registers, if you have not already
  6045. implemented that. This is necessary when generating code for function
  6046. definitions.
  6047. \section{An Example Translation}
  6048. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6049. function in $R_4$ to x86. The figure also includes the results of the
  6050. \code{explicate-control} and \code{select-instructions} passes. We
  6051. have omitted the \code{has-type} AST nodes for readability. Can you
  6052. see any ways to improve the translation?
  6053. \begin{figure}[tbp]
  6054. \begin{tabular}{ll}
  6055. \begin{minipage}{0.45\textwidth}
  6056. % s3_2.rkt
  6057. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6058. (program
  6059. (define (add [x : Integer]
  6060. [y : Integer])
  6061. : Integer (+ x y))
  6062. (add 40 2))
  6063. \end{lstlisting}
  6064. $\Downarrow$
  6065. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6066. (program ()
  6067. (define (add86 [x87 : Integer]
  6068. [y88 : Integer]) : Integer ()
  6069. ((add86start . (return (+ x87 y88)))))
  6070. (define (main) : Integer ()
  6071. ((mainstart .
  6072. (seq (assign tmp89 (fun-ref add86))
  6073. (tailcall tmp89 40 2))))))
  6074. \end{lstlisting}
  6075. \end{minipage}
  6076. &
  6077. $\Rightarrow$
  6078. \begin{minipage}{0.5\textwidth}
  6079. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6080. (program ()
  6081. (define (add86)
  6082. ((locals (x87 . Integer) (y88 . Integer))
  6083. (num-params . 2))
  6084. ((add86start .
  6085. (block ()
  6086. (movq (reg rcx) (var x87))
  6087. (movq (reg rdx) (var y88))
  6088. (movq (var x87) (reg rax))
  6089. (addq (var y88) (reg rax))
  6090. (jmp add86conclusion)))))
  6091. (define (main)
  6092. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6093. (num-params . 0))
  6094. ((mainstart .
  6095. (block ()
  6096. (leaq (fun-ref add86) (var tmp89))
  6097. (movq (int 40) (reg rcx))
  6098. (movq (int 2) (reg rdx))
  6099. (tail-jmp (var tmp89))))))
  6100. \end{lstlisting}
  6101. $\Downarrow$
  6102. \end{minipage}
  6103. \end{tabular}
  6104. \begin{tabular}{lll}
  6105. \begin{minipage}{0.3\textwidth}
  6106. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6107. _add90start:
  6108. movq %rcx, %rsi
  6109. movq %rdx, %rcx
  6110. movq %rsi, %rax
  6111. addq %rcx, %rax
  6112. jmp _add90conclusion
  6113. .globl _add90
  6114. .align 16
  6115. _add90:
  6116. pushq %rbp
  6117. movq %rsp, %rbp
  6118. pushq %r12
  6119. pushq %rbx
  6120. pushq %r13
  6121. pushq %r14
  6122. subq $0, %rsp
  6123. jmp _add90start
  6124. _add90conclusion:
  6125. addq $0, %rsp
  6126. popq %r14
  6127. popq %r13
  6128. popq %rbx
  6129. popq %r12
  6130. subq $0, %r15
  6131. popq %rbp
  6132. retq
  6133. \end{lstlisting}
  6134. \end{minipage}
  6135. &
  6136. \begin{minipage}{0.3\textwidth}
  6137. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6138. _mainstart:
  6139. leaq _add90(%rip), %rsi
  6140. movq $40, %rcx
  6141. movq $2, %rdx
  6142. movq %rsi, %rax
  6143. addq $0, %rsp
  6144. popq %r14
  6145. popq %r13
  6146. popq %rbx
  6147. popq %r12
  6148. subq $0, %r15
  6149. popq %rbp
  6150. jmp *%rax
  6151. .globl _main
  6152. .align 16
  6153. _main:
  6154. pushq %rbp
  6155. movq %rsp, %rbp
  6156. pushq %r12
  6157. pushq %rbx
  6158. pushq %r13
  6159. pushq %r14
  6160. subq $0, %rsp
  6161. movq $16384, %rdi
  6162. movq $16, %rsi
  6163. callq _initialize
  6164. movq _rootstack_begin(%rip), %r15
  6165. jmp _mainstart
  6166. \end{lstlisting}
  6167. \end{minipage}
  6168. &
  6169. \begin{minipage}{0.3\textwidth}
  6170. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6171. _mainconclusion:
  6172. addq $0, %rsp
  6173. popq %r14
  6174. popq %r13
  6175. popq %rbx
  6176. popq %r12
  6177. subq $0, %r15
  6178. popq %rbp
  6179. retq
  6180. \end{lstlisting}
  6181. \end{minipage}
  6182. \end{tabular}
  6183. \caption{Example compilation of a simple function to x86.}
  6184. \label{fig:add-fun}
  6185. \end{figure}
  6186. \begin{exercise}\normalfont
  6187. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6188. Create 5 new programs that use functions, including examples that pass
  6189. functions and return functions from other functions and including
  6190. recursive functions. Test your compiler on these new programs and all
  6191. of your previously created test programs.
  6192. \end{exercise}
  6193. \begin{figure}[p]
  6194. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6195. \node (R4) at (0,2) {\large $R_4$};
  6196. \node (R4-2) at (3,2) {\large $R_4$};
  6197. \node (R4-3) at (6,2) {\large $R_4$};
  6198. \node (F1-1) at (12,0) {\large $F_1$};
  6199. \node (F1-2) at (9,0) {\large $F_1$};
  6200. \node (F1-3) at (6,0) {\large $F_1$};
  6201. \node (F1-4) at (3,0) {\large $F_1$};
  6202. \node (C3-1) at (6,-2) {\large $C_3$};
  6203. \node (C3-2) at (3,-2) {\large $C_3$};
  6204. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6205. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6206. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6207. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6208. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6209. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6210. \path[->,bend left=15] (R4) edge [above] node
  6211. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6212. \path[->,bend left=15] (R4-2) edge [above] node
  6213. {\ttfamily\footnotesize uniquify} (R4-3);
  6214. \path[->,bend left=15] (R4-3) edge [right] node
  6215. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6216. \path[->,bend left=15] (F1-1) edge [below] node
  6217. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6218. \path[->,bend right=15] (F1-2) edge [above] node
  6219. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6220. \path[->,bend right=15] (F1-3) edge [above] node
  6221. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6222. \path[->,bend left=15] (F1-4) edge [right] node
  6223. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6224. \path[->,bend left=15] (C3-1) edge [below] node
  6225. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6226. \path[->,bend right=15] (C3-2) edge [left] node
  6227. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6228. \path[->,bend left=15] (x86-2) edge [left] node
  6229. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6230. \path[->,bend right=15] (x86-2-1) edge [below] node
  6231. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6232. \path[->,bend right=15] (x86-2-2) edge [left] node
  6233. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6234. \path[->,bend left=15] (x86-3) edge [above] node
  6235. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6236. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6237. \end{tikzpicture}
  6238. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6239. \label{fig:R4-passes}
  6240. \end{figure}
  6241. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6242. the compilation of $R_4$.
  6243. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6244. \chapter{Lexically Scoped Functions}
  6245. \label{ch:lambdas}
  6246. This chapter studies lexically scoped functions as they appear in
  6247. functional languages such as Racket. By lexical scoping we mean that a
  6248. function's body may refer to variables whose binding site is outside
  6249. of the function, in an enclosing scope.
  6250. %
  6251. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6252. anonymous function defined using the \key{lambda} form. The body of
  6253. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6254. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6255. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6256. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6257. returned from the function \code{f}. Below the definition of \code{f},
  6258. we have two calls to \code{f} with different arguments for \code{x},
  6259. first \code{5} then \code{3}. The functions returned from \code{f} are
  6260. bound to variables \code{g} and \code{h}. Even though these two
  6261. functions were created by the same \code{lambda}, they are really
  6262. different functions because they use different values for
  6263. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6264. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6265. the result of this program is \code{42}.
  6266. \begin{figure}[btp]
  6267. % s4_6.rkt
  6268. \begin{lstlisting}
  6269. (define (f [x : Integer]) : (Integer -> Integer)
  6270. (let ([y 4])
  6271. (lambda: ([z : Integer]) : Integer
  6272. (+ x (+ y z)))))
  6273. (let ([g (f 5)])
  6274. (let ([h (f 3)])
  6275. (+ (g 11) (h 15))))
  6276. \end{lstlisting}
  6277. \caption{Example of a lexically scoped function.}
  6278. \label{fig:lexical-scoping}
  6279. \end{figure}
  6280. \section{The $R_5$ Language}
  6281. The syntax for this language with anonymous functions and lexical
  6282. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6283. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6284. for function application. In this chapter we shall describe how to
  6285. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6286. into a combination of functions (as in $R_4$) and tuples (as in
  6287. $R_3$).
  6288. \begin{figure}[tp]
  6289. \centering
  6290. \fbox{
  6291. \begin{minipage}{0.96\textwidth}
  6292. \[
  6293. \begin{array}{lcl}
  6294. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6295. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6296. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6297. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6298. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6299. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6300. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6301. \mid (\key{and}\;\Exp\;\Exp)
  6302. \mid (\key{or}\;\Exp\;\Exp)
  6303. \mid (\key{not}\;\Exp) } \\
  6304. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6305. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6306. (\key{vector-ref}\;\Exp\;\Int)} \\
  6307. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6308. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6309. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6310. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6311. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6312. \end{array}
  6313. \]
  6314. \end{minipage}
  6315. }
  6316. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6317. with \key{lambda}.}
  6318. \label{fig:r5-syntax}
  6319. \end{figure}
  6320. To compile lexically-scoped functions to top-level function
  6321. definitions, the compiler will need to provide special treatment to
  6322. variable occurrences such as \code{x} and \code{y} in the body of the
  6323. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6324. of $R_4$ may not refer to variables defined outside the function. To
  6325. identify such variable occurrences, we review the standard notion of
  6326. free variable.
  6327. \begin{definition}
  6328. A variable is \emph{free with respect to an expression} $e$ if the
  6329. variable occurs inside $e$ but does not have an enclosing binding in
  6330. $e$.
  6331. \end{definition}
  6332. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6333. free with respect to the expression \code{(+ x (+ y z))}. On the
  6334. other hand, only \code{x} and \code{y} are free with respect to the
  6335. following expression because \code{z} is bound by the \code{lambda}.
  6336. \begin{lstlisting}
  6337. (lambda: ([z : Integer]) : Integer
  6338. (+ x (+ y z)))
  6339. \end{lstlisting}
  6340. Once we have identified the free variables of a \code{lambda}, we need
  6341. to arrange for some way to transport, at runtime, the values of those
  6342. variables from the point where the \code{lambda} was created to the
  6343. point where the \code{lambda} is applied. Referring again to
  6344. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6345. needs to be used in the application of \code{g} to \code{11}, but the
  6346. binding of \code{x} to \code{3} needs to be used in the application of
  6347. \code{h} to \code{15}. An efficient solution to the problem, due to
  6348. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6349. free variables together with the function pointer for the lambda's
  6350. code, an arrangement called a \emph{flat closure} (which we shorten to
  6351. just ``closure'') . Fortunately, we have all the ingredients to make
  6352. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6353. Chapter~\ref{ch:functions} gave us function pointers. The function
  6354. pointer shall reside at index $0$ and the values for free variables
  6355. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6356. the two closures created by the two calls to \code{f} in
  6357. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6358. the same \key{lambda}, they share the same function pointer but differ
  6359. in the values for the free variable \code{x}.
  6360. \begin{figure}[tbp]
  6361. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6362. \caption{Example closure representation for the \key{lambda}'s
  6363. in Figure~\ref{fig:lexical-scoping}.}
  6364. \label{fig:closures}
  6365. \end{figure}
  6366. \section{Interpreting $R_5$}
  6367. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6368. $R_5$. The clause for \key{lambda} saves the current environment
  6369. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6370. the environment from the \key{lambda}, the \code{lam-env}, when
  6371. interpreting the body of the \key{lambda}. The \code{lam-env}
  6372. environment is extended with the mapping of parameters to argument
  6373. values.
  6374. \begin{figure}[tbp]
  6375. \begin{lstlisting}
  6376. (define (interp-exp env)
  6377. (lambda (e)
  6378. (define recur (interp-exp env))
  6379. (match e
  6380. ...
  6381. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6382. `(lambda ,xs ,body ,env)]
  6383. [`(app ,fun ,args ...)
  6384. (define fun-val ((interp-exp env) fun))
  6385. (define arg-vals (map (interp-exp env) args))
  6386. (match fun-val
  6387. [`(lambda (,xs ...) ,body ,lam-env)
  6388. (define new-env (append (map cons xs arg-vals) lam-env))
  6389. ((interp-exp new-env) body)]
  6390. [else (error "interp-exp, expected function, not" fun-val)])]
  6391. [else (error 'interp-exp "unrecognized expression")]
  6392. )))
  6393. \end{lstlisting}
  6394. \caption{Interpreter for $R_5$.}
  6395. \label{fig:interp-R5}
  6396. \end{figure}
  6397. \section{Type Checking $R_5$}
  6398. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6399. \key{lambda} form. The body of the \key{lambda} is checked in an
  6400. environment that includes the current environment (because it is
  6401. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6402. require the body's type to match the declared return type.
  6403. \begin{figure}[tbp]
  6404. \begin{lstlisting}
  6405. (define (typecheck-R5 env)
  6406. (lambda (e)
  6407. (match e
  6408. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6409. (define new-env (append (map cons xs Ts) env))
  6410. (define bodyT ((typecheck-R5 new-env) body))
  6411. (cond [(equal? rT bodyT)
  6412. `(,@Ts -> ,rT)]
  6413. [else
  6414. (error "mismatch in return type" bodyT rT)])]
  6415. ...
  6416. )))
  6417. \end{lstlisting}
  6418. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6419. \label{fig:typecheck-R5}
  6420. \end{figure}
  6421. \section{Closure Conversion}
  6422. The compiling of lexically-scoped functions into top-level function
  6423. definitions is accomplished in the pass \code{convert-to-closures}
  6424. that comes after \code{reveal-functions} and before
  6425. \code{limit-functions}.
  6426. As usual, we shall implement the pass as a recursive function over the
  6427. AST. All of the action is in the clauses for \key{lambda} and
  6428. \key{app}. We transform a \key{lambda} expression into an expression
  6429. that creates a closure, that is, creates a vector whose first element
  6430. is a function pointer and the rest of the elements are the free
  6431. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6432. generated to identify the function.
  6433. \begin{tabular}{lll}
  6434. \begin{minipage}{0.4\textwidth}
  6435. \begin{lstlisting}
  6436. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6437. \end{lstlisting}
  6438. \end{minipage}
  6439. &
  6440. $\Rightarrow$
  6441. &
  6442. \begin{minipage}{0.4\textwidth}
  6443. \begin{lstlisting}
  6444. (vector |\itm{name}| |\itm{fvs}| ...)
  6445. \end{lstlisting}
  6446. \end{minipage}
  6447. \end{tabular} \\
  6448. %
  6449. In addition to transforming each \key{lambda} into a \key{vector}, we
  6450. must create a top-level function definition for each \key{lambda}, as
  6451. shown below.\\
  6452. \begin{minipage}{0.8\textwidth}
  6453. \begin{lstlisting}
  6454. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6455. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6456. ...
  6457. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6458. |\itm{body'}|)...))
  6459. \end{lstlisting}
  6460. \end{minipage}\\
  6461. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6462. parameters are the normal parameters of the \key{lambda}. The types
  6463. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6464. underscore is a dummy type because it is rather difficult to give a
  6465. type to the function in the closure's type, and it does not matter.
  6466. The sequence of \key{let} forms bind the free variables to their
  6467. values obtained from the closure.
  6468. We transform function application into code that retrieves the
  6469. function pointer from the closure and then calls the function, passing
  6470. in the closure as the first argument. We bind $e'$ to a temporary
  6471. variable to avoid code duplication.
  6472. \begin{tabular}{lll}
  6473. \begin{minipage}{0.3\textwidth}
  6474. \begin{lstlisting}
  6475. (app |$e$| |\itm{es}| ...)
  6476. \end{lstlisting}
  6477. \end{minipage}
  6478. &
  6479. $\Rightarrow$
  6480. &
  6481. \begin{minipage}{0.5\textwidth}
  6482. \begin{lstlisting}
  6483. (let ([|\itm{tmp}| |$e'$|])
  6484. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6485. \end{lstlisting}
  6486. \end{minipage}
  6487. \end{tabular} \\
  6488. There is also the question of what to do with top-level function
  6489. definitions. To maintain a uniform translation of function
  6490. application, we turn function references into closures.
  6491. \begin{tabular}{lll}
  6492. \begin{minipage}{0.3\textwidth}
  6493. \begin{lstlisting}
  6494. (fun-ref |$f$|)
  6495. \end{lstlisting}
  6496. \end{minipage}
  6497. &
  6498. $\Rightarrow$
  6499. &
  6500. \begin{minipage}{0.5\textwidth}
  6501. \begin{lstlisting}
  6502. (vector (fun-ref |$f$|))
  6503. \end{lstlisting}
  6504. \end{minipage}
  6505. \end{tabular} \\
  6506. %
  6507. The top-level function definitions need to be updated as well to take
  6508. an extra closure parameter.
  6509. \section{An Example Translation}
  6510. \label{sec:example-lambda}
  6511. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6512. conversion for the example program demonstrating lexical scoping that
  6513. we discussed at the beginning of this chapter.
  6514. \begin{figure}[h]
  6515. \begin{minipage}{0.8\textwidth}
  6516. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6517. (program
  6518. (define (f [x : Integer]) : (Integer -> Integer)
  6519. (let ([y 4])
  6520. (lambda: ([z : Integer]) : Integer
  6521. (+ x (+ y z)))))
  6522. (let ([g (f 5)])
  6523. (let ([h (f 3)])
  6524. (+ (g 11) (h 15)))))
  6525. \end{lstlisting}
  6526. $\Downarrow$
  6527. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6528. (program (type Integer)
  6529. (define (f (x : Integer)) : (Integer -> Integer)
  6530. (let ((y 4))
  6531. (lambda: ((z : Integer)) : Integer
  6532. (+ x (+ y z)))))
  6533. (let ((g (app (fun-ref f) 5)))
  6534. (let ((h (app (fun-ref f) 3)))
  6535. (+ (app g 11) (app h 15)))))
  6536. \end{lstlisting}
  6537. $\Downarrow$
  6538. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6539. (program (type Integer)
  6540. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6541. (let ((y 4))
  6542. (vector (fun-ref lam.1) x y)))
  6543. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6544. (let ((x (vector-ref clos.2 1)))
  6545. (let ((y (vector-ref clos.2 2)))
  6546. (+ x (+ y z)))))
  6547. (let ((g (let ((t.1 (vector (fun-ref f))))
  6548. (app (vector-ref t.1 0) t.1 5))))
  6549. (let ((h (let ((t.2 (vector (fun-ref f))))
  6550. (app (vector-ref t.2 0) t.2 3))))
  6551. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6552. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6553. \end{lstlisting}
  6554. \end{minipage}
  6555. \caption{Example of closure conversion.}
  6556. \label{fig:lexical-functions-example}
  6557. \end{figure}
  6558. \begin{figure}[p]
  6559. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6560. \node (R4) at (0,2) {\large $R_4$};
  6561. \node (R4-2) at (3,2) {\large $R_4$};
  6562. \node (R4-3) at (6,2) {\large $R_4$};
  6563. \node (F1-1) at (12,0) {\large $F_1$};
  6564. \node (F1-2) at (9,0) {\large $F_1$};
  6565. \node (F1-3) at (6,0) {\large $F_1$};
  6566. \node (F1-4) at (3,0) {\large $F_1$};
  6567. \node (F1-5) at (0,0) {\large $F_1$};
  6568. \node (C3-1) at (6,-2) {\large $C_3$};
  6569. \node (C3-2) at (3,-2) {\large $C_3$};
  6570. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6571. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6572. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6573. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6574. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6575. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6576. \path[->,bend left=15] (R4) edge [above] node
  6577. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6578. \path[->,bend left=15] (R4-2) edge [above] node
  6579. {\ttfamily\footnotesize uniquify} (R4-3);
  6580. \path[->] (R4-3) edge [right] node
  6581. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6582. \path[->,bend left=15] (F1-1) edge [below] node
  6583. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6584. \path[->,bend right=15] (F1-2) edge [above] node
  6585. {\ttfamily\footnotesize limit-functions} (F1-3);
  6586. \path[->,bend right=15] (F1-3) edge [above] node
  6587. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6588. \path[->,bend right=15] (F1-4) edge [above] node
  6589. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6590. \path[->] (F1-5) edge [left] node
  6591. {\ttfamily\footnotesize explicate-control} (C3-1);
  6592. \path[->,bend left=15] (C3-1) edge [below] node
  6593. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6594. \path[->,bend right=15] (C3-2) edge [left] node
  6595. {\ttfamily\footnotesize select-instr.} (x86-2);
  6596. \path[->,bend left=15] (x86-2) edge [left] node
  6597. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6598. \path[->,bend right=15] (x86-2-1) edge [below] node
  6599. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6600. \path[->,bend right=15] (x86-2-2) edge [left] node
  6601. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6602. \path[->,bend left=15] (x86-3) edge [above] node
  6603. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6604. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6605. \end{tikzpicture}
  6606. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6607. functions.}
  6608. \label{fig:R5-passes}
  6609. \end{figure}
  6610. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6611. for the compilation of $R_5$.
  6612. \begin{exercise}\normalfont
  6613. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6614. Create 5 new programs that use \key{lambda} functions and make use of
  6615. lexical scoping. Test your compiler on these new programs and all of
  6616. your previously created test programs.
  6617. \end{exercise}
  6618. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6619. \chapter{Dynamic Typing}
  6620. \label{ch:type-dynamic}
  6621. In this chapter we discuss the compilation of a dynamically typed
  6622. language, named $R_7$, that is a subset of the Racket
  6623. language. (Recall that in the previous chapters we have studied
  6624. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6625. languages, an expression may produce values of differing
  6626. type. Consider the following example with a conditional expression
  6627. that may return a Boolean or an integer depending on the input to the
  6628. program.
  6629. \begin{lstlisting}
  6630. (not (if (eq? (read) 1) #f 0))
  6631. \end{lstlisting}
  6632. Languages that allow expressions to produce different kinds of values
  6633. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6634. such as subtype polymorphism and parametric
  6635. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6636. talking about here does not have a special name, but it is the usual
  6637. kind that arises in dynamically typed languages.
  6638. Another characteristic of dynamically typed languages is that
  6639. primitive operations, such as \code{not}, are often defined to operate
  6640. on many different types of values. In fact, in Racket, the \code{not}
  6641. operator produces a result for any kind of value: given \code{\#f} it
  6642. returns \code{\#t} and given anything else it returns \code{\#f}.
  6643. Furthermore, even when primitive operations restrict their inputs to
  6644. values of a certain type, this restriction is enforced at runtime
  6645. instead of during compilation. For example, the following vector
  6646. reference results in a run-time contract violation.
  6647. \begin{lstlisting}
  6648. (vector-ref (vector 42) #t)
  6649. \end{lstlisting}
  6650. \begin{figure}[tp]
  6651. \centering
  6652. \fbox{
  6653. \begin{minipage}{0.97\textwidth}
  6654. \[
  6655. \begin{array}{rcl}
  6656. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6657. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6658. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6659. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6660. &\mid& \key{\#t} \mid \key{\#f}
  6661. \mid (\key{and}\;\Exp\;\Exp)
  6662. \mid (\key{or}\;\Exp\;\Exp)
  6663. \mid (\key{not}\;\Exp) \\
  6664. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6665. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6666. (\key{vector-ref}\;\Exp\;\Exp) \\
  6667. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6668. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6669. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6670. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6671. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6672. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6673. \end{array}
  6674. \]
  6675. \end{minipage}
  6676. }
  6677. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6678. \label{fig:r7-syntax}
  6679. \end{figure}
  6680. The syntax of $R_7$, our subset of Racket, is defined in
  6681. Figure~\ref{fig:r7-syntax}.
  6682. %
  6683. The definitional interpreter for $R_7$ is given in
  6684. Figure~\ref{fig:interp-R7}.
  6685. \begin{figure}[tbp]
  6686. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6687. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6688. (define (valid-op? op) (member op '(+ - and or not)))
  6689. (define (interp-r7 env)
  6690. (lambda (ast)
  6691. (define recur (interp-r7 env))
  6692. (match ast
  6693. [(? symbol?) (lookup ast env)]
  6694. [(? integer?) `(inject ,ast Integer)]
  6695. [#t `(inject #t Boolean)]
  6696. [#f `(inject #f Boolean)]
  6697. [`(read) `(inject ,(read-fixnum) Integer)]
  6698. [`(lambda (,xs ...) ,body)
  6699. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6700. [`(define (,f ,xs ...) ,body)
  6701. (mcons f `(lambda ,xs ,body))]
  6702. [`(program ,ds ... ,body)
  6703. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6704. (for/list ([b top-level])
  6705. (set-mcdr! b (match (mcdr b)
  6706. [`(lambda ,xs ,body)
  6707. `(inject (lambda ,xs ,body ,top-level)
  6708. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6709. ((interp-r7 top-level) body))]
  6710. [`(vector ,(app recur elts) ...)
  6711. (define tys (map get-tagged-type elts))
  6712. `(inject ,(apply vector elts) (Vector ,@tys))]
  6713. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6714. (match v1
  6715. [`(inject ,vec ,ty)
  6716. (vector-set! vec n v2)
  6717. `(inject (void) Void)])]
  6718. [`(vector-ref ,(app recur v) ,n)
  6719. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6720. [`(let ([,x ,(app recur v)]) ,body)
  6721. ((interp-r7 (cons (cons x v) env)) body)]
  6722. [`(,op ,es ...) #:when (valid-op? op)
  6723. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6724. [`(eq? ,(app recur l) ,(app recur r))
  6725. `(inject ,(equal? l r) Boolean)]
  6726. [`(if ,(app recur q) ,t ,f)
  6727. (match q
  6728. [`(inject #f Boolean) (recur f)]
  6729. [else (recur t)])]
  6730. [`(,(app recur f-val) ,(app recur vs) ...)
  6731. (match f-val
  6732. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6733. (define new-env (append (map cons xs vs) lam-env))
  6734. ((interp-r7 new-env) body)]
  6735. [else (error "interp-r7, expected function, not" f-val)])])))
  6736. \end{lstlisting}
  6737. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6738. \label{fig:interp-R7}
  6739. \end{figure}
  6740. Let us consider how we might compile $R_7$ to x86, thinking about the
  6741. first example above. Our bit-level representation of the Boolean
  6742. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6743. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6744. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6745. general, cannot be determined at compile time, but depends on the
  6746. runtime type of its input, as in the example above that depends on the
  6747. result of \code{(read)}.
  6748. The way around this problem is to include information about a value's
  6749. runtime type in the value itself, so that this information can be
  6750. inspected by operators such as \code{not}. In particular, we shall
  6751. steal the 3 right-most bits from our 64-bit values to encode the
  6752. runtime type. We shall use $001$ to identify integers, $100$ for
  6753. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6754. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6755. define the following auxiliary function.
  6756. \begin{align*}
  6757. \itm{tagof}(\key{Integer}) &= 001 \\
  6758. \itm{tagof}(\key{Boolean}) &= 100 \\
  6759. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6760. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6761. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6762. \itm{tagof}(\key{Void}) &= 101
  6763. \end{align*}
  6764. (We shall say more about the new \key{Vectorof} type shortly.)
  6765. This stealing of 3 bits comes at some
  6766. price: our integers are reduced to ranging from $-2^{60}$ to
  6767. $2^{60}$. The stealing does not adversely affect vectors and
  6768. procedures because those values are addresses, and our addresses are
  6769. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6770. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6771. bits with the tag and we can simply zero-out the tag to recover the
  6772. original address.
  6773. In some sense, these tagged values are a new kind of value. Indeed,
  6774. we can extend our \emph{typed} language with tagged values by adding a
  6775. new type to classify them, called \key{Any}, and with operations for
  6776. creating and using tagged values, yielding the $R_6$ language that we
  6777. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6778. fundamental support for polymorphism and runtime types that we need to
  6779. support dynamic typing.
  6780. There is an interesting interaction between tagged values and garbage
  6781. collection. A variable of type \code{Any} might refer to a vector and
  6782. therefore it might be a root that needs to be inspected and copied
  6783. during garbage collection. Thus, we need to treat variables of type
  6784. \code{Any} in a similar way to variables of type \code{Vector} for
  6785. purposes of register allocation, which we discuss in
  6786. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6787. variable of type \code{Any} is spilled, it must be spilled to the root
  6788. stack. But this means that the garbage collector needs to be able to
  6789. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6790. value that points to a tuple, and (3) a tagged value that is not a
  6791. tuple. We enable this differentiation by choosing not to use the tag
  6792. $000$. Instead, that bit pattern is reserved for identifying plain old
  6793. pointers to tuples. On the other hand, if one of the first three bits
  6794. is set, then we have a tagged value, and inspecting the tag can
  6795. differentiation between vectors ($010$) and the other kinds of values.
  6796. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6797. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6798. extend our compiler to handle the new features of $R_6$
  6799. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6800. \ref{sec:register-allocation-r6}).
  6801. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6802. \label{sec:r6-lang}
  6803. \begin{figure}[tp]
  6804. \centering
  6805. \fbox{
  6806. \begin{minipage}{0.97\textwidth}
  6807. \[
  6808. \begin{array}{lcl}
  6809. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6810. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6811. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6812. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6813. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6814. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6815. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6816. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6817. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6818. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6819. \mid (\key{and}\;\Exp\;\Exp)
  6820. \mid (\key{or}\;\Exp\;\Exp)
  6821. \mid (\key{not}\;\Exp)} \\
  6822. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6823. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6824. (\key{vector-ref}\;\Exp\;\Int)} \\
  6825. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6826. &\mid& \gray{(\Exp \; \Exp^{*})
  6827. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6828. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6829. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6830. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6831. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6832. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6833. \end{array}
  6834. \]
  6835. \end{minipage}
  6836. }
  6837. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6838. with \key{Any}.}
  6839. \label{fig:r6-syntax}
  6840. \end{figure}
  6841. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6842. $(\key{inject}\; e\; T)$ form converts the value produced by
  6843. expression $e$ of type $T$ into a tagged value. The
  6844. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6845. expression $e$ into a value of type $T$ or else halts the program if
  6846. the type tag is equivalent to $T$. We treat
  6847. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6848. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6849. Note that in both \key{inject} and
  6850. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6851. which simplifies the implementation and corresponds with what is
  6852. needed for compiling untyped Racket. The type predicates,
  6853. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6854. if the tag corresponds to the predicate, and return \key{\#t}
  6855. otherwise.
  6856. %
  6857. Selections from the type checker for $R_6$ are shown in
  6858. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6859. Figure~\ref{fig:interp-R6}.
  6860. \begin{figure}[btp]
  6861. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6862. (define (flat-ty? ty) ...)
  6863. (define (typecheck-R6 env)
  6864. (lambda (e)
  6865. (define recur (typecheck-R6 env))
  6866. (match e
  6867. [`(inject ,e ,ty)
  6868. (unless (flat-ty? ty)
  6869. (error "may only inject a value of flat type, not ~a" ty))
  6870. (define-values (new-e e-ty) (recur e))
  6871. (cond
  6872. [(equal? e-ty ty)
  6873. (values `(inject ,new-e ,ty) 'Any)]
  6874. [else
  6875. (error "inject expected ~a to have type ~a" e ty)])]
  6876. [`(project ,e ,ty)
  6877. (unless (flat-ty? ty)
  6878. (error "may only project to a flat type, not ~a" ty))
  6879. (define-values (new-e e-ty) (recur e))
  6880. (cond
  6881. [(equal? e-ty 'Any)
  6882. (values `(project ,new-e ,ty) ty)]
  6883. [else
  6884. (error "project expected ~a to have type Any" e)])]
  6885. [`(vector-ref ,e ,i)
  6886. (define-values (new-e e-ty) (recur e))
  6887. (match e-ty
  6888. [`(Vector ,ts ...) ...]
  6889. [`(Vectorof ,ty)
  6890. (unless (exact-nonnegative-integer? i)
  6891. (error 'type-check "invalid index ~a" i))
  6892. (values `(vector-ref ,new-e ,i) ty)]
  6893. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6894. ...
  6895. )))
  6896. \end{lstlisting}
  6897. \caption{Type checker for parts of the $R_6$ language.}
  6898. \label{fig:typecheck-R6}
  6899. \end{figure}
  6900. % to do: add rules for vector-ref, etc. for Vectorof
  6901. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6902. \begin{figure}[btp]
  6903. \begin{lstlisting}
  6904. (define primitives (set 'boolean? ...))
  6905. (define (interp-op op)
  6906. (match op
  6907. ['boolean? (lambda (v)
  6908. (match v
  6909. [`(tagged ,v1 Boolean) #t]
  6910. [else #f]))]
  6911. ...))
  6912. ;; Equivalence of flat types
  6913. (define (tyeq? t1 t2)
  6914. (match `(,t1 ,t2)
  6915. [`((Vectorof Any) (Vector ,t2s ...))
  6916. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6917. [`((Vector ,t1s ...) (Vectorof Any))
  6918. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6919. [else (equal? t1 t2)]))
  6920. (define (interp-R6 env)
  6921. (lambda (ast)
  6922. (match ast
  6923. [`(inject ,e ,t)
  6924. `(tagged ,((interp-R6 env) e) ,t)]
  6925. [`(project ,e ,t2)
  6926. (define v ((interp-R6 env) e))
  6927. (match v
  6928. [`(tagged ,v1 ,t1)
  6929. (cond [(tyeq? t1 t2)
  6930. v1]
  6931. [else
  6932. (error "in project, type mismatch" t1 t2)])]
  6933. [else
  6934. (error "in project, expected tagged value" v)])]
  6935. ...)))
  6936. \end{lstlisting}
  6937. \caption{Interpreter for $R_6$.}
  6938. \label{fig:interp-R6}
  6939. \end{figure}
  6940. %\clearpage
  6941. \section{Shrinking $R_6$}
  6942. \label{sec:shrink-r6}
  6943. In the \code{shrink} pass we recommend compiling \code{project} into
  6944. an explicit \code{if} expression that uses three new operations:
  6945. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6946. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6947. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6948. value from a tagged value. Finally, the \code{exit} operation ends the
  6949. execution of the program by invoking the operating system's
  6950. \code{exit} function. So the translation for \code{project} is as
  6951. follows. (We have omitted the \code{has-type} AST nodes to make this
  6952. output more readable.)
  6953. \begin{tabular}{lll}
  6954. \begin{minipage}{0.3\textwidth}
  6955. \begin{lstlisting}
  6956. (project |$e$| |$\Type$|)
  6957. \end{lstlisting}
  6958. \end{minipage}
  6959. &
  6960. $\Rightarrow$
  6961. &
  6962. \begin{minipage}{0.5\textwidth}
  6963. \begin{lstlisting}
  6964. (let ([|$\itm{tmp}$| |$e'$|])
  6965. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6966. (value-of-any |$\itm{tmp}$|)
  6967. (exit)))
  6968. \end{lstlisting}
  6969. \end{minipage}
  6970. \end{tabular} \\
  6971. Similarly, we recommend translating the type predicates
  6972. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6973. \section{Instruction Selection for $R_6$}
  6974. \label{sec:select-r6}
  6975. \paragraph{Inject}
  6976. We recommend compiling an \key{inject} as follows if the type is
  6977. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6978. destination to the left by the number of bits specified its source
  6979. argument (in this case $3$, the length of the tag) and it preserves
  6980. the sign of the integer. We use the \key{orq} instruction to combine
  6981. the tag and the value to form the tagged value. \\
  6982. \begin{tabular}{lll}
  6983. \begin{minipage}{0.4\textwidth}
  6984. \begin{lstlisting}
  6985. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6986. \end{lstlisting}
  6987. \end{minipage}
  6988. &
  6989. $\Rightarrow$
  6990. &
  6991. \begin{minipage}{0.5\textwidth}
  6992. \begin{lstlisting}
  6993. (movq |$e'$| |\itm{lhs}'|)
  6994. (salq (int 3) |\itm{lhs}'|)
  6995. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6996. \end{lstlisting}
  6997. \end{minipage}
  6998. \end{tabular} \\
  6999. The instruction selection for vectors and procedures is different
  7000. because their is no need to shift them to the left. The rightmost 3
  7001. bits are already zeros as described above. So we just combine the
  7002. value and the tag using \key{orq}. \\
  7003. \begin{tabular}{lll}
  7004. \begin{minipage}{0.4\textwidth}
  7005. \begin{lstlisting}
  7006. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7007. \end{lstlisting}
  7008. \end{minipage}
  7009. &
  7010. $\Rightarrow$
  7011. &
  7012. \begin{minipage}{0.5\textwidth}
  7013. \begin{lstlisting}
  7014. (movq |$e'$| |\itm{lhs}'|)
  7015. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7016. \end{lstlisting}
  7017. \end{minipage}
  7018. \end{tabular}
  7019. \paragraph{Tag of Any}
  7020. Recall that the \code{tag-of-any} operation extracts the type tag from
  7021. a value of type \code{Any}. The type tag is the bottom three bits, so
  7022. we obtain the tag by taking the bitwise-and of the value with $111$
  7023. ($7$ in decimal).
  7024. \begin{tabular}{lll}
  7025. \begin{minipage}{0.4\textwidth}
  7026. \begin{lstlisting}
  7027. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7028. \end{lstlisting}
  7029. \end{minipage}
  7030. &
  7031. $\Rightarrow$
  7032. &
  7033. \begin{minipage}{0.5\textwidth}
  7034. \begin{lstlisting}
  7035. (movq |$e'$| |\itm{lhs}'|)
  7036. (andq (int 7) |\itm{lhs}'|)
  7037. \end{lstlisting}
  7038. \end{minipage}
  7039. \end{tabular}
  7040. \paragraph{Value of Any}
  7041. Like \key{inject}, the instructions for \key{value-of-any} are
  7042. different depending on whether the type $T$ is a pointer (vector or
  7043. procedure) or not (Integer or Boolean). The following shows the
  7044. instruction selection for Integer and Boolean. We produce an untagged
  7045. value by shifting it to the right by 3 bits.
  7046. %
  7047. \\
  7048. \begin{tabular}{lll}
  7049. \begin{minipage}{0.4\textwidth}
  7050. \begin{lstlisting}
  7051. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7052. \end{lstlisting}
  7053. \end{minipage}
  7054. &
  7055. $\Rightarrow$
  7056. &
  7057. \begin{minipage}{0.5\textwidth}
  7058. \begin{lstlisting}
  7059. (movq |$e'$| |\itm{lhs}'|)
  7060. (sarq (int 3) |\itm{lhs}'|)
  7061. \end{lstlisting}
  7062. \end{minipage}
  7063. \end{tabular} \\
  7064. %
  7065. In the case for vectors and procedures, there is no need to
  7066. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7067. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7068. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7069. \code{movq} into the destination $\itm{lhs}$. We then generate
  7070. \code{andq} with the tagged value to get the desired result. \\
  7071. %
  7072. \begin{tabular}{lll}
  7073. \begin{minipage}{0.4\textwidth}
  7074. \begin{lstlisting}
  7075. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7076. \end{lstlisting}
  7077. \end{minipage}
  7078. &
  7079. $\Rightarrow$
  7080. &
  7081. \begin{minipage}{0.5\textwidth}
  7082. \begin{lstlisting}
  7083. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7084. (andq |$e'$| |\itm{lhs}'|)
  7085. \end{lstlisting}
  7086. \end{minipage}
  7087. \end{tabular}
  7088. %% \paragraph{Type Predicates} We leave it to the reader to
  7089. %% devise a sequence of instructions to implement the type predicates
  7090. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7091. \section{Register Allocation for $R_6$}
  7092. \label{sec:register-allocation-r6}
  7093. As mentioned above, a variable of type \code{Any} might refer to a
  7094. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7095. of type \code{Any} in the same way that it treats variables of type
  7096. \code{Vector} for purposes of garbage collection. In particular,
  7097. \begin{itemize}
  7098. \item If a variable of type \code{Any} is live during a function call,
  7099. then it must be spilled. One way to accomplish this is to augment
  7100. the pass \code{build-interference} to mark all variables that are
  7101. live after a \code{callq} as interfering with all the registers.
  7102. \item If a variable of type \code{Any} is spilled, it must be spilled
  7103. to the root stack instead of the normal procedure call stack.
  7104. \end{itemize}
  7105. \begin{exercise}\normalfont
  7106. Expand your compiler to handle $R_6$ as discussed in the last few
  7107. sections. Create 5 new programs that use the \code{Any} type and the
  7108. new operations (\code{inject}, \code{project}, \code{boolean?},
  7109. etc.). Test your compiler on these new programs and all of your
  7110. previously created test programs.
  7111. \end{exercise}
  7112. \section{Compiling $R_7$ to $R_6$}
  7113. \label{sec:compile-r7}
  7114. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7115. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7116. given a subexpression $e$ of $R_7$, the pass will produce an
  7117. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7118. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7119. the Boolean \code{\#t}, which must be injected to produce an
  7120. expression of type \key{Any}.
  7121. %
  7122. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7123. addition, is representative of compilation for many operations: the
  7124. arguments have type \key{Any} and must be projected to \key{Integer}
  7125. before the addition can be performed.
  7126. The compilation of \key{lambda} (third row of
  7127. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7128. produce type annotations: we simply use \key{Any}.
  7129. %
  7130. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7131. has to account for some differences in behavior between $R_7$ and
  7132. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7133. kind of values can be used in various places. For example, the
  7134. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7135. the arguments need not be of the same type (but in that case, the
  7136. result will be \code{\#f}).
  7137. \begin{figure}[btp]
  7138. \centering
  7139. \begin{tabular}{|lll|} \hline
  7140. \begin{minipage}{0.25\textwidth}
  7141. \begin{lstlisting}
  7142. #t
  7143. \end{lstlisting}
  7144. \end{minipage}
  7145. &
  7146. $\Rightarrow$
  7147. &
  7148. \begin{minipage}{0.6\textwidth}
  7149. \begin{lstlisting}
  7150. (inject #t Boolean)
  7151. \end{lstlisting}
  7152. \end{minipage}
  7153. \\[2ex]\hline
  7154. \begin{minipage}{0.25\textwidth}
  7155. \begin{lstlisting}
  7156. (+ |$e_1$| |$e_2$|)
  7157. \end{lstlisting}
  7158. \end{minipage}
  7159. &
  7160. $\Rightarrow$
  7161. &
  7162. \begin{minipage}{0.6\textwidth}
  7163. \begin{lstlisting}
  7164. (inject
  7165. (+ (project |$e'_1$| Integer)
  7166. (project |$e'_2$| Integer))
  7167. Integer)
  7168. \end{lstlisting}
  7169. \end{minipage}
  7170. \\[2ex]\hline
  7171. \begin{minipage}{0.25\textwidth}
  7172. \begin{lstlisting}
  7173. (lambda (|$x_1 \ldots$|) |$e$|)
  7174. \end{lstlisting}
  7175. \end{minipage}
  7176. &
  7177. $\Rightarrow$
  7178. &
  7179. \begin{minipage}{0.6\textwidth}
  7180. \begin{lstlisting}
  7181. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7182. (Any|$\ldots$|Any -> Any))
  7183. \end{lstlisting}
  7184. \end{minipage}
  7185. \\[2ex]\hline
  7186. \begin{minipage}{0.25\textwidth}
  7187. \begin{lstlisting}
  7188. (app |$e_0$| |$e_1 \ldots e_n$|)
  7189. \end{lstlisting}
  7190. \end{minipage}
  7191. &
  7192. $\Rightarrow$
  7193. &
  7194. \begin{minipage}{0.6\textwidth}
  7195. \begin{lstlisting}
  7196. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7197. |$e'_1 \ldots e'_n$|)
  7198. \end{lstlisting}
  7199. \end{minipage}
  7200. \\[2ex]\hline
  7201. \begin{minipage}{0.25\textwidth}
  7202. \begin{lstlisting}
  7203. (vector-ref |$e_1$| |$e_2$|)
  7204. \end{lstlisting}
  7205. \end{minipage}
  7206. &
  7207. $\Rightarrow$
  7208. &
  7209. \begin{minipage}{0.6\textwidth}
  7210. \begin{lstlisting}
  7211. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7212. (let ([tmp2 (project |$e'_2$| Integer)])
  7213. (vector-ref tmp1 tmp2)))
  7214. \end{lstlisting}
  7215. \end{minipage}
  7216. \\[2ex]\hline
  7217. \begin{minipage}{0.25\textwidth}
  7218. \begin{lstlisting}
  7219. (if |$e_1$| |$e_2$| |$e_3$|)
  7220. \end{lstlisting}
  7221. \end{minipage}
  7222. &
  7223. $\Rightarrow$
  7224. &
  7225. \begin{minipage}{0.6\textwidth}
  7226. \begin{lstlisting}
  7227. (if (eq? |$e'_1$| (inject #f Boolean))
  7228. |$e'_3$|
  7229. |$e'_2$|)
  7230. \end{lstlisting}
  7231. \end{minipage}
  7232. \\[2ex]\hline
  7233. \begin{minipage}{0.25\textwidth}
  7234. \begin{lstlisting}
  7235. (eq? |$e_1$| |$e_2$|)
  7236. \end{lstlisting}
  7237. \end{minipage}
  7238. &
  7239. $\Rightarrow$
  7240. &
  7241. \begin{minipage}{0.6\textwidth}
  7242. \begin{lstlisting}
  7243. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7244. \end{lstlisting}
  7245. \end{minipage}
  7246. \\[2ex]\hline
  7247. \end{tabular}
  7248. \caption{Compiling $R_7$ to $R_6$.}
  7249. \label{fig:compile-r7-r6}
  7250. \end{figure}
  7251. \begin{exercise}\normalfont
  7252. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7253. Create tests for $R_7$ by adapting all of your previous test programs
  7254. by removing type annotations. Add 5 more tests programs that
  7255. specifically rely on the language being dynamically typed. That is,
  7256. they should not be legal programs in a statically typed language, but
  7257. nevertheless, they should be valid $R_7$ programs that run to
  7258. completion without error.
  7259. \end{exercise}
  7260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7261. \chapter{Gradual Typing}
  7262. \label{ch:gradual-typing}
  7263. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7264. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7265. \chapter{Parametric Polymorphism}
  7266. \label{ch:parametric-polymorphism}
  7267. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7268. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7269. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7270. \chapter{High-level Optimization}
  7271. \label{ch:high-level-optimization}
  7272. This chapter will present a procedure inlining pass based on the
  7273. algorithm of \citet{Waddell:1997fk}.
  7274. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7275. \chapter{Appendix}
  7276. \section{Interpreters}
  7277. \label{appendix:interp}
  7278. We provide several interpreters in the \key{interp.rkt} file. The
  7279. \key{interp-scheme} function takes an AST in one of the Racket-like
  7280. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7281. the program, returning the result value. The \key{interp-C} function
  7282. interprets an AST for a program in one of the C-like languages ($C_0,
  7283. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7284. for an x86 program.
  7285. \section{Utility Functions}
  7286. \label{appendix:utilities}
  7287. The utility function described in this section can be found in the
  7288. \key{utilities.rkt} file.
  7289. The \key{read-program} function takes a file path and parses that file
  7290. (it must be a Racket program) into an abstract syntax tree with a
  7291. \key{Program} node at the top.
  7292. The \key{parse-program} function takes an S-expression representation
  7293. of an AST and converts it into the struct-based representation.
  7294. The \key{assert} function displays the error message \key{msg} if the
  7295. Boolean \key{bool} is false.
  7296. \begin{lstlisting}
  7297. (define (assert msg bool) ...)
  7298. \end{lstlisting}
  7299. % remove discussion of lookup? -Jeremy
  7300. The \key{lookup} function takes a key and an alist, and returns the
  7301. first value that is associated with the given key, if there is one. If
  7302. not, an error is triggered. The alist may contain both immutable
  7303. pairs (built with \key{cons}) and mutable pairs (built with
  7304. \key{mcons}).
  7305. The \key{map2} function ...
  7306. %% \subsection{Graphs}
  7307. %% \begin{itemize}
  7308. %% \item The \code{make-graph} function takes a list of vertices
  7309. %% (symbols) and returns a graph.
  7310. %% \item The \code{add-edge} function takes a graph and two vertices and
  7311. %% adds an edge to the graph that connects the two vertices. The graph
  7312. %% is updated in-place. There is no return value for this function.
  7313. %% \item The \code{adjacent} function takes a graph and a vertex and
  7314. %% returns the set of vertices that are adjacent to the given
  7315. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7316. %% used with functions from the \code{racket/set} module.
  7317. %% \item The \code{vertices} function takes a graph and returns the list
  7318. %% of vertices in the graph.
  7319. %% \end{itemize}
  7320. \subsection{Testing}
  7321. The \key{interp-tests} function takes a compiler name (a string), a
  7322. description of the passes, an interpreter for the source language, a
  7323. test family name (a string), and a list of test numbers, and runs the
  7324. compiler passes and the interpreters to check whether the passes
  7325. correct. The description of the passes is a list with one entry per
  7326. pass. An entry is a list with three things: a string giving the name
  7327. of the pass, the function that implements the pass (a translator from
  7328. AST to AST), and a function that implements the interpreter (a
  7329. function from AST to result value) for the language of the output of
  7330. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7331. good choice. The \key{interp-tests} function assumes that the
  7332. subdirectory \key{tests} has a collection of Scheme programs whose names
  7333. all start with the family name, followed by an underscore and then the
  7334. test number, ending in \key{.scm}. Also, for each Scheme program there
  7335. is a file with the same number except that it ends with \key{.in} that
  7336. provides the input for the Scheme program.
  7337. \begin{lstlisting}
  7338. (define (interp-tests name passes test-family test-nums) ...)
  7339. \end{lstlisting}
  7340. The compiler-tests function takes a compiler name (a string) a
  7341. description of the passes (as described above for
  7342. \code{interp-tests}), a test family name (a string), and a list of
  7343. test numbers (see the comment for interp-tests), and runs the compiler
  7344. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7345. machine code. It runs the machine code and checks that the output is
  7346. 42.
  7347. \begin{lstlisting}
  7348. (define (compiler-tests name passes test-family test-nums) ...)
  7349. \end{lstlisting}
  7350. The compile-file function takes a description of the compiler passes
  7351. (see the comment for \key{interp-tests}) and returns a function that,
  7352. given a program file name (a string ending in \key{.scm}), applies all
  7353. of the passes and writes the output to a file whose name is the same
  7354. as the program file name but with \key{.scm} replaced with \key{.s}.
  7355. \begin{lstlisting}
  7356. (define (compile-file passes)
  7357. (lambda (prog-file-name) ...))
  7358. \end{lstlisting}
  7359. \section{x86 Instruction Set Quick-Reference}
  7360. \label{sec:x86-quick-reference}
  7361. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7362. do. We write $A \to B$ to mean that the value of $A$ is written into
  7363. location $B$. Address offsets are given in bytes. The instruction
  7364. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7365. registers (such as $\%rax$), or memory references (such as
  7366. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7367. reference per instruction. Other operands must be immediates or
  7368. registers.
  7369. \begin{table}[tbp]
  7370. \centering
  7371. \begin{tabular}{l|l}
  7372. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7373. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7374. \texttt{negq} $A$ & $- A \to A$ \\
  7375. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7376. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7377. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7378. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7379. \texttt{retq} & Pops the return address and jumps to it \\
  7380. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7381. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7382. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7383. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7384. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7385. matches the condition code of the instruction, otherwise go to the
  7386. next instructions. The condition codes are \key{e} for ``equal'',
  7387. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7388. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7389. \texttt{jl} $L$ & \\
  7390. \texttt{jle} $L$ & \\
  7391. \texttt{jg} $L$ & \\
  7392. \texttt{jge} $L$ & \\
  7393. \texttt{jmp} $L$ & Jump to label $L$ \\
  7394. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7395. \texttt{movzbq} $A$, $B$ &
  7396. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7397. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7398. and the extra bytes of $B$ are set to zero.} \\
  7399. & \\
  7400. & \\
  7401. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7402. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7403. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7404. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7405. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7406. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7407. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7408. description of the condition codes. $A$ must be a single byte register
  7409. (e.g., \texttt{al} or \texttt{cl}).} \\
  7410. \texttt{setl} $A$ & \\
  7411. \texttt{setle} $A$ & \\
  7412. \texttt{setg} $A$ & \\
  7413. \texttt{setge} $A$ &
  7414. \end{tabular}
  7415. \vspace{5pt}
  7416. \caption{Quick-reference for the x86 instructions used in this book.}
  7417. \label{tab:x86-instr}
  7418. \end{table}
  7419. \bibliographystyle{plainnat}
  7420. \bibliography{all}
  7421. \end{document}
  7422. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7423. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7424. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7425. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7426. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7427. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7428. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7429. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7430. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7431. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7432. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7433. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7434. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7435. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7436. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7437. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7438. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7439. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7440. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7441. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7442. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7443. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7444. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7445. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7446. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7447. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7448. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7449. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7450. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7451. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7452. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7453. % LocalWords: struct symtab