book.tex 547 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \definecolor{lightgray}{gray}{1}
  17. \newcommand{\black}[1]{{\color{black} #1}}
  18. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  19. \newcommand{\gray}[1]{{\color{gray} #1}}
  20. \def\racketEd{0}
  21. \def\pythonEd{1}
  22. \def\edition{1}
  23. % material that is specific to the Racket edition of the book
  24. \newcommand{\racket}[1]{{\if\edition\racketEd\color{olive}{#1}\fi}}
  25. % would like a command for: \if\edition\racketEd\color{olive}
  26. % and : \fi\color{black}
  27. % material that is specific to the Python edition of the book
  28. \newcommand{\python}[1]{{\if\edition\pythonEd\color{purple}{#1}\fi}}
  29. %% For multiple indices:
  30. \usepackage{multind}
  31. \makeindex{subject}
  32. \makeindex{authors}
  33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  34. \lstset{%
  35. language=Lisp,
  36. basicstyle=\ttfamily\small,
  37. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  38. deletekeywords={read,mapping,vector},
  39. escapechar=|,
  40. columns=flexible,
  41. moredelim=[is][\color{red}]{~}{~},
  42. showstringspaces=false
  43. }
  44. %%% Any shortcut own defined macros place here
  45. %% sample of author macro:
  46. \input{defs}
  47. \newtheorem{exercise}[theorem]{Exercise}
  48. % Adjusted settings
  49. \setlength{\columnsep}{4pt}
  50. %% \begingroup
  51. %% \setlength{\intextsep}{0pt}%
  52. %% \setlength{\columnsep}{0pt}%
  53. %% \begin{wrapfigure}{r}{0.5\textwidth}
  54. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  55. %% \caption{Basic layout}
  56. %% \end{wrapfigure}
  57. %% \lipsum[1]
  58. %% \endgroup
  59. \newbox\oiintbox
  60. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  61. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  62. \def\oiint{\copy\oiintbox}
  63. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  64. %\usepackage{showframe}
  65. \def\ShowFrameLinethickness{0.125pt}
  66. \addbibresource{book.bib}
  67. \begin{document}
  68. \frontmatter
  69. \HalfTitle{Essentials of Compilation}
  70. \halftitlepage
  71. %% \begin{seriespage}
  72. %% \seriestitle{Industrial Economics}
  73. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  74. %% \title{Engineering and Economics}
  75. %% \author{Samuel Endgrove}
  76. %% \title{Structural Economics: From Beginning to End}
  77. %% \author{Guang Xi}
  78. %% \end{seriespage}
  79. \Title{Essentials of Compilation}
  80. \Booksubtitle{The Incremental, Nano-Pass Approach}
  81. \edition{First Edition}
  82. \BookAuthor{Jeremy G. Siek}
  83. \imprint{The MIT Press\\
  84. Cambridge, Massachusetts\\
  85. London, England}
  86. \begin{copyrightpage}
  87. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  88. or personal downloading under the
  89. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  90. license.
  91. Copyright in this monograph has been licensed exclusively to The MIT
  92. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  93. version to the public in 2022. All inquiries regarding rights should
  94. be addressed to The MIT Press, Rights and Permissions Department.
  95. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  96. %% All rights reserved. No part of this book may be reproduced in any
  97. %% form by any electronic or mechanical means (including photocopying,
  98. %% recording, or information storage and retrieval) without permission in
  99. %% writing from the publisher.
  100. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  101. %% United States of America.
  102. %% Library of Congress Cataloging-in-Publication Data is available.
  103. %% ISBN:
  104. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  105. \end{copyrightpage}
  106. \dedication{This book is dedicated to the programming language wonks
  107. at Indiana University.}
  108. %% \begin{epigraphpage}
  109. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  110. %% \textit{Book Name if any}}
  111. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  112. %% \end{epigraphpage}
  113. \tableofcontents
  114. \listoffigures
  115. \listoftables
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \chapter*{Preface}
  118. \addcontentsline{toc}{fmbm}{Preface}
  119. There is a magical moment when a programmer presses the ``run'' button
  120. and the software begins to execute. Somehow a program written in a
  121. high-level language is running on a computer that is only capable of
  122. shuffling bits. Here we reveal the wizardry that makes that moment
  123. possible. Beginning with the groundbreaking work of Backus and
  124. colleagues in the 1950s, computer scientists discovered techniques for
  125. constructing programs, called \emph{compilers}, that automatically
  126. translate high-level programs into machine code.
  127. We take you on a journey by constructing your own compiler for a small
  128. but powerful language. Along the way we explain the essential
  129. concepts, algorithms, and data structures that underlie compilers. We
  130. develop your understanding of how programs are mapped onto computer
  131. hardware, which is helpful when reasoning about properties at the
  132. junction between hardware and software such as execution time,
  133. software errors, and security vulnerabilities. For those interested
  134. in pursuing compiler construction, our goal is to provide a
  135. stepping-stone to advanced topics such as just-in-time compilation,
  136. program analysis, and program optimization. For those interested in
  137. designing and implementing programming languages, we connect
  138. language design choices to their impact on the compiler and the generated
  139. code.
  140. A compiler is typically organized as a sequence of stages that
  141. progressively translates a program to code that runs on hardware. We
  142. take this approach to the extreme by partitioning our compiler into a
  143. large number of \emph{nanopasses}, each of which performs a single
  144. task. This allows us to test the output of each pass in isolation, and
  145. furthermore, allows us to focus our attention making the compiler far
  146. easier to understand.
  147. %% [TODO: easier to understand/debug for those maintaining the compiler,
  148. %% proving correctness]
  149. The most familiar approach to describing compilers is with one pass
  150. per chapter. The problem with that is it obfuscates how language
  151. features motivate design choices in a compiler. We take an
  152. \emph{incremental} approach in which we build a complete compiler in
  153. each chapter, starting with arithmetic and variables and add new
  154. features in subsequent chapters.
  155. Our choice of language features is designed to elicit the fundamental
  156. concepts and algorithms used in compilers.
  157. \begin{itemize}
  158. \item We begin with integer arithmetic and local variables in
  159. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  160. the fundamental tools of compiler construction: \emph{abstract
  161. syntax trees} and \emph{recursive functions}.
  162. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  163. \emph{graph coloring} to assign variables to machine registers.
  164. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  165. an elegant recursive algorithm for mapping expressions to
  166. \emph{control-flow graphs}.
  167. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  168. \emph{garbage collection}.
  169. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  170. but lack lexical scoping, similar to the C programming
  171. language~\citep{Kernighan:1988nx} except that we generate efficient
  172. tail calls. The reader learns about the procedure call stack,
  173. \emph{calling conventions}, and their interaction with register
  174. allocation and garbage collection.
  175. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  176. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  177. \emph{closure conversion}, in which lambdas are translated into a
  178. combination of functions and tuples.
  179. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  180. point the input languages are statically typed. The reader extends
  181. the statically typed language with an \code{Any} type which serves
  182. as a target for compiling the dynamically typed language.
  183. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  184. programming languages with the addition of loops and mutable
  185. variables. These additions elicit the need for \emph{dataflow
  186. analysis} in the register allocator.
  187. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  188. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  189. in which different regions of a program may be static or dynamically
  190. typed. The reader implements runtime support for \emph{proxies} that
  191. allow values to safely move between regions.
  192. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  193. leveraging the \code{Any} type and type casts developed in Chapters
  194. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  195. \end{itemize}
  196. There are many language features that we do not include. Our choices
  197. weigh the incidental complexity of a feature against the fundamental
  198. concepts that it exposes. For example, we include tuples and not
  199. records because they both elicit the study of heap allocation and
  200. garbage collection but records come with more incidental complexity.
  201. Since 2016 this book has served as the textbook for the compiler
  202. course at Indiana University, a 16-week course for upper-level
  203. undergraduates and first-year graduate students.
  204. %
  205. Prior to this course, students learn to program in both imperative and
  206. functional languages, study data structures and algorithms, and take
  207. discrete mathematics.
  208. %
  209. At the beginning of the course, students form groups of 2-4 people.
  210. The groups complete one chapter every two weeks, starting with
  211. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  212. chapters include a challenge problem that we assign to the graduate
  213. students. The last two weeks of the course involve a final project in
  214. which students design and implement a compiler extension of their
  215. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  216. \ref{ch:Rpoly} can be used in support of these projects or they can
  217. replace some of the earlier chapters. For example, a course with an
  218. emphasis on statically-typed imperative languages would skip
  219. Chapter~\ref{ch:Rdyn} in favor of
  220. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  221. the dependencies between chapters.
  222. This book has also been used in compiler courses at California
  223. Polytechnic State University, Portland State University, Rose–Hulman
  224. Institute of Technology, University of Massachusetts Lowell, and the
  225. University of Vermont.
  226. \begin{figure}[tp]
  227. \begin{tikzpicture}[baseline=(current bounding box.center)]
  228. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  229. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  230. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  231. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  232. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  233. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  234. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  235. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  236. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  237. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  238. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  239. \path[->] (C1) edge [above] node {} (C2);
  240. \path[->] (C2) edge [above] node {} (C3);
  241. \path[->] (C3) edge [above] node {} (C4);
  242. \path[->] (C4) edge [above] node {} (C5);
  243. \path[->] (C5) edge [above] node {} (C6);
  244. \path[->] (C6) edge [above] node {} (C7);
  245. \path[->] (C4) edge [above] node {} (C8);
  246. \path[->] (C4) edge [above] node {} (C9);
  247. \path[->] (C8) edge [above] node {} (C10);
  248. \path[->] (C10) edge [above] node {} (C11);
  249. \end{tikzpicture}
  250. \caption{Diagram of chapter dependencies.}
  251. \label{fig:chapter-dependences}
  252. \end{figure}
  253. \racket{
  254. We use the \href{https://racket-lang.org/}{Racket} language both for
  255. the implementation of the compiler and for the input language, so the
  256. reader should be proficient with Racket or Scheme. There are many
  257. excellent resources for learning Scheme and
  258. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  259. }
  260. \python{
  261. This edition of the book uses the \href{https://www.python.org/}{Python}
  262. both for the implementation of the compiler and for the input language, so the
  263. reader should be proficient with Python. There are many
  264. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  265. }
  266. The support code for this book is in the \code{github} repository at
  267. the following URL:
  268. \begin{center}\small
  269. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  270. \end{center}
  271. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  272. is helpful but not necessary for the reader to have taken a computer
  273. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  274. of x86-64 assembly language that are needed.
  275. %
  276. We follow the System V calling
  277. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  278. that we generate works with the runtime system (written in C) when it
  279. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  280. operating systems.
  281. %
  282. On the Windows operating system, \code{gcc} uses the Microsoft x64
  283. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  284. assembly code that we generate does \emph{not} work with the runtime
  285. system on Windows. One workaround is to use a virtual machine with
  286. Linux as the guest operating system.
  287. \section*{Acknowledgments}
  288. The tradition of compiler construction at Indiana University goes back
  289. to research and courses on programming languages by Daniel Friedman in
  290. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  291. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  292. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  293. the compiler course and continued the development of Chez Scheme.
  294. %
  295. The compiler course evolved to incorporate novel pedagogical ideas
  296. while also including elements of efficient real-world compilers. One
  297. of Friedman's ideas was to split the compiler into many small
  298. passes. Another idea, called ``the game'', was to test the code
  299. generated by each pass using interpreters.
  300. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  301. developed infrastructure to support this approach and evolved the
  302. course to use even smaller
  303. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  304. design decisions in this book are inspired by the assignment
  305. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  306. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  307. organization of the course made it difficult for students to
  308. understand the rationale for the compiler design. Ghuloum proposed the
  309. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  310. on.
  311. We thank the many students who served as teaching assistants for the
  312. compiler course at IU and made suggestions for improving the book
  313. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  314. thank Andre Kuhlenschmidt for his work on the garbage collector,
  315. Michael Vollmer for his work on efficient tail calls, and Michael
  316. Vitousek for his help running the first offering of the incremental
  317. compiler course at IU.
  318. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  319. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  320. for teaching courses based on drafts of this book and for their
  321. invaluable feedback.
  322. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  323. course in the early 2000's and especially for finding the bug that
  324. sent our garbage collector on a wild goose chase!
  325. \mbox{}\\
  326. \noindent Jeremy G. Siek \\
  327. Bloomington, Indiana
  328. \mainmatter
  329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  330. \chapter{Preliminaries}
  331. \label{ch:trees-recur}
  332. In this chapter we review the basic tools that are needed to implement
  333. a compiler. Programs are typically input by a programmer as text,
  334. i.e., a sequence of characters. The program-as-text representation is
  335. called \emph{concrete syntax}. We use concrete syntax to concisely
  336. write down and talk about programs. Inside the compiler, we use
  337. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  338. that efficiently supports the operations that the compiler needs to
  339. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  340. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  341. from concrete syntax to abstract syntax is a process called
  342. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  343. implementation of parsing in this book.
  344. %
  345. \racket{A parser is provided in the support code for translating from
  346. concrete to abstract syntax.}
  347. %
  348. \python{We use Python's \code{ast} module to translate from concrete
  349. to abstract syntax.}
  350. ASTs can be represented in many different ways inside the compiler,
  351. depending on the programming language used to write the compiler.
  352. %
  353. \racket{We use Racket's
  354. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  355. feature to represent ASTs (Section~\ref{sec:ast}).}
  356. %
  357. \python{We use Python classes and objects to represent ASTs, especially the
  358. classes defined in the standard \code{ast} module for the Python
  359. source language.}
  360. %
  361. We use grammars to define the abstract syntax of programming languages
  362. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  363. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  364. recursive functions to construct and deconstruct ASTs
  365. (Section~\ref{sec:recursion}). This chapter provides an brief
  366. introduction to these ideas.
  367. \racket{\index{subject}{struct}}
  368. \python{\index{subject}{class}\index{subject}{object}}
  369. \section{Abstract Syntax Trees}
  370. \label{sec:ast}
  371. Compilers use abstract syntax trees to represent programs because they
  372. often need to ask questions like: for a given part of a program, what
  373. kind of language feature is it? What are its sub-parts? Consider the
  374. program on the left and its AST on the right. This program is an
  375. addition operation and it has two sub-parts, a read operation and a
  376. negation. The negation has another sub-part, the integer constant
  377. \code{8}. By using a tree to represent the program, we can easily
  378. follow the links to go from one part of a program to its sub-parts.
  379. \begin{center}
  380. \begin{minipage}{0.4\textwidth}
  381. \if\edition\racketEd
  382. \begin{lstlisting}
  383. (+ (read) (- 8))
  384. \end{lstlisting}
  385. \fi
  386. \if\edition\pythonEd
  387. \begin{lstlisting}
  388. input_int() + -8
  389. \end{lstlisting}
  390. \fi
  391. \end{minipage}
  392. \begin{minipage}{0.4\textwidth}
  393. \begin{equation}
  394. \begin{tikzpicture}
  395. \node[draw] (plus) at (0 , 0) {\key{+}};
  396. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  397. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  398. \node[draw] (8) at (1 , -3) {\key{8}};
  399. \draw[->] (plus) to (read);
  400. \draw[->] (plus) to (minus);
  401. \draw[->] (minus) to (8);
  402. \end{tikzpicture}
  403. \label{eq:arith-prog}
  404. \end{equation}
  405. \end{minipage}
  406. \end{center}
  407. We use the standard terminology for trees to describe ASTs: each
  408. rectangle above is called a \emph{node}. The arrows connect a node to its
  409. \emph{children} (which are also nodes). The top-most node is the
  410. \emph{root}. Every node except for the root has a \emph{parent} (the
  411. node it is the child of). If a node has no children, it is a
  412. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  413. \index{subject}{node}
  414. \index{subject}{children}
  415. \index{subject}{root}
  416. \index{subject}{parent}
  417. \index{subject}{leaf}
  418. \index{subject}{internal node}
  419. %% Recall that an \emph{symbolic expression} (S-expression) is either
  420. %% \begin{enumerate}
  421. %% \item an atom, or
  422. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  423. %% where $e_1$ and $e_2$ are each an S-expression.
  424. %% \end{enumerate}
  425. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  426. %% null value \code{'()}, etc. We can create an S-expression in Racket
  427. %% simply by writing a backquote (called a quasi-quote in Racket)
  428. %% followed by the textual representation of the S-expression. It is
  429. %% quite common to use S-expressions to represent a list, such as $a, b
  430. %% ,c$ in the following way:
  431. %% \begin{lstlisting}
  432. %% `(a . (b . (c . ())))
  433. %% \end{lstlisting}
  434. %% Each element of the list is in the first slot of a pair, and the
  435. %% second slot is either the rest of the list or the null value, to mark
  436. %% the end of the list. Such lists are so common that Racket provides
  437. %% special notation for them that removes the need for the periods
  438. %% and so many parenthesis:
  439. %% \begin{lstlisting}
  440. %% `(a b c)
  441. %% \end{lstlisting}
  442. %% The following expression creates an S-expression that represents AST
  443. %% \eqref{eq:arith-prog}.
  444. %% \begin{lstlisting}
  445. %% `(+ (read) (- 8))
  446. %% \end{lstlisting}
  447. %% When using S-expressions to represent ASTs, the convention is to
  448. %% represent each AST node as a list and to put the operation symbol at
  449. %% the front of the list. The rest of the list contains the children. So
  450. %% in the above case, the root AST node has operation \code{`+} and its
  451. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  452. %% diagram \eqref{eq:arith-prog}.
  453. %% To build larger S-expressions one often needs to splice together
  454. %% several smaller S-expressions. Racket provides the comma operator to
  455. %% splice an S-expression into a larger one. For example, instead of
  456. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  457. %% we could have first created an S-expression for AST
  458. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  459. %% S-expression.
  460. %% \begin{lstlisting}
  461. %% (define ast1.4 `(- 8))
  462. %% (define ast1_1 `(+ (read) ,ast1.4))
  463. %% \end{lstlisting}
  464. %% In general, the Racket expression that follows the comma (splice)
  465. %% can be any expression that produces an S-expression.
  466. {\if\edition\racketEd\color{olive}
  467. We define a Racket \code{struct} for each kind of node. For this
  468. chapter we require just two kinds of nodes: one for integer constants
  469. and one for primitive operations. The following is the \code{struct}
  470. definition for integer constants.
  471. \begin{lstlisting}
  472. (struct Int (value))
  473. \end{lstlisting}
  474. An integer node includes just one thing: the integer value.
  475. To create an AST node for the integer $8$, we write \INT{8}.
  476. \begin{lstlisting}
  477. (define eight (Int 8))
  478. \end{lstlisting}
  479. We say that the value created by \INT{8} is an
  480. \emph{instance} of the
  481. \code{Int} structure.
  482. The following is the \code{struct} definition for primitive operations.
  483. \begin{lstlisting}
  484. (struct Prim (op args))
  485. \end{lstlisting}
  486. A primitive operation node includes an operator symbol \code{op} and a
  487. list of child \code{args}. For example, to create an AST that negates
  488. the number $8$, we write \code{(Prim '- (list eight))}.
  489. \begin{lstlisting}
  490. (define neg-eight (Prim '- (list eight)))
  491. \end{lstlisting}
  492. Primitive operations may have zero or more children. The \code{read}
  493. operator has zero children:
  494. \begin{lstlisting}
  495. (define rd (Prim 'read '()))
  496. \end{lstlisting}
  497. whereas the addition operator has two children:
  498. \begin{lstlisting}
  499. (define ast1_1 (Prim '+ (list rd neg-eight)))
  500. \end{lstlisting}
  501. We have made a design choice regarding the \code{Prim} structure.
  502. Instead of using one structure for many different operations
  503. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  504. structure for each operation, as follows.
  505. \begin{lstlisting}
  506. (struct Read ())
  507. (struct Add (left right))
  508. (struct Neg (value))
  509. \end{lstlisting}
  510. The reason we choose to use just one structure is that in many parts
  511. of the compiler the code for the different primitive operators is the
  512. same, so we might as well just write that code once, which is enabled
  513. by using a single structure.
  514. \fi}
  515. {\if\edition\pythonEd\color{purple}
  516. We use a Python \code{class} for each kind of node.
  517. The following is the class definition for constants.
  518. \begin{lstlisting}
  519. class Constant:
  520. def __init__(self, value):
  521. self.value = value
  522. \end{lstlisting}
  523. An integer constant node includes just one thing: the integer value.
  524. To create an AST node for the integer $8$, we write \INT{8}.
  525. \begin{lstlisting}
  526. eight = Constant(8)
  527. \end{lstlisting}
  528. We say that the value created by \INT{8} is an
  529. \emph{instance} of the \code{Constant} class.
  530. The following is class definition for unary operators.
  531. \begin{lstlisting}
  532. class UnaryOp:
  533. def __init__(self, op, operand):
  534. self.op = op
  535. self.operand = operand
  536. \end{lstlisting}
  537. The specific operation is specified by the \code{op} parameter. For
  538. example, the class \code{USub} is for unary subtraction. (More unary
  539. operators are introduced in later chapters.) To create an AST that
  540. negates the number $8$, we write \NEG{\code{eight}}.
  541. \begin{lstlisting}
  542. neg_eight = UnaryOp(USub(), eight)
  543. \end{lstlisting}
  544. The call to the \code{input\_int} function is represented by the
  545. \code{Call} and \code{Name} classes.
  546. \begin{lstlisting}
  547. class Call:
  548. def __init__(self, func, args):
  549. self.func = func
  550. self.args = args
  551. class Name:
  552. def __init__(self, id):
  553. self.id = id
  554. \end{lstlisting}
  555. To create an AST node that calls \code{input\_int}, we write
  556. \begin{lstlisting}
  557. read = Call(Name('input_int'), [])
  558. \end{lstlisting}
  559. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  560. the \code{BinOp} class for binary operators.
  561. \begin{lstlisting}
  562. class BinOp:
  563. def __init__(self, left, op, right):
  564. self.op = op
  565. self.left = left
  566. self.right = right
  567. \end{lstlisting}
  568. Similar to \code{UnaryOp}, the specific operation is specified by the
  569. \code{op} parameter, which for now is just an instance of the
  570. \code{Add} class. So to create the AST node that adds negative eight
  571. to some user input, we write the following.
  572. \begin{lstlisting}
  573. ast1_1 = BinOp(read, Add(), neg_eight)
  574. \end{lstlisting}
  575. \fi}
  576. When compiling a program such as \eqref{eq:arith-prog}, we need to
  577. know that the operation associated with the root node is addition and
  578. we need to be able to access its two children. \racket{Racket}\python{Python}
  579. provides pattern matching to support these kinds of queries, as we see in
  580. Section~\ref{sec:pattern-matching}.
  581. In this book, we often write down the concrete syntax of a program
  582. even when we really have in mind the AST because the concrete syntax
  583. is more concise. We recommend that, in your mind, you always think of
  584. programs as abstract syntax trees.
  585. \section{Grammars}
  586. \label{sec:grammar}
  587. \index{subject}{integer}
  588. \index{subject}{literal}
  589. \index{subject}{constant}
  590. A programming language can be thought of as a \emph{set} of programs.
  591. The set is typically infinite (one can always create larger and larger
  592. programs), so one cannot simply describe a language by listing all of
  593. the programs in the language. Instead we write down a set of rules, a
  594. \emph{grammar}, for building programs. Grammars are often used to
  595. define the concrete syntax of a language, but they can also be used to
  596. describe the abstract syntax. We write our rules in a variant of
  597. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  598. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  599. As an example, we describe a small language, named \LangInt{}, that consists of
  600. integers and arithmetic operations.
  601. \index{subject}{grammar}
  602. The first grammar rule for the abstract syntax of \LangInt{} says that an
  603. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  604. \begin{equation}
  605. \Exp ::= \INT{\Int} \label{eq:arith-int}
  606. \end{equation}
  607. %
  608. Each rule has a left-hand-side and a right-hand-side.
  609. If you have an AST node that matches the
  610. right-hand-side, then you can categorize it according to the
  611. left-hand-side.
  612. %
  613. A name such as $\Exp$ that is defined by the grammar rules is a
  614. \emph{non-terminal}. \index{subject}{non-terminal}
  615. %
  616. The name $\Int$ is also a non-terminal, but instead of defining it
  617. with a grammar rule, we define it with the following explanation. An
  618. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  619. $-$ (for negative integers), such that the sequence of decimals
  620. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  621. the representation of integers using 63 bits, which simplifies several
  622. aspects of compilation. \racket{Thus, these integers corresponds to
  623. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  624. \python{In contrast, integers in Python have unlimited precision, but
  625. the techniques need to handle unlimited precision fall outside the
  626. scope of this book.}
  627. The second grammar rule is the \READOP{} operation that receives an
  628. input integer from the user of the program.
  629. \begin{equation}
  630. \Exp ::= \READ{} \label{eq:arith-read}
  631. \end{equation}
  632. The third rule says that, given an $\Exp$ node, the negation of that
  633. node is also an $\Exp$.
  634. \begin{equation}
  635. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  636. \end{equation}
  637. Symbols in typewriter font are \emph{terminal} symbols and must
  638. literally appear in the program for the rule to be applicable.
  639. \index{subject}{terminal}
  640. We can apply these rules to categorize the ASTs that are in the
  641. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  642. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  643. following AST is an $\Exp$.
  644. \begin{center}
  645. \begin{minipage}{0.5\textwidth}
  646. \NEG{\INT{\code{8}}}
  647. \end{minipage}
  648. \begin{minipage}{0.25\textwidth}
  649. \begin{equation}
  650. \begin{tikzpicture}
  651. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  652. \node[draw, circle] (8) at (0, -1.2) {$8$};
  653. \draw[->] (minus) to (8);
  654. \end{tikzpicture}
  655. \label{eq:arith-neg8}
  656. \end{equation}
  657. \end{minipage}
  658. \end{center}
  659. The next grammar rule is for addition expressions:
  660. \begin{equation}
  661. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  662. \end{equation}
  663. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  664. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  665. \eqref{eq:arith-read} and we have already categorized
  666. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  667. to show that
  668. \[
  669. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  670. \]
  671. is an $\Exp$ in the \LangInt{} language.
  672. If you have an AST for which the above rules do not apply, then the
  673. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  674. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  675. because there are no rules for the \key{-} operator with two
  676. arguments. Whenever we define a language with a grammar, the language
  677. only includes those programs that are justified by the rules.
  678. {\if\edition\pythonEd\color{purple}
  679. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  680. There is a statement for printing the value of an expression
  681. \[
  682. \Stmt{} ::= \PRINT{\Exp}
  683. \]
  684. and a statement that evaluates an expression but ignores the result.
  685. \[
  686. \Stmt{} ::= \EXPR{\Exp}
  687. \]
  688. \fi}
  689. {\if\edition\racketEd\color{olive}
  690. The last grammar rule for \LangInt{} states that there is a
  691. \code{Program} node to mark the top of the whole program:
  692. \[
  693. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  694. \]
  695. The \code{Program} structure is defined as follows
  696. \begin{lstlisting}
  697. (struct Program (info body))
  698. \end{lstlisting}
  699. where \code{body} is an expression. In later chapters, the \code{info}
  700. part will be used to store auxiliary information but for now it is
  701. just the empty list.
  702. \fi}
  703. {\if\edition\pythonEd\color{purple}
  704. The last grammar rule for \LangInt{} states that there is a
  705. \code{Module} node to mark the top of the whole program:
  706. \[
  707. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  708. \]
  709. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  710. this case, a list of statements.
  711. %
  712. The \code{Module} class is defined as follows
  713. \begin{lstlisting}
  714. class Module:
  715. def __init__(self, body):
  716. self.body = body
  717. \end{lstlisting}
  718. where \code{body} is a list of statements.
  719. \fi}
  720. It is common to have many grammar rules with the same left-hand side
  721. but different right-hand sides, such as the rules for $\Exp$ in the
  722. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  723. combine several right-hand-sides into a single rule.
  724. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  725. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  726. defined in Figure~\ref{fig:r0-concrete-syntax}.
  727. \racket{The \code{read-program} function provided in
  728. \code{utilities.rkt} of the support code reads a program in from a
  729. file (the sequence of characters in the concrete syntax of Racket)
  730. and parses it into an abstract syntax tree. See the description of
  731. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  732. details.}
  733. \python{The \code{parse} function in Python's \code{ast} module
  734. converts the concrete syntax (represented as a string) into an
  735. abstract syntax tree.}
  736. \begin{figure}[tp]
  737. \fbox{
  738. \begin{minipage}{0.96\textwidth}
  739. {\if\edition\racketEd\color{olive}
  740. \[
  741. \begin{array}{rcl}
  742. \begin{array}{rcl}
  743. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  744. \LangInt{} &::=& \Exp
  745. \end{array}
  746. \end{array}
  747. \]
  748. \fi}
  749. {\if\edition\pythonEd\color{purple}
  750. \[
  751. \begin{array}{rcl}
  752. \begin{array}{rcl}
  753. \Exp &::=& \Int \mid \key{input\_int}\LP\RP \mid \key{-}\;\Exp \mid \Exp \; \key{+} \; \Exp\\
  754. \Stmt &::=& \key{print}\LP \Exp \RP \mid \Exp\\
  755. \LangInt{} &::=& \Stmt^{*}
  756. \end{array}
  757. \end{array}
  758. \]
  759. \fi}
  760. \end{minipage}
  761. }
  762. \caption{The concrete syntax of \LangInt{}.}
  763. \label{fig:r0-concrete-syntax}
  764. \end{figure}
  765. \begin{figure}[tp]
  766. \fbox{
  767. \begin{minipage}{0.96\textwidth}
  768. {\if\edition\racketEd\color{olive}
  769. \[
  770. \begin{array}{rcl}
  771. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  772. &\mid& \ADD{\Exp}{\Exp} \\
  773. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  774. \end{array}
  775. \]
  776. \fi}
  777. {\if\edition\pythonEd\color{purple}
  778. \[
  779. \begin{array}{rcl}
  780. \Exp{} &::=& \INT{\Int} \mid \READ{} \\
  781. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  782. \Stmt{} &::=& \PRINT{\Exp} \mid \EXPR{\Exp} \\
  783. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  784. \end{array}
  785. \]
  786. \fi}
  787. \end{minipage}
  788. }
  789. \caption{The abstract syntax of \LangInt{}.}
  790. \label{fig:r0-syntax}
  791. \end{figure}
  792. \section{Pattern Matching}
  793. \label{sec:pattern-matching}
  794. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  795. the parts of an AST node. \racket{Racket}\python{Python} provides the
  796. \texttt{match} feature to access the parts of a value.
  797. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  798. \begin{center}
  799. \begin{minipage}{0.5\textwidth}
  800. {\if\edition\racketEd\color{olive}
  801. \begin{lstlisting}
  802. (match ast1_1
  803. [(Prim op (list child1 child2))
  804. (print op)])
  805. \end{lstlisting}
  806. \fi}
  807. {\if\edition\pythonEd\color{purple}
  808. \begin{lstlisting}
  809. match ast1_1:
  810. case BinOp(child1, op, child2):
  811. print(op)
  812. \end{lstlisting}
  813. \fi}
  814. \end{minipage}
  815. \end{center}
  816. {\if\edition\racketEd\color{olive}
  817. %
  818. In the above example, the \texttt{match} form checks whether the AST
  819. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  820. three pattern variables \texttt{op}, \texttt{child1}, and
  821. \texttt{child2}, and then prints out the operator. In general, a match
  822. clause consists of a \emph{pattern} and a
  823. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  824. to be either a pattern variable, a structure name followed by a
  825. pattern for each of the structure's arguments, or an S-expression
  826. (symbols, lists, etc.). (See Chapter 12 of The Racket
  827. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  828. and Chapter 9 of The Racket
  829. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  830. for a complete description of \code{match}.)
  831. %
  832. The body of a match clause may contain arbitrary Racket code. The
  833. pattern variables can be used in the scope of the body, such as
  834. \code{op} in \code{(print op)}.
  835. %
  836. \fi}
  837. %
  838. %
  839. {\if\edition\pythonEd\color{purple}
  840. %
  841. In the above example, the \texttt{match} form checks whether the AST
  842. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  843. three pattern variables \texttt{child1}, \texttt{op}, and
  844. \texttt{child2}, and then prints out the operator. In general, each
  845. \code{case} consists of a \emph{pattern} and a
  846. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  847. to be either a pattern variable, a class name followed by a pattern
  848. for each of its constructor's arguments, or other literals such as
  849. strings, lists, etc.
  850. %
  851. The body of each \code{case} may contain arbitrary Python code. The
  852. pattern variables can be used in the body, such as \code{op} in
  853. \code{print(op)}.
  854. %
  855. \fi}
  856. A \code{match} form may contain several clauses, as in the following
  857. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  858. the AST. The \code{match} proceeds through the clauses in order,
  859. checking whether the pattern can match the input AST. The body of the
  860. first clause that matches is executed. The output of \code{leaf} for
  861. several ASTs is shown on the right.
  862. \begin{center}
  863. \begin{minipage}{0.6\textwidth}
  864. {\if\edition\racketEd\color{olive}
  865. \begin{lstlisting}
  866. (define (leaf arith)
  867. (match arith
  868. [(Int n) #t]
  869. [(Prim 'read '()) #t]
  870. [(Prim '- (list e1)) #f]
  871. [(Prim '+ (list e1 e2)) #f]))
  872. (leaf (Prim 'read '()))
  873. (leaf (Prim '- (list (Int 8))))
  874. (leaf (Int 8))
  875. \end{lstlisting}
  876. \fi}
  877. {\if\edition\pythonEd\color{purple}
  878. \begin{lstlisting}
  879. def leaf(arith):
  880. match arith:
  881. case Constant(n):
  882. return True
  883. case Call(Name('input_int'), []):
  884. return True
  885. case UnaryOp(USub(), e1):
  886. return False
  887. case BinOp(e1, Add(), e2):
  888. return False
  889. case _:
  890. return False
  891. print(leaf(Call(Name('input_int'), [])))
  892. print(leaf(UnaryOp(USub(), eight)))
  893. print(leaf(Constant(8)))
  894. \end{lstlisting}
  895. \fi}
  896. \end{minipage}
  897. \vrule
  898. \begin{minipage}{0.25\textwidth}
  899. {\if\edition\racketEd\color{olive}
  900. \begin{lstlisting}
  901. #t
  902. #f
  903. #t
  904. \end{lstlisting}
  905. \fi}
  906. {\if\edition\pythonEd\color{purple}
  907. \begin{lstlisting}
  908. True
  909. False
  910. True
  911. \end{lstlisting}
  912. \fi}
  913. \end{minipage}
  914. \end{center}
  915. When writing a \code{match}, we refer to the grammar definition to
  916. identify which non-terminal we are expecting to match against, then we
  917. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  918. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  919. corresponding right-hand side of a grammar rule. For the \code{match}
  920. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  921. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  922. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  923. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  924. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  925. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  926. patterns, replace non-terminals such as $\Exp$ with pattern variables
  927. of your choice (e.g. \code{e1} and \code{e2}).
  928. \section{Recursive Functions}
  929. \label{sec:recursion}
  930. \index{subject}{recursive function}
  931. Programs are inherently recursive. For example, an \LangInt{}
  932. expression is often made of smaller expressions. Thus, the natural way
  933. to process an entire program is with a recursive function. As a first
  934. example of such a recursive function, we define the function
  935. \code{exp} in Figure~\ref{fig:exp-predicate}, which takes an
  936. arbitrary value and determines whether or not it is an \LangInt{}
  937. expression.
  938. %
  939. We say that a function is defined by \emph{structural recursion} when
  940. it is defined using a sequence of match \racket{clauses}\python{cases}
  941. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  942. makes a recursive call on each
  943. child node.\footnote{This principle of structuring code according to
  944. the data definition is advocated in the book \emph{How to Design
  945. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  946. \python{We define a second function, named \code{stmt}, that recognizes
  947. whether a value is a \LangInt{} statement.}
  948. \python{Finally, }
  949. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Rint}, which
  950. determines whether an AST is a program in \LangInt{}. In general we can
  951. expect to write one recursive function to handle each non-terminal in
  952. a grammar.\index{subject}{structural recursion}
  953. \begin{figure}[tp]
  954. {\if\edition\racketEd\color{olive}
  955. \begin{minipage}{0.7\textwidth}
  956. \begin{lstlisting}
  957. (define (exp ast)
  958. (match ast
  959. [(Int n) #t]
  960. [(Prim 'read '()) #t]
  961. [(Prim '- (list e)) (exp e)]
  962. [(Prim '+ (list e1 e2))
  963. (and (exp e1) (exp e2))]
  964. [else #f]))
  965. (define (Rint ast)
  966. (match ast
  967. [(Program '() e) (exp e)]
  968. [else #f]))
  969. (Rint (Program '() ast1_1)
  970. (Rint (Program '()
  971. (Prim '- (list (Prim 'read '())
  972. (Prim '+ (list (Num 8)))))))
  973. \end{lstlisting}
  974. \end{minipage}
  975. \vrule
  976. \begin{minipage}{0.25\textwidth}
  977. \begin{lstlisting}
  978. #t
  979. #f
  980. \end{lstlisting}
  981. \end{minipage}
  982. \fi}
  983. {\if\edition\pythonEd\color{purple}
  984. \begin{minipage}{0.7\textwidth}
  985. \begin{lstlisting}
  986. def exp(e):
  987. match e:
  988. case Constant(n):
  989. return True
  990. case Call(Name('input_int'), []):
  991. return True
  992. case UnaryOp(USub(), e1):
  993. return exp(e1)
  994. case BinOp(e1, Add(), e2):
  995. return exp(e1) and exp(e2)
  996. case _:
  997. return False
  998. def stmt(s):
  999. match s:
  1000. case Call(Name('print'), [e]):
  1001. return exp(e)
  1002. case Expr(e):
  1003. return exp(e)
  1004. case _:
  1005. return False
  1006. def Rint(p):
  1007. match p:
  1008. case Module(body):
  1009. return all([stmt(s) for s in body])
  1010. case _:
  1011. return False
  1012. print(Rint(Module([Expr(ast1_1)])))
  1013. print(Rint(Module([Expr(BinOp(read, Sub(),
  1014. UnaryOp(Add(), Constant(8))))])))
  1015. \end{lstlisting}
  1016. \end{minipage}
  1017. \vrule
  1018. \begin{minipage}{0.25\textwidth}
  1019. \begin{lstlisting}
  1020. True
  1021. False
  1022. \end{lstlisting}
  1023. \end{minipage}
  1024. \fi}
  1025. \caption{Example of recursive functions for \LangInt{}. These functions
  1026. recognize whether an AST is in \LangInt{}.}
  1027. \label{fig:exp-predicate}
  1028. \end{figure}
  1029. %% You may be tempted to merge the two functions into one, like this:
  1030. %% \begin{center}
  1031. %% \begin{minipage}{0.5\textwidth}
  1032. %% \begin{lstlisting}
  1033. %% (define (Rint ast)
  1034. %% (match ast
  1035. %% [(Int n) #t]
  1036. %% [(Prim 'read '()) #t]
  1037. %% [(Prim '- (list e)) (Rint e)]
  1038. %% [(Prim '+ (list e1 e2)) (and (Rint e1) (Rint e2))]
  1039. %% [(Program '() e) (Rint e)]
  1040. %% [else #f]))
  1041. %% \end{lstlisting}
  1042. %% \end{minipage}
  1043. %% \end{center}
  1044. %% %
  1045. %% Sometimes such a trick will save a few lines of code, especially when
  1046. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1047. %% \emph{not} recommended because it can get you into trouble.
  1048. %% %
  1049. %% For example, the above function is subtly wrong:
  1050. %% \lstinline{(Rint (Program '() (Program '() (Int 3))))}
  1051. %% returns true when it should return false.
  1052. \section{Interpreters}
  1053. \label{sec:interp_Rint}
  1054. \index{subject}{interpreter}
  1055. The behavior of a program is defined by the specification of the
  1056. programming language.
  1057. %
  1058. \racket{For example, the Scheme language is defined in the report by
  1059. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1060. reference manual~\citep{plt-tr}.}
  1061. %
  1062. \python{For example, the Python language is defined in the Python
  1063. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1064. %
  1065. In this book we use interpreters
  1066. to specify each language that we consider. An interpreter that is
  1067. designated as the definition of a language is called a
  1068. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1069. \index{subject}{definitional interpreter} We warm up by creating a
  1070. definitional interpreter for the \LangInt{} language, which serves as
  1071. a second example of structural recursion. The \texttt{interp\_Rint}
  1072. function is defined in Figure~\ref{fig:interp_Rint}. The body of the
  1073. function is a match on the input program followed by a call to the
  1074. \lstinline{interp_exp} helper function, which in turn has one match
  1075. clause per grammar rule for \LangInt{} expressions.
  1076. \begin{figure}[tp]
  1077. {\if\edition\racketEd\color{olive}
  1078. \begin{lstlisting}
  1079. (define (interp_exp e)
  1080. (match e
  1081. [(Int n) n]
  1082. [(Prim 'read '())
  1083. (define r (read))
  1084. (cond [(fixnum? r) r]
  1085. [else (error 'interp_exp "read expected an integer" r)])]
  1086. [(Prim '- (list e))
  1087. (define v (interp_exp e))
  1088. (fx- 0 v)]
  1089. [(Prim '+ (list e1 e2))
  1090. (define v1 (interp_exp e1))
  1091. (define v2 (interp_exp e2))
  1092. (fx+ v1 v2)]))
  1093. (define (interp_Rint p)
  1094. (match p
  1095. [(Program '() e) (interp_exp e)]))
  1096. \end{lstlisting}
  1097. \fi}
  1098. {\if\edition\pythonEd\color{purple}
  1099. \begin{lstlisting}
  1100. def interp_exp(e):
  1101. match e:
  1102. case BinOp(left, Add(), right):
  1103. l = interp_exp(left)
  1104. r = interp_exp(right)
  1105. return l + r
  1106. case UnaryOp(USub(), v):
  1107. return - interp_exp(v)
  1108. case Constant(value):
  1109. return value
  1110. case Call(Name('input_int'), []):
  1111. return int(input())
  1112. def interp_stmt(s):
  1113. match s:
  1114. case Expr(Call(Name('print'), [arg])):
  1115. print(interp_exp(arg))
  1116. case Expr(value):
  1117. interp_exp(value)
  1118. def interp_Pint(p):
  1119. match p:
  1120. case Module(body):
  1121. for s in body:
  1122. interp_stmt(s)
  1123. \end{lstlisting}
  1124. \fi}
  1125. \caption{Interpreter for the \LangInt{} language.}
  1126. \label{fig:interp_Rint}
  1127. \end{figure}
  1128. Let us consider the result of interpreting a few \LangInt{} programs. The
  1129. following program adds two integers.
  1130. {\if\edition\racketEd\color{olive}
  1131. \begin{lstlisting}
  1132. (+ 10 32)
  1133. \end{lstlisting}
  1134. \fi}
  1135. {\if\edition\pythonEd\color{purple}
  1136. \begin{lstlisting}
  1137. print(10 + 32)
  1138. \end{lstlisting}
  1139. \fi}
  1140. The result is \key{42}, the answer to life, the universe, and
  1141. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1142. Galaxy} by Douglas Adams.}.
  1143. %
  1144. We wrote the above program in concrete syntax whereas the parsed
  1145. abstract syntax is:
  1146. {\if\edition\racketEd\color{olive}
  1147. \begin{lstlisting}
  1148. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1149. \end{lstlisting}
  1150. \fi}
  1151. {\if\edition\pythonEd\color{purple}
  1152. \begin{lstlisting}
  1153. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1154. \end{lstlisting}
  1155. \fi}
  1156. The next example demonstrates that expressions may be nested within
  1157. each other, in this case nesting several additions and negations.
  1158. {\if\edition\racketEd\color{olive}
  1159. \begin{lstlisting}
  1160. (+ 10 (- (+ 12 20)))
  1161. \end{lstlisting}
  1162. \fi}
  1163. {\if\edition\pythonEd\color{purple}
  1164. \begin{lstlisting}
  1165. print(10 + -(12 + 20))
  1166. \end{lstlisting}
  1167. \fi}
  1168. What is the result of the above program?
  1169. {\if\edition\racketEd\color{olive}
  1170. As mentioned previously, the \LangInt{} language does not support
  1171. arbitrarily-large integers, but only $63$-bit integers, so we
  1172. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1173. in Racket.
  1174. Suppose
  1175. \[
  1176. n = 999999999999999999
  1177. \]
  1178. which indeed fits in $63$-bits. What happens when we run the
  1179. following program in our interpreter?
  1180. \begin{lstlisting}
  1181. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1182. \end{lstlisting}
  1183. It produces an error:
  1184. \begin{lstlisting}
  1185. fx+: result is not a fixnum
  1186. \end{lstlisting}
  1187. We establish the convention that if running the definitional
  1188. interpreter on a program produces an error then the meaning of that
  1189. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1190. error is a \code{trapped-error}. A compiler for the language is under
  1191. no obligations regarding programs with unspecified behavior; it does
  1192. not have to produce an executable, and if it does, that executable can
  1193. do anything. On the other hand, if the error is a
  1194. \code{trapped-error}, then the compiler must produce an executable and
  1195. it is required to report that an error occurred. To signal an error,
  1196. exit with a return code of \code{255}. The interpreters in chapters
  1197. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1198. \code{trapped-error}.
  1199. \fi}
  1200. % TODO: how to deal with too-large integers in the Python interpreter?
  1201. %% This convention applies to the languages defined in this
  1202. %% book, as a way to simplify the student's task of implementing them,
  1203. %% but this convention is not applicable to all programming languages.
  1204. %%
  1205. Moving on to the last feature of the \LangInt{} language, the
  1206. \READOP{} operation prompts the user of the program for an integer.
  1207. Recall that program \eqref{eq:arith-prog} requests an integer input
  1208. and then subtracts \code{8}. So if we run
  1209. {\if\edition\racketEd\color{olive}
  1210. \begin{lstlisting}
  1211. (interp_Rint (Program '() ast1_1))
  1212. \end{lstlisting}
  1213. \fi}
  1214. {\if\edition\pythonEd\color{purple}
  1215. \begin{lstlisting}
  1216. interp_Pint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1217. \end{lstlisting}
  1218. \fi}
  1219. \noindent and if the input is \code{50}, the result is \code{42}.
  1220. We include the \READOP{} operation in \LangInt{} so a clever student
  1221. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1222. during compilation to obtain the output and then generates the trivial
  1223. code to produce the output.\footnote{Yes, a clever student did this in the
  1224. first instance of this course!}
  1225. The job of a compiler is to translate a program in one language into a
  1226. program in another language so that the output program behaves the
  1227. same way as the input program does. This idea is depicted in the
  1228. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1229. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1230. Given a compiler that translates from language $\mathcal{L}_1$ to
  1231. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1232. compiler must translate it into some program $P_2$ such that
  1233. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1234. same input $i$ yields the same output $o$.
  1235. \begin{equation} \label{eq:compile-correct}
  1236. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1237. \node (p1) at (0, 0) {$P_1$};
  1238. \node (p2) at (3, 0) {$P_2$};
  1239. \node (o) at (3, -2.5) {$o$};
  1240. \path[->] (p1) edge [above] node {compile} (p2);
  1241. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1242. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1243. \end{tikzpicture}
  1244. \end{equation}
  1245. In the next section we see our first example of a compiler.
  1246. \section{Example Compiler: a Partial Evaluator}
  1247. \label{sec:partial-evaluation}
  1248. In this section we consider a compiler that translates \LangInt{} programs
  1249. into \LangInt{} programs that may be more efficient, that is, this compiler
  1250. is an optimizer. This optimizer eagerly computes the parts of the
  1251. program that do not depend on any inputs, a process known as
  1252. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1253. \index{subject}{partial evaluation}
  1254. For example, given the following program
  1255. \begin{lstlisting}
  1256. (+ (read) (- (+ 5 3)))
  1257. \end{lstlisting}
  1258. our compiler will translate it into the program
  1259. \begin{lstlisting}
  1260. (+ (read) -8)
  1261. \end{lstlisting}
  1262. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1263. evaluator for the \LangInt{} language. The output of the partial evaluator
  1264. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1265. recursion over $\Exp$ is captured in the \code{pe-exp} function
  1266. whereas the code for partially evaluating the negation and addition
  1267. operations is factored into two separate helper functions:
  1268. \code{pe-neg} and \code{pe-add}. The input to these helper
  1269. functions is the output of partially evaluating the children.
  1270. \begin{figure}[tp]
  1271. \begin{lstlisting}
  1272. (define (pe-neg r)
  1273. (match r
  1274. [(Int n) (Int (fx- 0 n))]
  1275. [else (Prim '- (list r))]))
  1276. (define (pe-add r1 r2)
  1277. (match* (r1 r2)
  1278. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1279. [(_ _) (Prim '+ (list r1 r2))]))
  1280. (define (pe-exp e)
  1281. (match e
  1282. [(Int n) (Int n)]
  1283. [(Prim 'read '()) (Prim 'read '())]
  1284. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  1285. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  1286. (define (pe-Rint p)
  1287. (match p
  1288. [(Program '() e) (Program '() (pe-exp e))]))
  1289. \end{lstlisting}
  1290. \caption{A partial evaluator for \LangInt{}.}
  1291. \label{fig:pe-arith}
  1292. \end{figure}
  1293. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  1294. arguments are integers and if they are, perform the appropriate
  1295. arithmetic. Otherwise, they create an AST node for the arithmetic
  1296. operation.
  1297. To gain some confidence that the partial evaluator is correct, we can
  1298. test whether it produces programs that get the same result as the
  1299. input programs. That is, we can test whether it satisfies Diagram
  1300. \ref{eq:compile-correct}. The following code runs the partial
  1301. evaluator on several examples and tests the output program. The
  1302. \texttt{parse-program} and \texttt{assert} functions are defined in
  1303. Appendix~\ref{appendix:utilities}.\\
  1304. \begin{minipage}{1.0\textwidth}
  1305. \begin{lstlisting}
  1306. (define (test-pe p)
  1307. (assert "testing pe-Rint"
  1308. (equal? (interp_Rint p) (interp_Rint (pe-Rint p)))))
  1309. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1310. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1311. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1312. \end{lstlisting}
  1313. \end{minipage}
  1314. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1315. \chapter{Integers and Variables}
  1316. \label{ch:Rvar}
  1317. This chapter is about compiling a subset of Racket to x86-64 assembly
  1318. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1319. integer arithmetic and local variable binding. We often refer to
  1320. x86-64 simply as x86. The chapter begins with a description of the
  1321. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1322. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1323. is large so we discuss only the instructions needed for compiling
  1324. \LangVar{}. We introduce more x86 instructions in later chapters.
  1325. After introducing \LangVar{} and x86, we reflect on their differences
  1326. and come up with a plan to break down the translation from \LangVar{}
  1327. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1328. rest of the sections in this chapter give detailed hints regarding
  1329. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1330. We hope to give enough hints that the well-prepared reader, together
  1331. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1332. a couple weeks. To give the reader a feeling for the scale of this
  1333. first compiler, the instructor solution for the \LangVar{} compiler is
  1334. approximately 500 lines of code.
  1335. \section{The \LangVar{} Language}
  1336. \label{sec:s0}
  1337. \index{subject}{variable}
  1338. The \LangVar{} language extends the \LangInt{} language with variable
  1339. definitions. The concrete syntax of the \LangVar{} language is defined by
  1340. the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the abstract
  1341. syntax is defined in Figure~\ref{fig:Rvar-syntax}. The non-terminal
  1342. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1343. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1344. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1345. \key{Program} struct to mark the top of the program.
  1346. %% The $\itm{info}$
  1347. %% field of the \key{Program} structure contains an \emph{association
  1348. %% list} (a list of key-value pairs) that is used to communicate
  1349. %% auxiliary data from one compiler pass the next.
  1350. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1351. exhibit several compilation techniques.
  1352. \begin{figure}[tp]
  1353. \centering
  1354. \fbox{
  1355. \begin{minipage}{0.96\textwidth}
  1356. \[
  1357. \begin{array}{rcl}
  1358. \Exp &::=& \Int{} \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1359. &\mid& \Var{} \mid \CLET{\Var}{\Exp}{\Exp} \\
  1360. \LangVarM{} &::=& \Exp
  1361. \end{array}
  1362. \]
  1363. \end{minipage}
  1364. }
  1365. \caption{The concrete syntax of \LangVar{}.}
  1366. \label{fig:Rvar-concrete-syntax}
  1367. \end{figure}
  1368. \begin{figure}[tp]
  1369. \centering
  1370. \fbox{
  1371. \begin{minipage}{0.96\textwidth}
  1372. \[
  1373. \begin{array}{rcl}
  1374. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1375. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1376. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1377. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1378. \end{array}
  1379. \]
  1380. \end{minipage}
  1381. }
  1382. \caption{The abstract syntax of \LangVar{}.}
  1383. \label{fig:Rvar-syntax}
  1384. \end{figure}
  1385. Let us dive further into the syntax and semantics of the \LangVar{}
  1386. language. The \key{let} feature defines a variable for use within its
  1387. body and initializes the variable with the value of an expression.
  1388. The abstract syntax for \key{let} is defined in
  1389. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1390. \begin{lstlisting}
  1391. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1392. \end{lstlisting}
  1393. For example, the following program initializes \code{x} to $32$ and then
  1394. evaluates the body \code{(+ 10 x)}, producing $42$.
  1395. \begin{lstlisting}
  1396. (let ([x (+ 12 20)]) (+ 10 x))
  1397. \end{lstlisting}
  1398. When there are multiple \key{let}'s for the same variable, the closest
  1399. enclosing \key{let} is used. That is, variable definitions overshadow
  1400. prior definitions. Consider the following program with two \key{let}'s
  1401. that define variables named \code{x}. Can you figure out the result?
  1402. \begin{lstlisting}
  1403. (let ([x 32]) (+ (let ([x 10]) x) x))
  1404. \end{lstlisting}
  1405. For the purposes of depicting which variable uses correspond to which
  1406. definitions, the following shows the \code{x}'s annotated with
  1407. subscripts to distinguish them. Double check that your answer for the
  1408. above is the same as your answer for this annotated version of the
  1409. program.
  1410. \begin{lstlisting}
  1411. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1412. \end{lstlisting}
  1413. The initializing expression is always evaluated before the body of the
  1414. \key{let}, so in the following, the \key{read} for \code{x} is
  1415. performed before the \key{read} for \code{y}. Given the input
  1416. $52$ then $10$, the following produces $42$ (not $-42$).
  1417. \begin{lstlisting}
  1418. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1419. \end{lstlisting}
  1420. \subsection{Extensible Interpreters via Method Overriding}
  1421. \label{sec:extensible-interp}
  1422. To prepare for discussing the interpreter for \LangVar{}, we
  1423. explain why we to implement the interpreter using
  1424. object-oriented programming, that is, as a collection of methods
  1425. inside of a class. Throughout this book we define many interpreters,
  1426. one for each of the languages that we study. Because each language
  1427. builds on the prior one, there is a lot of commonality between these
  1428. interpreters. We want to write down those common parts just once
  1429. instead of many times. A naive approach would be to have, for example,
  1430. the interpreter for \LangIf{} handle all of the new features in that
  1431. language and then have a default case that dispatches to the
  1432. interpreter for \LangVar{}. The following code sketches this idea.
  1433. \begin{center}
  1434. \begin{minipage}{0.45\textwidth}
  1435. \begin{lstlisting}
  1436. (define (interp-Rvar e)
  1437. (match e
  1438. [(Prim '- (list e))
  1439. (fx- 0 (interp-Rvar e))]
  1440. ...))
  1441. \end{lstlisting}
  1442. \end{minipage}
  1443. \begin{minipage}{0.45\textwidth}
  1444. \begin{lstlisting}
  1445. (define (interp-Rif e)
  1446. (match e
  1447. [(If cnd thn els)
  1448. (match (interp-Rif cnd)
  1449. [#t (interp-Rif thn)]
  1450. [#f (interp-Rif els)])]
  1451. ...
  1452. [else (interp-Rvar e)]))
  1453. \end{lstlisting}
  1454. \end{minipage}
  1455. \end{center}
  1456. The problem with this approach is that it does not handle situations
  1457. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1458. feature, like the \code{-} operator, as in the following program.
  1459. \begin{lstlisting}
  1460. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1461. \end{lstlisting}
  1462. If we invoke \code{interp-Rif} on this program, it dispatches to
  1463. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1464. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1465. which is an \code{If}. But there is no case for \code{If} in
  1466. \code{interp-Rvar}, so we get an error!
  1467. To make our interpreters extensible we need something called
  1468. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1469. recursive knot is delayed to when the functions are
  1470. composed. Object-oriented languages provide open recursion with the
  1471. late-binding of overridden methods\index{subject}{method overriding}. The
  1472. following code sketches this idea for interpreting \LangVar{} and
  1473. \LangIf{} using the
  1474. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1475. \index{subject}{class} feature of Racket. We define one class for each
  1476. language and define a method for interpreting expressions inside each
  1477. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1478. and the method \code{interp-exp} in \LangIf{} overrides the
  1479. \code{interp-exp} in \LangVar{}. Note that the default case of
  1480. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1481. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1482. that dispatches to the \code{interp-exp} in \LangVar{}.
  1483. \begin{center}
  1484. \begin{minipage}{0.45\textwidth}
  1485. \begin{lstlisting}
  1486. (define interp-Rvar-class
  1487. (class object%
  1488. (define/public (interp-exp e)
  1489. (match e
  1490. [(Prim '- (list e))
  1491. (fx- 0 (interp-exp e))]
  1492. ...))
  1493. ...))
  1494. \end{lstlisting}
  1495. \end{minipage}
  1496. \begin{minipage}{0.45\textwidth}
  1497. \begin{lstlisting}
  1498. (define interp-Rif-class
  1499. (class interp-Rvar-class
  1500. (define/override (interp-exp e)
  1501. (match e
  1502. [(If cnd thn els)
  1503. (match (interp-exp cnd)
  1504. [#t (interp-exp thn)]
  1505. [#f (interp-exp els)])]
  1506. ...
  1507. [else (super interp-exp e)]))
  1508. ...
  1509. ))
  1510. \end{lstlisting}
  1511. \end{minipage}
  1512. \end{center}
  1513. Getting back to the troublesome example, repeated here:
  1514. \begin{lstlisting}
  1515. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1516. \end{lstlisting}
  1517. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1518. expression by creating an object of the \LangIf{} class and sending it the
  1519. \code{interp-exp} method with the argument \code{e0}.
  1520. \begin{lstlisting}
  1521. (send (new interp-Rif-class) interp-exp e0)
  1522. \end{lstlisting}
  1523. The default case of \code{interp-exp} in \LangIf{} handles it by
  1524. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1525. handles the \code{-} operator. But then for the recursive method call,
  1526. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1527. \code{If} is handled correctly. Thus, method overriding gives us the
  1528. open recursion that we need to implement our interpreters in an
  1529. extensible way.
  1530. \subsection{Definitional Interpreter for \LangVar{}}
  1531. \begin{figure}[tp]
  1532. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1533. \small
  1534. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1535. An \emph{association list} (alist) is a list of key-value pairs.
  1536. For example, we can map people to their ages with an alist.
  1537. \index{subject}{alist}\index{subject}{association list}
  1538. \begin{lstlisting}[basicstyle=\ttfamily]
  1539. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1540. \end{lstlisting}
  1541. The \emph{dictionary} interface is for mapping keys to values.
  1542. Every alist implements this interface. \index{subject}{dictionary} The package
  1543. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1544. provides many functions for working with dictionaries. Here
  1545. are a few of them:
  1546. \begin{description}
  1547. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1548. returns the value associated with the given $\itm{key}$.
  1549. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1550. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1551. but otherwise is the same as $\itm{dict}$.
  1552. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1553. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1554. of keys and values in $\itm{dict}$. For example, the following
  1555. creates a new alist in which the ages are incremented.
  1556. \end{description}
  1557. \vspace{-10pt}
  1558. \begin{lstlisting}[basicstyle=\ttfamily]
  1559. (for/list ([(k v) (in-dict ages)])
  1560. (cons k (add1 v)))
  1561. \end{lstlisting}
  1562. \end{tcolorbox}
  1563. %\end{wrapfigure}
  1564. \caption{Association lists implement the dictionary interface.}
  1565. \label{fig:alist}
  1566. \end{figure}
  1567. Having justified the use of classes and methods to implement
  1568. interpreters, we turn to the definitional interpreter for \LangVar{}
  1569. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1570. \LangInt{} but adds two new \key{match} cases for variables and
  1571. \key{let}. For \key{let} we need a way to communicate the value bound
  1572. to a variable to all the uses of the variable. To accomplish this, we
  1573. maintain a mapping from variables to values. Throughout the compiler
  1574. we often need to map variables to information about them. We refer to
  1575. these mappings as
  1576. \emph{environments}\index{subject}{environment}.\footnote{Another common term
  1577. for environment in the compiler literature is \emph{symbol
  1578. table}\index{subject}{symbol table}.}
  1579. %
  1580. For simplicity, we use an association list (alist) to represent the
  1581. environment. Figure~\ref{fig:alist} gives a brief introduction to
  1582. alists and the \code{racket/dict} package. The \code{interp-exp}
  1583. function takes the current environment, \code{env}, as an extra
  1584. parameter. When the interpreter encounters a variable, it finds the
  1585. corresponding value using the \code{dict-ref} function. When the
  1586. interpreter encounters a \key{Let}, it evaluates the initializing
  1587. expression, extends the environment with the result value bound to the
  1588. variable, using \code{dict-set}, then evaluates the body of the
  1589. \key{Let}.
  1590. \begin{figure}[tp]
  1591. \begin{lstlisting}
  1592. (define interp-Rvar-class
  1593. (class object%
  1594. (super-new)
  1595. (define/public ((interp-exp env) e)
  1596. (match e
  1597. [(Int n) n]
  1598. [(Prim 'read '())
  1599. (define r (read))
  1600. (cond [(fixnum? r) r]
  1601. [else (error 'interp-exp "expected an integer" r)])]
  1602. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1603. [(Prim '+ (list e1 e2))
  1604. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1605. [(Var x) (dict-ref env x)]
  1606. [(Let x e body)
  1607. (define new-env (dict-set env x ((interp-exp env) e)))
  1608. ((interp-exp new-env) body)]))
  1609. (define/public (interp-program p)
  1610. (match p
  1611. [(Program '() e) ((interp-exp '()) e)]))
  1612. ))
  1613. (define (interp-Rvar p)
  1614. (send (new interp-Rvar-class) interp-program p))
  1615. \end{lstlisting}
  1616. \caption{Interpreter for the \LangVar{} language.}
  1617. \label{fig:interp-Rvar}
  1618. \end{figure}
  1619. The goal for this chapter is to implement a compiler that translates
  1620. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1621. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1622. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1623. is, they output the same integer $n$. We depict this correctness
  1624. criteria in the following diagram.
  1625. \[
  1626. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1627. \node (p1) at (0, 0) {$P_1$};
  1628. \node (p2) at (4, 0) {$P_2$};
  1629. \node (o) at (4, -2) {$n$};
  1630. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1631. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1632. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1633. \end{tikzpicture}
  1634. \]
  1635. In the next section we introduce the \LangXInt{} subset of x86 that
  1636. suffices for compiling \LangVar{}.
  1637. \section{The \LangXInt{} Assembly Language}
  1638. \label{sec:x86}
  1639. \index{subject}{x86}
  1640. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1641. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1642. assembler.
  1643. %
  1644. A program begins with a \code{main} label followed by a sequence of
  1645. instructions. The \key{globl} directive says that the \key{main}
  1646. procedure is externally visible, which is necessary so that the
  1647. operating system can call it. In the grammar, ellipses such as
  1648. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1649. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1650. %
  1651. An x86 program is stored in the computer's memory. For our purposes,
  1652. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1653. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1654. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1655. the address of the next instruction to be executed. For most
  1656. instructions, the program counter is incremented after the instruction
  1657. is executed, so it points to the next instruction in memory. Most x86
  1658. instructions take two operands, where each operand is either an
  1659. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1660. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1661. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1662. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1663. && \key{r8} \mid \key{r9} \mid \key{r10}
  1664. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1665. \mid \key{r14} \mid \key{r15}}
  1666. \begin{figure}[tp]
  1667. \fbox{
  1668. \begin{minipage}{0.96\textwidth}
  1669. \[
  1670. \begin{array}{lcl}
  1671. \Reg &::=& \allregisters{} \\
  1672. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1673. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1674. \key{subq} \; \Arg\key{,} \Arg \mid
  1675. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1676. && \key{callq} \; \mathit{label} \mid
  1677. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1678. && \itm{label}\key{:}\; \Instr \\
  1679. \LangXIntM{} &::= & \key{.globl main}\\
  1680. & & \key{main:} \; \Instr\ldots
  1681. \end{array}
  1682. \]
  1683. \end{minipage}
  1684. }
  1685. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1686. \label{fig:x86-int-concrete}
  1687. \end{figure}
  1688. A register is a special kind of variable. Each one holds a 64-bit
  1689. value; there are 16 general-purpose registers in the computer and
  1690. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1691. is written with a \key{\%} followed by the register name, such as
  1692. \key{\%rax}.
  1693. An immediate value is written using the notation \key{\$}$n$ where $n$
  1694. is an integer.
  1695. %
  1696. %
  1697. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1698. which obtains the address stored in register $r$ and then adds $n$
  1699. bytes to the address. The resulting address is used to load or store
  1700. to memory depending on whether it occurs as a source or destination
  1701. argument of an instruction.
  1702. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1703. source $s$ and destination $d$, applies the arithmetic operation, then
  1704. writes the result back to the destination $d$.
  1705. %
  1706. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1707. stores the result in $d$.
  1708. %
  1709. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1710. specified by the label and $\key{retq}$ returns from a procedure to
  1711. its caller.
  1712. %
  1713. We discuss procedure calls in more detail later in this chapter and in
  1714. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1715. updates the program counter to the address of the instruction after
  1716. the specified label.
  1717. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1718. all of the x86 instructions used in this book.
  1719. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1720. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1721. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1722. adds $32$ to the $10$ in \key{rax} and
  1723. puts the result, $42$, back into \key{rax}.
  1724. %
  1725. The last instruction, \key{retq}, finishes the \key{main} function by
  1726. returning the integer in \key{rax} to the operating system. The
  1727. operating system interprets this integer as the program's exit
  1728. code. By convention, an exit code of 0 indicates that a program
  1729. completed successfully, and all other exit codes indicate various
  1730. errors. Nevertheless, in this book we return the result of the program
  1731. as the exit code.
  1732. \begin{figure}[tbp]
  1733. \begin{lstlisting}
  1734. .globl main
  1735. main:
  1736. movq $10, %rax
  1737. addq $32, %rax
  1738. retq
  1739. \end{lstlisting}
  1740. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1741. \label{fig:p0-x86}
  1742. \end{figure}
  1743. The x86 assembly language varies in a couple of ways depending on what
  1744. operating system it is assembled in. The code examples shown here are
  1745. correct on Linux and most Unix-like platforms, but when assembled on
  1746. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1747. as in \key{\_main}.
  1748. We exhibit the use of memory for storing intermediate results in the
  1749. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1750. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1751. memory called the \emph{procedure call stack} (or \emph{stack} for
  1752. short). \index{subject}{stack}\index{subject}{procedure call stack} The stack consists
  1753. of a separate \emph{frame}\index{subject}{frame} for each procedure call. The
  1754. memory layout for an individual frame is shown in
  1755. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1756. \emph{stack pointer}\index{subject}{stack pointer} and points to the item at
  1757. the top of the stack. The stack grows downward in memory, so we
  1758. increase the size of the stack by subtracting from the stack pointer.
  1759. In the context of a procedure call, the \emph{return
  1760. address}\index{subject}{return address} is the instruction after the call
  1761. instruction on the caller side. The function call instruction,
  1762. \code{callq}, pushes the return address onto the stack prior to
  1763. jumping to the procedure. The register \key{rbp} is the \emph{base
  1764. pointer}\index{subject}{base pointer} and is used to access variables that
  1765. are stored in the frame of the current procedure call. The base
  1766. pointer of the caller is pushed onto the stack after the return
  1767. address and then the base pointer is set to the location of the old
  1768. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1769. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1770. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1771. \begin{figure}[tbp]
  1772. \begin{lstlisting}
  1773. start:
  1774. movq $10, -8(%rbp)
  1775. negq -8(%rbp)
  1776. movq -8(%rbp), %rax
  1777. addq $52, %rax
  1778. jmp conclusion
  1779. .globl main
  1780. main:
  1781. pushq %rbp
  1782. movq %rsp, %rbp
  1783. subq $16, %rsp
  1784. jmp start
  1785. conclusion:
  1786. addq $16, %rsp
  1787. popq %rbp
  1788. retq
  1789. \end{lstlisting}
  1790. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1791. \label{fig:p1-x86}
  1792. \end{figure}
  1793. \begin{figure}[tbp]
  1794. \centering
  1795. \begin{tabular}{|r|l|} \hline
  1796. Position & Contents \\ \hline
  1797. 8(\key{\%rbp}) & return address \\
  1798. 0(\key{\%rbp}) & old \key{rbp} \\
  1799. -8(\key{\%rbp}) & variable $1$ \\
  1800. -16(\key{\%rbp}) & variable $2$ \\
  1801. \ldots & \ldots \\
  1802. 0(\key{\%rsp}) & variable $n$\\ \hline
  1803. \end{tabular}
  1804. \caption{Memory layout of a frame.}
  1805. \label{fig:frame}
  1806. \end{figure}
  1807. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1808. control is transferred from the operating system to the \code{main}
  1809. function. The operating system issues a \code{callq main} instruction
  1810. which pushes its return address on the stack and then jumps to
  1811. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1812. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1813. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1814. alignment (because the \code{callq} pushed the return address). The
  1815. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  1816. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1817. pointer for the caller onto the stack and subtracts $8$ from the stack
  1818. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1819. base pointer so that it points the location of the old base
  1820. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1821. pointer down to make enough room for storing variables. This program
  1822. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1823. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1824. functions. The last instruction of the prelude is \code{jmp start},
  1825. which transfers control to the instructions that were generated from
  1826. the Racket expression \code{(+ 52 (- 10))}.
  1827. The first instruction under the \code{start} label is
  1828. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1829. %
  1830. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1831. %
  1832. The next instruction moves the $-10$ from variable $1$ into the
  1833. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1834. the value in \code{rax}, updating its contents to $42$.
  1835. The three instructions under the label \code{conclusion} are the
  1836. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  1837. two instructions restore the \code{rsp} and \code{rbp} registers to
  1838. the state they were in at the beginning of the procedure. The
  1839. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1840. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1841. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1842. instruction, \key{retq}, jumps back to the procedure that called this
  1843. one and adds $8$ to the stack pointer.
  1844. The compiler needs a convenient representation for manipulating x86
  1845. programs, so we define an abstract syntax for x86 in
  1846. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1847. \LangXInt{}. The main difference compared to the concrete syntax of
  1848. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1849. allowed in front of every instruction. Instead instructions are
  1850. grouped into \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  1851. label associated with every block, which is why the \key{X86Program}
  1852. struct includes an alist mapping labels to blocks. The reason for this
  1853. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1854. introduce conditional branching. The \code{Block} structure includes
  1855. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1856. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1857. $\itm{info}$ field should contain an empty list. Also, regarding the
  1858. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1859. integer for representing the arity of the function, i.e., the number
  1860. of arguments, which is helpful to know during register allocation
  1861. (Chapter~\ref{ch:register-allocation-Rvar}).
  1862. \begin{figure}[tp]
  1863. \fbox{
  1864. \begin{minipage}{0.98\textwidth}
  1865. \small
  1866. \[
  1867. \begin{array}{lcl}
  1868. \Reg &::=& \allregisters{} \\
  1869. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1870. \mid \DEREF{\Reg}{\Int} \\
  1871. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1872. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1873. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1874. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1875. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1876. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1877. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1878. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1879. \end{array}
  1880. \]
  1881. \end{minipage}
  1882. }
  1883. \caption{The abstract syntax of \LangXInt{} assembly.}
  1884. \label{fig:x86-int-ast}
  1885. \end{figure}
  1886. \section{Planning the trip to x86 via the \LangCVar{} language}
  1887. \label{sec:plan-s0-x86}
  1888. To compile one language to another it helps to focus on the
  1889. differences between the two languages because the compiler will need
  1890. to bridge those differences. What are the differences between \LangVar{}
  1891. and x86 assembly? Here are some of the most important ones:
  1892. \begin{enumerate}
  1893. \item[(a)] x86 arithmetic instructions typically have two arguments
  1894. and update the second argument in place. In contrast, \LangVar{}
  1895. arithmetic operations take two arguments and produce a new value.
  1896. An x86 instruction may have at most one memory-accessing argument.
  1897. Furthermore, some instructions place special restrictions on their
  1898. arguments.
  1899. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1900. expression, whereas x86 instructions restrict their arguments to be
  1901. integer constants, registers, and memory locations.
  1902. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1903. sequence of instructions and jumps to labeled positions, whereas in
  1904. \LangVar{} the order of evaluation is a left-to-right depth-first
  1905. traversal of the abstract syntax tree.
  1906. \item[(d)] A program in \LangVar{} can have any number of variables
  1907. whereas x86 has 16 registers and the procedure calls stack.
  1908. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  1909. same name. In x86, registers have unique names and memory locations
  1910. have unique addresses.
  1911. \end{enumerate}
  1912. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1913. the problem into several steps, dealing with the above differences one
  1914. at a time. Each of these steps is called a \emph{pass} of the
  1915. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  1916. %
  1917. This terminology comes from the way each step passes over the AST of
  1918. the program.
  1919. %
  1920. We begin by sketching how we might implement each pass, and give them
  1921. names. We then figure out an ordering of the passes and the
  1922. input/output language for each pass. The very first pass has
  1923. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1924. its output language. In between we can choose whichever language is
  1925. most convenient for expressing the output of each pass, whether that
  1926. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1927. our own design. Finally, to implement each pass we write one
  1928. recursive function per non-terminal in the grammar of the input
  1929. language of the pass. \index{subject}{intermediate language}
  1930. \begin{description}
  1931. \item[\key{select-instructions}] handles the difference between
  1932. \LangVar{} operations and x86 instructions. This pass converts each
  1933. \LangVar{} operation to a short sequence of instructions that
  1934. accomplishes the same task.
  1935. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1936. a primitive operation is a variable or integer, that is, an
  1937. \emph{atomic} expression. We refer to non-atomic expressions as
  1938. \emph{complex}. This pass introduces temporary variables to hold
  1939. the results of complex subexpressions.\index{subject}{atomic
  1940. expression}\index{subject}{complex expression}%
  1941. \footnote{The subexpressions of an operation are often called
  1942. operators and operands which explains the presence of
  1943. \code{opera*} in the name of this pass.}
  1944. \item[\key{explicate-control}] makes the execution order of the
  1945. program explicit. It convert the abstract syntax tree representation
  1946. into a control-flow graph in which each node contains a sequence of
  1947. statements and the edges between nodes say which nodes contain jumps
  1948. to other nodes.
  1949. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1950. registers or stack locations in x86.
  1951. \item[\key{uniquify}] deals with the shadowing of variables by
  1952. renaming every variable to a unique name.
  1953. \end{description}
  1954. The next question is: in what order should we apply these passes? This
  1955. question can be challenging because it is difficult to know ahead of
  1956. time which orderings will be better (easier to implement, produce more
  1957. efficient code, etc.) so oftentimes trial-and-error is
  1958. involved. Nevertheless, we can try to plan ahead and make educated
  1959. choices regarding the ordering.
  1960. What should be the ordering of \key{explicate-control} with respect to
  1961. \key{uniquify}? The \key{uniquify} pass should come first because
  1962. \key{explicate-control} changes all the \key{let}-bound variables to
  1963. become local variables whose scope is the entire program, which would
  1964. confuse variables with the same name.
  1965. %
  1966. We place \key{remove-complex-opera*} before \key{explicate-control}
  1967. because the later removes the \key{let} form, but it is convenient to
  1968. use \key{let} in the output of \key{remove-complex-opera*}.
  1969. %
  1970. The ordering of \key{uniquify} with respect to
  1971. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1972. \key{uniquify} to come first.
  1973. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1974. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1975. learn that, in x86, registers are used for passing arguments to
  1976. functions and it is preferable to assign parameters to their
  1977. corresponding registers. On the other hand, by selecting instructions
  1978. first we may run into a dead end in \key{assign-homes}. Recall that
  1979. only one argument of an x86 instruction may be a memory access but
  1980. \key{assign-homes} might fail to assign even one of them to a
  1981. register.
  1982. %
  1983. A sophisticated approach is to iteratively repeat the two passes until
  1984. a solution is found. However, to reduce implementation complexity we
  1985. recommend a simpler approach in which \key{select-instructions} comes
  1986. first, followed by the \key{assign-homes}, then a third pass named
  1987. \key{patch-instructions} that uses a reserved register to fix
  1988. outstanding problems.
  1989. \begin{figure}[tbp]
  1990. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1991. \node (Rvar) at (0,2) {\large \LangVar{}};
  1992. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1993. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1994. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1995. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1996. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1997. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1998. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1999. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2000. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2001. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  2002. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  2003. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2004. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  2005. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2006. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2007. \end{tikzpicture}
  2008. \caption{Diagram of the passes for compiling \LangVar{}. }
  2009. \label{fig:Rvar-passes}
  2010. \end{figure}
  2011. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2012. passes and identifies the input and output language of each pass. The
  2013. last pass, \key{print-x86}, converts from the abstract syntax of
  2014. \LangXInt{} to the concrete syntax. In the following two sections
  2015. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  2016. dialect of x86. The remainder of this chapter gives hints regarding
  2017. the implementation of each of the compiler passes in
  2018. Figure~\ref{fig:Rvar-passes}.
  2019. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2020. %% are programs that are still in the \LangVar{} language, though the
  2021. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2022. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2023. %% %
  2024. %% The output of \key{explicate-control} is in an intermediate language
  2025. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2026. %% syntax, which we introduce in the next section. The
  2027. %% \key{select-instruction} pass translates from \LangCVar{} to
  2028. %% \LangXVar{}. The \key{assign-homes} and
  2029. %% \key{patch-instructions}
  2030. %% passes input and output variants of x86 assembly.
  2031. \subsection{The \LangCVar{} Intermediate Language}
  2032. The output of \key{explicate-control} is similar to the $C$
  2033. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2034. categories for expressions and statements, so we name it \LangCVar{}. The
  2035. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2036. (The concrete syntax for \LangCVar{} is in the Appendix,
  2037. Figure~\ref{fig:c0-concrete-syntax}.)
  2038. %
  2039. The \LangCVar{} language supports the same operators as \LangVar{} but
  2040. the arguments of operators are restricted to atomic
  2041. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2042. assignment statements which can be executed in sequence using the
  2043. \key{Seq} form. A sequence of statements always ends with
  2044. \key{Return}, a guarantee that is baked into the grammar rules for
  2045. \itm{tail}. The naming of this non-terminal comes from the term
  2046. \emph{tail position}\index{subject}{tail position}, which refers to an
  2047. expression that is the last one to execute within a function.
  2048. A \LangCVar{} program consists of a control-flow graph represented as
  2049. an alist mapping labels to tails. This is more general than necessary
  2050. for the present chapter, as we do not yet introduce \key{goto} for
  2051. jumping to labels, but it saves us from having to change the syntax in
  2052. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2053. \key{start}, and the whole program is its tail.
  2054. %
  2055. The $\itm{info}$ field of the \key{CProgram} form, after the
  2056. \key{explicate-control} pass, contains a mapping from the symbol
  2057. \key{locals} to a list of variables, that is, a list of all the
  2058. variables used in the program. At the start of the program, these
  2059. variables are uninitialized; they become initialized on their first
  2060. assignment.
  2061. \begin{figure}[tbp]
  2062. \fbox{
  2063. \begin{minipage}{0.96\textwidth}
  2064. \[
  2065. \begin{array}{lcl}
  2066. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2067. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  2068. &\mid& \ADD{\Atm}{\Atm}\\
  2069. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2070. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  2071. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2072. \end{array}
  2073. \]
  2074. \end{minipage}
  2075. }
  2076. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2077. \label{fig:c0-syntax}
  2078. \end{figure}
  2079. The definitional interpreter for \LangCVar{} is in the support code,
  2080. in the file \code{interp-Cvar.rkt}.
  2081. \subsection{The \LangXVar{} dialect}
  2082. The \LangXVar{} language is the output of the pass
  2083. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  2084. number of program-scope variables and removes the restrictions
  2085. regarding instruction arguments.
  2086. \section{Uniquify Variables}
  2087. \label{sec:uniquify-Rvar}
  2088. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2089. programs in which every \key{let} binds a unique variable name. For
  2090. example, the \code{uniquify} pass should translate the program on the
  2091. left into the program on the right.
  2092. \begin{transformation}
  2093. \begin{lstlisting}
  2094. (let ([x 32])
  2095. (+ (let ([x 10]) x) x))
  2096. \end{lstlisting}
  2097. \compilesto
  2098. \begin{lstlisting}
  2099. (let ([x.1 32])
  2100. (+ (let ([x.2 10]) x.2) x.1))
  2101. \end{lstlisting}
  2102. \end{transformation}
  2103. The following is another example translation, this time of a program
  2104. with a \key{let} nested inside the initializing expression of another
  2105. \key{let}.
  2106. \begin{transformation}
  2107. \begin{lstlisting}
  2108. (let ([x (let ([x 4])
  2109. (+ x 1))])
  2110. (+ x 2))
  2111. \end{lstlisting}
  2112. \compilesto
  2113. \begin{lstlisting}
  2114. (let ([x.2 (let ([x.1 4])
  2115. (+ x.1 1))])
  2116. (+ x.2 2))
  2117. \end{lstlisting}
  2118. \end{transformation}
  2119. We recommend implementing \code{uniquify} by creating a structurally
  2120. recursive function named \code{uniquify-exp} that mostly just copies
  2121. an expression. However, when encountering a \key{let}, it should
  2122. generate a unique name for the variable and associate the old name
  2123. with the new name in an alist.\footnote{The Racket function
  2124. \code{gensym} is handy for generating unique variable names.} The
  2125. \code{uniquify-exp} function needs to access this alist when it gets
  2126. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2127. for the alist.
  2128. The skeleton of the \code{uniquify-exp} function is shown in
  2129. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2130. convenient to partially apply it to an alist and then apply it to
  2131. different expressions, as in the last case for primitive operations in
  2132. Figure~\ref{fig:uniquify-Rvar}. The
  2133. %
  2134. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2135. %
  2136. form of Racket is useful for transforming each element of a list to
  2137. produce a new list.\index{subject}{for/list}
  2138. \begin{figure}[tbp]
  2139. \begin{lstlisting}
  2140. (define (uniquify-exp env)
  2141. (lambda (e)
  2142. (match e
  2143. [(Var x) ___]
  2144. [(Int n) (Int n)]
  2145. [(Let x e body) ___]
  2146. [(Prim op es)
  2147. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2148. (define (uniquify p)
  2149. (match p
  2150. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2151. \end{lstlisting}
  2152. \caption{Skeleton for the \key{uniquify} pass.}
  2153. \label{fig:uniquify-Rvar}
  2154. \end{figure}
  2155. \begin{exercise}
  2156. \normalfont % I don't like the italics for exercises. -Jeremy
  2157. Complete the \code{uniquify} pass by filling in the blanks in
  2158. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2159. variables and for the \key{let} form in the file \code{compiler.rkt}
  2160. in the support code.
  2161. \end{exercise}
  2162. \begin{exercise}
  2163. \normalfont % I don't like the italics for exercises. -Jeremy
  2164. \label{ex:Rvar}
  2165. Create five \LangVar{} programs that exercise the most interesting
  2166. parts of the \key{uniquify} pass, that is, the programs should include
  2167. \key{let} forms, variables, and variables that shadow each other.
  2168. The five programs should be placed in the subdirectory named
  2169. \key{tests} and the file names should start with \code{var\_test\_}
  2170. followed by a unique integer and end with the file extension
  2171. \key{.rkt}.
  2172. %
  2173. The \key{run-tests.rkt} script in the support code checks whether the
  2174. output programs produce the same result as the input programs. The
  2175. script uses the \key{interp-tests} function
  2176. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2177. your \key{uniquify} pass on the example programs. The \code{passes}
  2178. parameter of \key{interp-tests} is a list that should have one entry
  2179. for each pass in your compiler. For now, define \code{passes} to
  2180. contain just one entry for \code{uniquify} as shown below.
  2181. \begin{lstlisting}
  2182. (define passes
  2183. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  2184. \end{lstlisting}
  2185. Run the \key{run-tests.rkt} script in the support code to check
  2186. whether the output programs produce the same result as the input
  2187. programs.
  2188. \end{exercise}
  2189. \section{Remove Complex Operands}
  2190. \label{sec:remove-complex-opera-Rvar}
  2191. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  2192. into a restricted form in which the arguments of operations are atomic
  2193. expressions. Put another way, this pass removes complex
  2194. operands\index{subject}{complex operand}, such as the expression \code{(- 10)}
  2195. in the program below. This is accomplished by introducing a new
  2196. \key{let}-bound variable, binding the complex operand to the new
  2197. variable, and then using the new variable in place of the complex
  2198. operand, as shown in the output of \code{remove-complex-opera*} on the
  2199. right.
  2200. \begin{transformation}
  2201. % var_test_19.rkt
  2202. \begin{lstlisting}
  2203. (let ([x (+ 42 (- 10))])
  2204. (+ x 10))
  2205. \end{lstlisting}
  2206. \compilesto
  2207. \begin{lstlisting}
  2208. (let ([x (let ([tmp.1 (- 10)])
  2209. (+ 42 tmp.1))])
  2210. (+ x 10))
  2211. \end{lstlisting}
  2212. \end{transformation}
  2213. \begin{figure}[tp]
  2214. \centering
  2215. \fbox{
  2216. \begin{minipage}{0.96\textwidth}
  2217. \[
  2218. \begin{array}{rcl}
  2219. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2220. \Exp &::=& \Atm \mid \READ{} \\
  2221. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  2222. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  2223. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2224. \end{array}
  2225. \]
  2226. \end{minipage}
  2227. }
  2228. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2229. atomic expressions, like administrative normal form (ANF).}
  2230. \label{fig:Rvar-anf-syntax}
  2231. \end{figure}
  2232. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  2233. this pass, the language \LangVarANF{}. The only difference is that
  2234. operator arguments are restricted to be atomic expressions that are
  2235. defined by the \Atm{} non-terminal. In particular, integer constants
  2236. and variables are atomic. In the literature, restricting arguments to
  2237. be atomic expressions is one of the ideas in \emph{administrative
  2238. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2239. \index{subject}{administrative normal form} \index{subject}{ANF}
  2240. We recommend implementing this pass with two mutually recursive
  2241. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  2242. \code{rco-atom} to subexpressions that need to become atomic and to
  2243. apply \code{rco-exp} to subexpressions that do not. Both functions
  2244. take an \LangVar{} expression as input. The \code{rco-exp} function
  2245. returns an expression. The \code{rco-atom} function returns two
  2246. things: an atomic expression and an alist mapping temporary variables to
  2247. complex subexpressions. You can return multiple things from a function
  2248. using Racket's \key{values} form and you can receive multiple things
  2249. from a function call using the \key{define-values} form.
  2250. Also, the
  2251. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2252. form is useful for applying a function to each element of a list, in
  2253. the case where the function returns multiple values.
  2254. \index{subject}{for/lists}
  2255. Returning to the example program with the expression \code{(+ 42 (-
  2256. 10))}, the subexpression \code{(- 10)} should be processed using the
  2257. \code{rco-atom} function because it is an argument of the \code{+} and
  2258. therefore needs to become atomic. The output of \code{rco-atom}
  2259. applied to \code{(- 10)} is as follows.
  2260. \begin{transformation}
  2261. \begin{lstlisting}
  2262. (- 10)
  2263. \end{lstlisting}
  2264. \compilesto
  2265. \begin{lstlisting}
  2266. tmp.1
  2267. ((tmp.1 . (- 10)))
  2268. \end{lstlisting}
  2269. \end{transformation}
  2270. Take special care of programs such as the following that bind a
  2271. variable to an atomic expression. You should leave such variable
  2272. bindings unchanged, as shown in the program on the right \\
  2273. \begin{transformation}
  2274. % var_test_20.rkt
  2275. \begin{lstlisting}
  2276. (let ([a 42])
  2277. (let ([b a])
  2278. b))
  2279. \end{lstlisting}
  2280. \compilesto
  2281. \begin{lstlisting}
  2282. (let ([a 42])
  2283. (let ([b a])
  2284. b))
  2285. \end{lstlisting}
  2286. \end{transformation}
  2287. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2288. produce the following output with unnecessary temporary variables.
  2289. \begin{center}
  2290. \begin{minipage}{0.4\textwidth}
  2291. \begin{lstlisting}
  2292. (let ([tmp.1 42])
  2293. (let ([a tmp.1])
  2294. (let ([tmp.2 a])
  2295. (let ([b tmp.2])
  2296. b))))
  2297. \end{lstlisting}
  2298. \end{minipage}
  2299. \end{center}
  2300. \begin{exercise}
  2301. \normalfont
  2302. Implement the \code{remove-complex-opera*} function in
  2303. \code{compiler.rkt}.
  2304. %
  2305. Create three new \LangVar{} programs that exercise the interesting
  2306. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  2307. regarding file names described in Exercise~\ref{ex:Rvar}.
  2308. %
  2309. In the \code{run-tests.rkt} script, add the following entry to the
  2310. list of \code{passes} and then run the script to test your compiler.
  2311. \begin{lstlisting}
  2312. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2313. \end{lstlisting}
  2314. While debugging your compiler, it is often useful to see the
  2315. intermediate programs that are output from each pass. To print the
  2316. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2317. \code{interp-tests} in \code{run-tests.rkt}.
  2318. \end{exercise}
  2319. \section{Explicate Control}
  2320. \label{sec:explicate-control-Rvar}
  2321. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2322. programs that make the order of execution explicit in their
  2323. syntax. For now this amounts to flattening \key{let} constructs into a
  2324. sequence of assignment statements. For example, consider the following
  2325. \LangVar{} program.\\
  2326. % var_test_11.rkt
  2327. \begin{minipage}{0.96\textwidth}
  2328. \begin{lstlisting}
  2329. (let ([y (let ([x 20])
  2330. (+ x (let ([x 22]) x)))])
  2331. y)
  2332. \end{lstlisting}
  2333. \end{minipage}\\
  2334. %
  2335. The output of the previous pass and of \code{explicate-control} is
  2336. shown below. Recall that the right-hand-side of a \key{let} executes
  2337. before its body, so the order of evaluation for this program is to
  2338. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2339. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2340. output of \code{explicate-control} makes this ordering explicit.
  2341. \begin{transformation}
  2342. \begin{lstlisting}
  2343. (let ([y (let ([x.1 20])
  2344. (let ([x.2 22])
  2345. (+ x.1 x.2)))])
  2346. y)
  2347. \end{lstlisting}
  2348. \compilesto
  2349. \begin{lstlisting}[language=C]
  2350. start:
  2351. x.1 = 20;
  2352. x.2 = 22;
  2353. y = (+ x.1 x.2);
  2354. return y;
  2355. \end{lstlisting}
  2356. \end{transformation}
  2357. \begin{figure}[tbp]
  2358. \begin{lstlisting}
  2359. (define (explicate-tail e)
  2360. (match e
  2361. [(Var x) ___]
  2362. [(Int n) (Return (Int n))]
  2363. [(Let x rhs body) ___]
  2364. [(Prim op es) ___]
  2365. [else (error "explicate-tail unhandled case" e)]))
  2366. (define (explicate-assign e x cont)
  2367. (match e
  2368. [(Var x) ___]
  2369. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2370. [(Let y rhs body) ___]
  2371. [(Prim op es) ___]
  2372. [else (error "explicate-assign unhandled case" e)]))
  2373. (define (explicate-control p)
  2374. (match p
  2375. [(Program info body) ___]))
  2376. \end{lstlisting}
  2377. \caption{Skeleton for the \key{explicate-control} pass.}
  2378. \label{fig:explicate-control-Rvar}
  2379. \end{figure}
  2380. The organization of this pass depends on the notion of tail position
  2381. that we have alluded to earlier.
  2382. \begin{definition}
  2383. The following rules define when an expression is in \textbf{\emph{tail
  2384. position}}\index{subject}{tail position} for the language \LangVar{}.
  2385. \begin{enumerate}
  2386. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2387. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2388. \end{enumerate}
  2389. \end{definition}
  2390. We recommend implementing \code{explicate-control} using two mutually
  2391. recursive functions, \code{explicate-tail} and
  2392. \code{explicate-assign}, as suggested in the skeleton code in
  2393. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2394. function should be applied to expressions in tail position whereas the
  2395. \code{explicate-assign} should be applied to expressions that occur on
  2396. the right-hand-side of a \key{let}.
  2397. %
  2398. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2399. input and produces a \Tail{} in \LangCVar{} (see
  2400. Figure~\ref{fig:c0-syntax}).
  2401. %
  2402. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2403. the variable that it is to be assigned to, and a \Tail{} in
  2404. \LangCVar{} for the code that comes after the assignment. The
  2405. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2406. The \code{explicate-assign} function is in accumulator-passing style:
  2407. the \code{cont} parameter is used for accumulating the output. This
  2408. accumulator-passing style plays an important role in how we generate
  2409. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2410. \begin{exercise}\normalfont
  2411. %
  2412. Implement the \code{explicate-control} function in
  2413. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2414. exercise the code in \code{explicate-control}.
  2415. %
  2416. In the \code{run-tests.rkt} script, add the following entry to the
  2417. list of \code{passes} and then run the script to test your compiler.
  2418. \begin{lstlisting}
  2419. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2420. \end{lstlisting}
  2421. \end{exercise}
  2422. \section{Select Instructions}
  2423. \label{sec:select-Rvar}
  2424. \index{subject}{instruction selection}
  2425. In the \code{select-instructions} pass we begin the work of
  2426. translating from \LangCVar{} to \LangXVar{}. The target language of
  2427. this pass is a variant of x86 that still uses variables, so we add an
  2428. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2429. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2430. recommend implementing the \code{select-instructions} with
  2431. three auxiliary functions, one for each of the non-terminals of
  2432. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2433. The cases for $\Atm$ are straightforward; variables stay
  2434. the same and integer constants are changed to immediates:
  2435. $\INT{n}$ changes to $\IMM{n}$.
  2436. Next we consider the cases for $\Stmt$, starting with arithmetic
  2437. operations. For example, consider the addition operation. We can use
  2438. the \key{addq} instruction, but it performs an in-place update. So we
  2439. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2440. add $\itm{arg}_2$ to \itm{var}.
  2441. \begin{transformation}
  2442. \begin{lstlisting}
  2443. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2444. \end{lstlisting}
  2445. \compilesto
  2446. \begin{lstlisting}
  2447. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2448. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2449. \end{lstlisting}
  2450. \end{transformation}
  2451. There are also cases that require special care to avoid generating
  2452. needlessly complicated code. For example, if one of the arguments of
  2453. the addition is the same variable as the left-hand side of the
  2454. assignment, then there is no need for the extra move instruction. The
  2455. assignment statement can be translated into a single \key{addq}
  2456. instruction as follows.
  2457. \begin{transformation}
  2458. \begin{lstlisting}
  2459. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2460. \end{lstlisting}
  2461. \compilesto
  2462. \begin{lstlisting}
  2463. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2464. \end{lstlisting}
  2465. \end{transformation}
  2466. The \key{read} operation does not have a direct counterpart in x86
  2467. assembly, so we provide this functionality with the function
  2468. \code{read\_int} in the file \code{runtime.c}, written in
  2469. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2470. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2471. system}, or simply the \emph{runtime} for short. When compiling your
  2472. generated x86 assembly code, you need to compile \code{runtime.c} to
  2473. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2474. \code{-c}) and link it into the executable. For our purposes of code
  2475. generation, all you need to do is translate an assignment of
  2476. \key{read} into a call to the \code{read\_int} function followed by a
  2477. move from \code{rax} to the left-hand-side variable. (Recall that the
  2478. return value of a function goes into \code{rax}.)
  2479. \begin{transformation}
  2480. \begin{lstlisting}
  2481. |$\itm{var}$| = (read);
  2482. \end{lstlisting}
  2483. \compilesto
  2484. \begin{lstlisting}
  2485. callq read_int
  2486. movq %rax, |$\itm{var}$|
  2487. \end{lstlisting}
  2488. \end{transformation}
  2489. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2490. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2491. assignment to the \key{rax} register followed by a jump to the
  2492. conclusion of the program (so the conclusion needs to be labeled).
  2493. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2494. recursively and then append the resulting instructions.
  2495. \begin{exercise}
  2496. \normalfont Implement the \key{select-instructions} pass in
  2497. \code{compiler.rkt}. Create three new example programs that are
  2498. designed to exercise all of the interesting cases in this pass.
  2499. %
  2500. In the \code{run-tests.rkt} script, add the following entry to the
  2501. list of \code{passes} and then run the script to test your compiler.
  2502. \begin{lstlisting}
  2503. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2504. \end{lstlisting}
  2505. \end{exercise}
  2506. \section{Assign Homes}
  2507. \label{sec:assign-Rvar}
  2508. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2509. \LangXVar{} programs that no longer use program variables.
  2510. Thus, the \key{assign-homes} pass is responsible for placing all of
  2511. the program variables in registers or on the stack. For runtime
  2512. efficiency, it is better to place variables in registers, but as there
  2513. are only 16 registers, some programs must necessarily resort to
  2514. placing some variables on the stack. In this chapter we focus on the
  2515. mechanics of placing variables on the stack. We study an algorithm for
  2516. placing variables in registers in
  2517. Chapter~\ref{ch:register-allocation-Rvar}.
  2518. Consider again the following \LangVar{} program from
  2519. Section~\ref{sec:remove-complex-opera-Rvar}.
  2520. % var_test_20.rkt
  2521. \begin{lstlisting}
  2522. (let ([a 42])
  2523. (let ([b a])
  2524. b))
  2525. \end{lstlisting}
  2526. The output of \code{select-instructions} is shown on the left and the
  2527. output of \code{assign-homes} on the right. In this example, we
  2528. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2529. variable \code{b} to location \code{-16(\%rbp)}.
  2530. \begin{transformation}
  2531. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2532. locals-types:
  2533. a : Integer, b : Integer
  2534. start:
  2535. movq $42, a
  2536. movq a, b
  2537. movq b, %rax
  2538. jmp conclusion
  2539. \end{lstlisting}
  2540. \compilesto
  2541. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2542. stack-space: 16
  2543. start:
  2544. movq $42, -8(%rbp)
  2545. movq -8(%rbp), -16(%rbp)
  2546. movq -16(%rbp), %rax
  2547. jmp conclusion
  2548. \end{lstlisting}
  2549. \end{transformation}
  2550. The \code{locals-types} entry in the $\itm{info}$ of the
  2551. \code{X86Program} node is an alist mapping all the variables in the
  2552. program to their types (for now just \code{Integer}). The
  2553. \code{assign-homes} pass should replace all uses of those variables
  2554. with stack locations. As an aside, the \code{locals-types} entry is
  2555. computed by \code{type-check-Cvar} in the support code, which installs
  2556. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2557. be propagated to the \code{X86Program} node.
  2558. In the process of assigning variables to stack locations, it is
  2559. convenient for you to compute and store the size of the frame (in
  2560. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2561. the key \code{stack-space}, which is needed later to generate the
  2562. conclusion of the \code{main} procedure. The x86-64 standard requires
  2563. the frame size to be a multiple of 16 bytes.\index{subject}{frame}
  2564. \begin{exercise}\normalfont
  2565. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2566. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2567. \Block{}. We recommend that the auxiliary functions take an extra
  2568. parameter that is an alist mapping variable names to homes (stack
  2569. locations for now).
  2570. %
  2571. In the \code{run-tests.rkt} script, add the following entry to the
  2572. list of \code{passes} and then run the script to test your compiler.
  2573. \begin{lstlisting}
  2574. (list "assign homes" assign-homes interp-x86-0)
  2575. \end{lstlisting}
  2576. \end{exercise}
  2577. \section{Patch Instructions}
  2578. \label{sec:patch-s0}
  2579. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2580. \LangXInt{} by making sure that each instruction adheres to the
  2581. restriction that at most one argument of an instruction may be a
  2582. memory reference.
  2583. We return to the following example.\\
  2584. \begin{minipage}{0.5\textwidth}
  2585. % var_test_20.rkt
  2586. \begin{lstlisting}
  2587. (let ([a 42])
  2588. (let ([b a])
  2589. b))
  2590. \end{lstlisting}
  2591. \end{minipage}\\
  2592. The \key{assign-homes} pass produces the following output
  2593. for this program. \\
  2594. \begin{minipage}{0.5\textwidth}
  2595. \begin{lstlisting}
  2596. stack-space: 16
  2597. start:
  2598. movq $42, -8(%rbp)
  2599. movq -8(%rbp), -16(%rbp)
  2600. movq -16(%rbp), %rax
  2601. jmp conclusion
  2602. \end{lstlisting}
  2603. \end{minipage}\\
  2604. The second \key{movq} instruction is problematic because both
  2605. arguments are stack locations. We suggest fixing this problem by
  2606. moving from the source location to the register \key{rax} and then
  2607. from \key{rax} to the destination location, as follows.
  2608. \begin{lstlisting}
  2609. movq -8(%rbp), %rax
  2610. movq %rax, -16(%rbp)
  2611. \end{lstlisting}
  2612. \begin{exercise}
  2613. \normalfont Implement the \key{patch-instructions} pass in
  2614. \code{compiler.rkt}. Create three new example programs that are
  2615. designed to exercise all of the interesting cases in this pass.
  2616. %
  2617. In the \code{run-tests.rkt} script, add the following entry to the
  2618. list of \code{passes} and then run the script to test your compiler.
  2619. \begin{lstlisting}
  2620. (list "patch instructions" patch-instructions interp-x86-0)
  2621. \end{lstlisting}
  2622. \end{exercise}
  2623. \section{Print x86}
  2624. \label{sec:print-x86}
  2625. The last step of the compiler from \LangVar{} to x86 is to convert the
  2626. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2627. string representation (defined in
  2628. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2629. \key{string-append} functions are useful in this regard. The main work
  2630. that this step needs to perform is to create the \key{main} function
  2631. and the standard instructions for its prelude and conclusion, as shown
  2632. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2633. know the amount of space needed for the stack frame, which you can
  2634. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2635. the \key{X86Program} node.
  2636. When running on Mac OS X, you compiler should prefix an underscore to
  2637. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2638. useful for determining which operating system the compiler is running
  2639. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2640. \begin{exercise}\normalfont
  2641. %
  2642. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2643. %
  2644. In the \code{run-tests.rkt} script, add the following entry to the
  2645. list of \code{passes} and then run the script to test your compiler.
  2646. \begin{lstlisting}
  2647. (list "print x86" print-x86 #f)
  2648. \end{lstlisting}
  2649. %
  2650. Uncomment the call to the \key{compiler-tests} function
  2651. (Appendix~\ref{appendix:utilities}), which tests your complete
  2652. compiler by executing the generated x86 code. Compile the provided
  2653. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2654. script to test your compiler.
  2655. \end{exercise}
  2656. \section{Challenge: Partial Evaluator for \LangVar{}}
  2657. \label{sec:pe-Rvar}
  2658. \index{subject}{partial evaluation}
  2659. This section describes optional challenge exercises that involve
  2660. adapting and improving the partial evaluator for \LangInt{} that was
  2661. introduced in Section~\ref{sec:partial-evaluation}.
  2662. \begin{exercise}\label{ex:pe-Rvar}
  2663. \normalfont
  2664. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2665. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2666. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2667. and variables to the \LangInt{} language, so you will need to add cases for
  2668. them in the \code{pe-exp} function. Once complete, add the partial
  2669. evaluation pass to the front of your compiler and make sure that your
  2670. compiler still passes all of the tests.
  2671. \end{exercise}
  2672. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2673. \begin{exercise}
  2674. \normalfont
  2675. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2676. \code{pe-add} auxiliary functions with functions that know more about
  2677. arithmetic. For example, your partial evaluator should translate
  2678. \[
  2679. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2680. \code{(+ 2 (read))}
  2681. \]
  2682. To accomplish this, the \code{pe-exp} function should produce output
  2683. in the form of the $\itm{residual}$ non-terminal of the following
  2684. grammar. The idea is that when processing an addition expression, we
  2685. can always produce either 1) an integer constant, 2) an addition
  2686. expression with an integer constant on the left-hand side but not the
  2687. right-hand side, or 3) or an addition expression in which neither
  2688. subexpression is a constant.
  2689. \[
  2690. \begin{array}{lcl}
  2691. \itm{inert} &::=& \Var
  2692. \mid \LP\key{read}\RP
  2693. \mid \LP\key{-} ~\Var\RP
  2694. \mid \LP\key{-} ~\LP\key{read}\RP\RP
  2695. \mid \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  2696. &\mid& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  2697. \itm{residual} &::=& \Int
  2698. \mid \LP\key{+}~ \Int~ \itm{inert}\RP
  2699. \mid \itm{inert}
  2700. \end{array}
  2701. \]
  2702. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2703. inputs are $\itm{residual}$ expressions and they should return
  2704. $\itm{residual}$ expressions. Once the improvements are complete,
  2705. make sure that your compiler still passes all of the tests. After
  2706. all, fast code is useless if it produces incorrect results!
  2707. \end{exercise}
  2708. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2709. \chapter{Register Allocation}
  2710. \label{ch:register-allocation-Rvar}
  2711. \index{subject}{register allocation}
  2712. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2713. stack. In this Chapter we learn how to improve the performance of the
  2714. generated code by placing some variables into registers. The CPU can
  2715. access a register in a single cycle, whereas accessing the stack can
  2716. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2717. serves as a running example. The source program is on the left and the
  2718. output of instruction selection is on the right. The program is almost
  2719. in the x86 assembly language but it still uses variables.
  2720. \begin{figure}
  2721. \begin{minipage}{0.45\textwidth}
  2722. Example \LangVar{} program:
  2723. % var_test_28.rkt
  2724. \begin{lstlisting}
  2725. (let ([v 1])
  2726. (let ([w 42])
  2727. (let ([x (+ v 7)])
  2728. (let ([y x])
  2729. (let ([z (+ x w)])
  2730. (+ z (- y)))))))
  2731. \end{lstlisting}
  2732. \end{minipage}
  2733. \begin{minipage}{0.45\textwidth}
  2734. After instruction selection:
  2735. \begin{lstlisting}
  2736. locals-types:
  2737. x : Integer, y : Integer,
  2738. z : Integer, t : Integer,
  2739. v : Integer, w : Integer
  2740. start:
  2741. movq $1, v
  2742. movq $42, w
  2743. movq v, x
  2744. addq $7, x
  2745. movq x, y
  2746. movq x, z
  2747. addq w, z
  2748. movq y, t
  2749. negq t
  2750. movq z, %rax
  2751. addq t, %rax
  2752. jmp conclusion
  2753. \end{lstlisting}
  2754. \end{minipage}
  2755. \caption{A running example for register allocation.}
  2756. \label{fig:reg-eg}
  2757. \end{figure}
  2758. The goal of register allocation is to fit as many variables into
  2759. registers as possible. Some programs have more variables than
  2760. registers so we cannot always map each variable to a different
  2761. register. Fortunately, it is common for different variables to be
  2762. needed during different periods of time during program execution, and
  2763. in such cases several variables can be mapped to the same register.
  2764. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2765. After the variable \code{x} is moved to \code{z} it is no longer
  2766. needed. Variable \code{z}, on the other hand, is used only after this
  2767. point, so \code{x} and \code{z} could share the same register. The
  2768. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2769. where a variable is needed. Once we have that information, we compute
  2770. which variables are needed at the same time, i.e., which ones
  2771. \emph{interfere} with each other, and represent this relation as an
  2772. undirected graph whose vertices are variables and edges indicate when
  2773. two variables interfere (Section~\ref{sec:build-interference}). We
  2774. then model register allocation as a graph coloring problem
  2775. (Section~\ref{sec:graph-coloring}).
  2776. If we run out of registers despite these efforts, we place the
  2777. remaining variables on the stack, similar to what we did in
  2778. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2779. for assigning a variable to a stack location. The decision to spill a
  2780. variable is handled as part of the graph coloring process
  2781. (Section~\ref{sec:graph-coloring}).
  2782. We make the simplifying assumption that each variable is assigned to
  2783. one location (a register or stack address). A more sophisticated
  2784. approach is to assign a variable to one or more locations in different
  2785. regions of the program. For example, if a variable is used many times
  2786. in short sequence and then only used again after many other
  2787. instructions, it could be more efficient to assign the variable to a
  2788. register during the initial sequence and then move it to the stack for
  2789. the rest of its lifetime. We refer the interested reader to
  2790. \citet{Cooper:2011aa} for more information about that approach.
  2791. % discuss prioritizing variables based on how much they are used.
  2792. \section{Registers and Calling Conventions}
  2793. \label{sec:calling-conventions}
  2794. \index{subject}{calling conventions}
  2795. As we perform register allocation, we need to be aware of the
  2796. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  2797. functions calls are performed in x86.
  2798. %
  2799. Even though \LangVar{} does not include programmer-defined functions,
  2800. our generated code includes a \code{main} function that is called by
  2801. the operating system and our generated code contains calls to the
  2802. \code{read\_int} function.
  2803. Function calls require coordination between two pieces of code that
  2804. may be written by different programmers or generated by different
  2805. compilers. Here we follow the System V calling conventions that are
  2806. used by the GNU C compiler on Linux and
  2807. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2808. %
  2809. The calling conventions include rules about how functions share the
  2810. use of registers. In particular, the caller is responsible for freeing
  2811. up some registers prior to the function call for use by the callee.
  2812. These are called the \emph{caller-saved registers}
  2813. \index{subject}{caller-saved registers}
  2814. and they are
  2815. \begin{lstlisting}
  2816. rax rcx rdx rsi rdi r8 r9 r10 r11
  2817. \end{lstlisting}
  2818. On the other hand, the callee is responsible for preserving the values
  2819. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  2820. which are
  2821. \begin{lstlisting}
  2822. rsp rbp rbx r12 r13 r14 r15
  2823. \end{lstlisting}
  2824. We can think about this caller/callee convention from two points of
  2825. view, the caller view and the callee view:
  2826. \begin{itemize}
  2827. \item The caller should assume that all the caller-saved registers get
  2828. overwritten with arbitrary values by the callee. On the other hand,
  2829. the caller can safely assume that all the callee-saved registers
  2830. contain the same values after the call that they did before the
  2831. call.
  2832. \item The callee can freely use any of the caller-saved registers.
  2833. However, if the callee wants to use a callee-saved register, the
  2834. callee must arrange to put the original value back in the register
  2835. prior to returning to the caller. This can be accomplished by saving
  2836. the value to the stack in the prelude of the function and restoring
  2837. the value in the conclusion of the function.
  2838. \end{itemize}
  2839. In x86, registers are also used for passing arguments to a function
  2840. and for the return value. In particular, the first six arguments to a
  2841. function are passed in the following six registers, in this order.
  2842. \begin{lstlisting}
  2843. rdi rsi rdx rcx r8 r9
  2844. \end{lstlisting}
  2845. If there are more than six arguments, then the convention is to use
  2846. space on the frame of the caller for the rest of the
  2847. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2848. need more than six arguments. For now, the only function we care about
  2849. is \code{read\_int} and it takes zero arguments.
  2850. %
  2851. The register \code{rax} is used for the return value of a function.
  2852. The next question is how these calling conventions impact register
  2853. allocation. Consider the \LangVar{} program in
  2854. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2855. example from the caller point of view and then from the callee point
  2856. of view.
  2857. The program makes two calls to the \code{read} function. Also, the
  2858. variable \code{x} is in use during the second call to \code{read}, so
  2859. we need to make sure that the value in \code{x} does not get
  2860. accidentally wiped out by the call to \code{read}. One obvious
  2861. approach is to save all the values in caller-saved registers to the
  2862. stack prior to each function call, and restore them after each
  2863. call. That way, if the register allocator chooses to assign \code{x}
  2864. to a caller-saved register, its value will be preserved across the
  2865. call to \code{read}. However, saving and restoring to the stack is
  2866. relatively slow. If \code{x} is not used many times, it may be better
  2867. to assign \code{x} to a stack location in the first place. Or better
  2868. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2869. register, then it won't need to be saved and restored during function
  2870. calls.
  2871. The approach that we recommend for variables that are in use during a
  2872. function call is to either assign them to callee-saved registers or to
  2873. spill them to the stack. On the other hand, for variables that are not
  2874. in use during a function call, we try the following alternatives in
  2875. order 1) look for an available caller-saved register (to leave room
  2876. for other variables in the callee-saved register), 2) look for a
  2877. callee-saved register, and 3) spill the variable to the stack.
  2878. It is straightforward to implement this approach in a graph coloring
  2879. register allocator. First, we know which variables are in use during
  2880. every function call because we compute that information for every
  2881. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2882. build the interference graph (Section~\ref{sec:build-interference}),
  2883. we can place an edge between each of these variables and the
  2884. caller-saved registers in the interference graph. This will prevent
  2885. the graph coloring algorithm from assigning those variables to
  2886. caller-saved registers.
  2887. Returning to the example in
  2888. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2889. generated x86 code on the right-hand side, focusing on the
  2890. \code{start} block. Notice that variable \code{x} is assigned to
  2891. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2892. place during the second call to \code{read\_int}. Next, notice that
  2893. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2894. because there are no function calls in the remainder of the block.
  2895. Next we analyze the example from the callee point of view, focusing on
  2896. the prelude and conclusion of the \code{main} function. As usual the
  2897. prelude begins with saving the \code{rbp} register to the stack and
  2898. setting the \code{rbp} to the current stack pointer. We now know why
  2899. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2900. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2901. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2902. (\code{x}). The other callee-saved registers are not saved in the
  2903. prelude because they are not used. The prelude subtracts 8 bytes from
  2904. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2905. \code{start} block. Shifting attention to the \code{conclusion}, we
  2906. see that \code{rbx} is restored from the stack with a \code{popq}
  2907. instruction. \index{subject}{prelude}\index{subject}{conclusion}
  2908. \begin{figure}[tp]
  2909. \begin{minipage}{0.45\textwidth}
  2910. Example \LangVar{} program:
  2911. %var_test_14.rkt
  2912. \begin{lstlisting}
  2913. (let ([x (read)])
  2914. (let ([y (read)])
  2915. (+ (+ x y) 42)))
  2916. \end{lstlisting}
  2917. \end{minipage}
  2918. \begin{minipage}{0.45\textwidth}
  2919. Generated x86 assembly:
  2920. \begin{lstlisting}
  2921. start:
  2922. callq read_int
  2923. movq %rax, %rbx
  2924. callq read_int
  2925. movq %rax, %rcx
  2926. addq %rcx, %rbx
  2927. movq %rbx, %rax
  2928. addq $42, %rax
  2929. jmp _conclusion
  2930. .globl main
  2931. main:
  2932. pushq %rbp
  2933. movq %rsp, %rbp
  2934. pushq %rbx
  2935. subq $8, %rsp
  2936. jmp start
  2937. conclusion:
  2938. addq $8, %rsp
  2939. popq %rbx
  2940. popq %rbp
  2941. retq
  2942. \end{lstlisting}
  2943. \end{minipage}
  2944. \caption{An example with function calls.}
  2945. \label{fig:example-calling-conventions}
  2946. \end{figure}
  2947. %\clearpage
  2948. \section{Liveness Analysis}
  2949. \label{sec:liveness-analysis-Rvar}
  2950. \index{subject}{liveness analysis}
  2951. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2952. is, it discovers which variables are in-use in different regions of a
  2953. program.
  2954. %
  2955. A variable or register is \emph{live} at a program point if its
  2956. current value is used at some later point in the program. We
  2957. refer to variables and registers collectively as \emph{locations}.
  2958. %
  2959. Consider the following code fragment in which there are two writes to
  2960. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2961. \begin{center}
  2962. \begin{minipage}{0.96\textwidth}
  2963. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2964. movq $5, a
  2965. movq $30, b
  2966. movq a, c
  2967. movq $10, b
  2968. addq b, c
  2969. \end{lstlisting}
  2970. \end{minipage}
  2971. \end{center}
  2972. The answer is no because \code{a} is live from line 1 to 3 and
  2973. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2974. line 2 is never used because it is overwritten (line 4) before the
  2975. next read (line 5).
  2976. The live locations can be computed by traversing the instruction
  2977. sequence back to front (i.e., backwards in execution order). Let
  2978. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2979. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2980. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2981. locations before instruction $I_k$. We recommend represeting these
  2982. sets with the Racket \code{set} data structure described in
  2983. Figure~\ref{fig:set}.
  2984. \begin{figure}[tp]
  2985. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  2986. \small
  2987. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2988. A \emph{set} is an unordered collection of elements without duplicates.
  2989. Here are some of the operations defined on sets.
  2990. \index{subject}{set}
  2991. \begin{description}
  2992. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  2993. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  2994. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  2995. difference of the two sets.
  2996. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  2997. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  2998. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  2999. \end{description}
  3000. \end{tcolorbox}
  3001. %\end{wrapfigure}
  3002. \caption{The \code{set} data structure.}
  3003. \label{fig:set}
  3004. \end{figure}
  3005. The live locations after an instruction are always the same as the
  3006. live locations before the next instruction.
  3007. \index{subject}{live-after} \index{subject}{live-before}
  3008. \begin{equation} \label{eq:live-after-before-next}
  3009. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3010. \end{equation}
  3011. To start things off, there are no live locations after the last
  3012. instruction, so
  3013. \begin{equation}\label{eq:live-last-empty}
  3014. L_{\mathsf{after}}(n) = \emptyset
  3015. \end{equation}
  3016. We then apply the following rule repeatedly, traversing the
  3017. instruction sequence back to front.
  3018. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3019. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3020. \end{equation}
  3021. where $W(k)$ are the locations written to by instruction $I_k$ and
  3022. $R(k)$ are the locations read by instruction $I_k$.
  3023. There is a special case for \code{jmp} instructions. The locations
  3024. that are live before a \code{jmp} should be the locations in
  3025. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3026. maintaining an alist named \code{label->live} that maps each label to
  3027. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3028. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3029. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3030. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3031. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3032. Let us walk through the above example, applying these formulas
  3033. starting with the instruction on line 5. We collect the answers in
  3034. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3035. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3036. instruction (formula~\ref{eq:live-last-empty}). The
  3037. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3038. because it reads from variables \code{b} and \code{c}
  3039. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3040. \[
  3041. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3042. \]
  3043. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3044. the live-before set from line 5 to be the live-after set for this
  3045. instruction (formula~\ref{eq:live-after-before-next}).
  3046. \[
  3047. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3048. \]
  3049. This move instruction writes to \code{b} and does not read from any
  3050. variables, so we have the following live-before set
  3051. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3052. \[
  3053. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3054. \]
  3055. The live-before for instruction \code{movq a, c}
  3056. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3057. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3058. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3059. variable that is not live and does not read from a variable.
  3060. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3061. because it writes to variable \code{a}.
  3062. \begin{figure}[tbp]
  3063. \begin{minipage}{0.45\textwidth}
  3064. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3065. movq $5, a
  3066. movq $30, b
  3067. movq a, c
  3068. movq $10, b
  3069. addq b, c
  3070. \end{lstlisting}
  3071. \end{minipage}
  3072. \vrule\hspace{10pt}
  3073. \begin{minipage}{0.45\textwidth}
  3074. \begin{align*}
  3075. L_{\mathsf{before}}(1)= \emptyset,
  3076. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3077. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3078. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3079. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3080. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3081. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3082. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3083. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3084. L_{\mathsf{after}}(5)= \emptyset
  3085. \end{align*}
  3086. \end{minipage}
  3087. \caption{Example output of liveness analysis on a short example.}
  3088. \label{fig:liveness-example-0}
  3089. \end{figure}
  3090. \begin{exercise}\normalfont
  3091. Perform liveness analysis on the running example in
  3092. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3093. sets for each instruction. Compare your answers to the solution
  3094. shown in Figure~\ref{fig:live-eg}.
  3095. \end{exercise}
  3096. \begin{figure}[tp]
  3097. \hspace{20pt}
  3098. \begin{minipage}{0.45\textwidth}
  3099. \begin{lstlisting}
  3100. |$\{\ttm{rsp}\}$|
  3101. movq $1, v
  3102. |$\{\ttm{v},\ttm{rsp}\}$|
  3103. movq $42, w
  3104. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3105. movq v, x
  3106. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3107. addq $7, x
  3108. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3109. movq x, y
  3110. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3111. movq x, z
  3112. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3113. addq w, z
  3114. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3115. movq y, t
  3116. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3117. negq t
  3118. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3119. movq z, %rax
  3120. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3121. addq t, %rax
  3122. |$\{\ttm{rax},\ttm{rsp}\}$|
  3123. jmp conclusion
  3124. \end{lstlisting}
  3125. \end{minipage}
  3126. \caption{The running example annotated with live-after sets.}
  3127. \label{fig:live-eg}
  3128. \end{figure}
  3129. \begin{exercise}\normalfont
  3130. Implement the \code{uncover-live} pass. Store the sequence of
  3131. live-after sets in the $\itm{info}$ field of the \code{Block}
  3132. structure.
  3133. %
  3134. We recommend creating an auxiliary function that takes a list of
  3135. instructions and an initial live-after set (typically empty) and
  3136. returns the list of live-after sets.
  3137. %
  3138. We also recommend creating auxiliary functions to 1) compute the set
  3139. of locations that appear in an \Arg{}, 2) compute the locations read
  3140. by an instruction (the $R$ function), and 3) the locations written by
  3141. an instruction (the $W$ function). The \code{callq} instruction should
  3142. include all of the caller-saved registers in its write-set $W$ because
  3143. the calling convention says that those registers may be written to
  3144. during the function call. Likewise, the \code{callq} instruction
  3145. should include the appropriate argument-passing registers in its
  3146. read-set $R$, depending on the arity of the function being
  3147. called. (This is why the abstract syntax for \code{callq} includes the
  3148. arity.)
  3149. \end{exercise}
  3150. %\clearpage
  3151. \section{Build the Interference Graph}
  3152. \label{sec:build-interference}
  3153. \begin{figure}[tp]
  3154. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3155. \small
  3156. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3157. A \emph{graph} is a collection of vertices and edges where each
  3158. edge connects two vertices. A graph is \emph{directed} if each
  3159. edge points from a source to a target. Otherwise the graph is
  3160. \emph{undirected}.
  3161. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3162. \begin{description}
  3163. %% We currently don't use directed graphs. We instead use
  3164. %% directed multi-graphs. -Jeremy
  3165. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3166. directed graph from a list of edges. Each edge is a list
  3167. containing the source and target vertex.
  3168. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3169. undirected graph from a list of edges. Each edge is represented by
  3170. a list containing two vertices.
  3171. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3172. inserts a vertex into the graph.
  3173. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3174. inserts an edge between the two vertices.
  3175. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3176. returns a sequence of vertices adjacent to the vertex.
  3177. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3178. returns a sequence of all vertices in the graph.
  3179. \end{description}
  3180. \end{tcolorbox}
  3181. %\end{wrapfigure}
  3182. \caption{The Racket \code{graph} package.}
  3183. \label{fig:graph}
  3184. \end{figure}
  3185. Based on the liveness analysis, we know where each location is live.
  3186. However, during register allocation, we need to answer questions of
  3187. the specific form: are locations $u$ and $v$ live at the same time?
  3188. (And therefore cannot be assigned to the same register.) To make this
  3189. question more efficient to answer, we create an explicit data
  3190. structure, an \emph{interference graph}\index{subject}{interference
  3191. graph}. An interference graph is an undirected graph that has an
  3192. edge between two locations if they are live at the same time, that is,
  3193. if they interfere with each other. We recommend using the Racket
  3194. \code{graph} package (Figure~\ref{fig:graph}) to represent
  3195. the interference graph.
  3196. An obvious way to compute the interference graph is to look at the set
  3197. of live locations between each instruction and the next and add an edge to the graph
  3198. for every pair of variables in the same set. This approach is less
  3199. than ideal for two reasons. First, it can be expensive because it
  3200. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  3201. locations. Second, in the special case where two locations hold the
  3202. same value (because one was assigned to the other), they can be live
  3203. at the same time without interfering with each other.
  3204. A better way to compute the interference graph is to focus on
  3205. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3206. must not overwrite something in a live location. So for each
  3207. instruction, we create an edge between the locations being written to
  3208. and the live locations. (Except that one should not create self
  3209. edges.) Note that for the \key{callq} instruction, we consider all of
  3210. the caller-saved registers as being written to, so an edge is added
  3211. between every live variable and every caller-saved register. For
  3212. \key{movq}, we deal with the above-mentioned special case by not
  3213. adding an edge between a live variable $v$ and the destination if $v$
  3214. matches the source. So we have the following two rules.
  3215. \begin{enumerate}
  3216. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3217. $d$, then add the edge $(d,v)$ for every $v \in
  3218. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3219. \item For any other instruction $I_k$, for every $d \in W(k)$
  3220. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3221. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3222. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3223. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3224. %% \item If instruction $I_k$ is of the form \key{callq}
  3225. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3226. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3227. \end{enumerate}
  3228. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3229. the above rules to each instruction. We highlight a few of the
  3230. instructions. The first instruction is \lstinline{movq $1, v} and the
  3231. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  3232. interferes with \code{rsp}.
  3233. %
  3234. The fourth instruction is \lstinline{addq $7, x} and the live-after
  3235. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  3236. interferes with \ttm{w} and \ttm{rsp}.
  3237. %
  3238. The next instruction is \lstinline{movq x, y} and the live-after set
  3239. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  3240. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  3241. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  3242. same value. Figure~\ref{fig:interference-results} lists the
  3243. interference results for all of the instructions and the resulting
  3244. interference graph is shown in Figure~\ref{fig:interfere}.
  3245. \begin{figure}[tbp]
  3246. \begin{quote}
  3247. \begin{tabular}{ll}
  3248. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3249. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3250. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3251. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3252. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3253. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3254. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3255. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3256. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3257. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3258. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3259. \lstinline!jmp conclusion!& no interference.
  3260. \end{tabular}
  3261. \end{quote}
  3262. \caption{Interference results for the running example.}
  3263. \label{fig:interference-results}
  3264. \end{figure}
  3265. \begin{figure}[tbp]
  3266. \large
  3267. \[
  3268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3269. \node (rax) at (0,0) {$\ttm{rax}$};
  3270. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3271. \node (t1) at (0,2) {$\ttm{t}$};
  3272. \node (z) at (3,2) {$\ttm{z}$};
  3273. \node (x) at (6,2) {$\ttm{x}$};
  3274. \node (y) at (3,0) {$\ttm{y}$};
  3275. \node (w) at (6,0) {$\ttm{w}$};
  3276. \node (v) at (9,0) {$\ttm{v}$};
  3277. \draw (t1) to (rax);
  3278. \draw (t1) to (z);
  3279. \draw (z) to (y);
  3280. \draw (z) to (w);
  3281. \draw (x) to (w);
  3282. \draw (y) to (w);
  3283. \draw (v) to (w);
  3284. \draw (v) to (rsp);
  3285. \draw (w) to (rsp);
  3286. \draw (x) to (rsp);
  3287. \draw (y) to (rsp);
  3288. \path[-.,bend left=15] (z) edge node {} (rsp);
  3289. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3290. \draw (rax) to (rsp);
  3291. \end{tikzpicture}
  3292. \]
  3293. \caption{The interference graph of the example program.}
  3294. \label{fig:interfere}
  3295. \end{figure}
  3296. %% Our next concern is to choose a data structure for representing the
  3297. %% interference graph. There are many choices for how to represent a
  3298. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3299. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3300. %% data structure is to study the algorithm that uses the data structure,
  3301. %% determine what operations need to be performed, and then choose the
  3302. %% data structure that provide the most efficient implementations of
  3303. %% those operations. Often times the choice of data structure can have an
  3304. %% effect on the time complexity of the algorithm, as it does here. If
  3305. %% you skim the next section, you will see that the register allocation
  3306. %% algorithm needs to ask the graph for all of its vertices and, given a
  3307. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3308. %% correct choice of graph representation is that of an adjacency
  3309. %% list. There are helper functions in \code{utilities.rkt} for
  3310. %% representing graphs using the adjacency list representation:
  3311. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3312. %% (Appendix~\ref{appendix:utilities}).
  3313. %% %
  3314. %% \margincomment{\footnotesize To do: change to use the
  3315. %% Racket graph library. \\ --Jeremy}
  3316. %% %
  3317. %% In particular, those functions use a hash table to map each vertex to
  3318. %% the set of adjacent vertices, and the sets are represented using
  3319. %% Racket's \key{set}, which is also a hash table.
  3320. \begin{exercise}\normalfont
  3321. Implement the compiler pass named \code{build-interference} according
  3322. to the algorithm suggested above. We recommend using the \code{graph}
  3323. package to create and inspect the interference graph. The output
  3324. graph of this pass should be stored in the $\itm{info}$ field of the
  3325. program, under the key \code{conflicts}.
  3326. \end{exercise}
  3327. \section{Graph Coloring via Sudoku}
  3328. \label{sec:graph-coloring}
  3329. \index{subject}{graph coloring}
  3330. \index{subject}{Sudoku}
  3331. \index{subject}{color}
  3332. We come to the main event, mapping variables to registers and stack
  3333. locations. Variables that interfere with each other must be mapped to
  3334. different locations. In terms of the interference graph, this means
  3335. that adjacent vertices must be mapped to different locations. If we
  3336. think of locations as colors, the register allocation problem becomes
  3337. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3338. The reader may be more familiar with the graph coloring problem than he
  3339. or she realizes; the popular game of Sudoku is an instance of the
  3340. graph coloring problem. The following describes how to build a graph
  3341. out of an initial Sudoku board.
  3342. \begin{itemize}
  3343. \item There is one vertex in the graph for each Sudoku square.
  3344. \item There is an edge between two vertices if the corresponding squares
  3345. are in the same row, in the same column, or if the squares are in
  3346. the same $3\times 3$ region.
  3347. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3348. \item Based on the initial assignment of numbers to squares in the
  3349. Sudoku board, assign the corresponding colors to the corresponding
  3350. vertices in the graph.
  3351. \end{itemize}
  3352. If you can color the remaining vertices in the graph with the nine
  3353. colors, then you have also solved the corresponding game of Sudoku.
  3354. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3355. the corresponding graph with colored vertices. We map the Sudoku
  3356. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  3357. sampling of the vertices (the colored ones) because showing edges for
  3358. all of the vertices would make the graph unreadable.
  3359. \begin{figure}[tbp]
  3360. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3361. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  3362. \caption{A Sudoku game board and the corresponding colored graph.}
  3363. \label{fig:sudoku-graph}
  3364. \end{figure}
  3365. Some techniques for playing Sudoku correspond to heuristics used in
  3366. graph coloring algorithms. For example, one of the basic techniques
  3367. for Sudoku is called Pencil Marks. The idea is to use a process of
  3368. elimination to determine what numbers are no longer available for a
  3369. square and write down those numbers in the square (writing very
  3370. small). For example, if the number $1$ is assigned to a square, then
  3371. write the pencil mark $1$ in all the squares in the same row, column,
  3372. and region to indicate that $1$ is no longer an option for those other
  3373. squares.
  3374. %
  3375. The Pencil Marks technique corresponds to the notion of
  3376. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  3377. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3378. are no longer available. In graph terminology, we have the following
  3379. definition:
  3380. \begin{equation*}
  3381. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3382. \text{ and } \mathrm{color}(v) = c \}
  3383. \end{equation*}
  3384. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3385. edge with $u$.
  3386. Using the Pencil Marks technique leads to a simple strategy for
  3387. filling in numbers: if there is a square with only one possible number
  3388. left, then choose that number! But what if there are no squares with
  3389. only one possibility left? One brute-force approach is to try them
  3390. all: choose the first one and if that ultimately leads to a solution,
  3391. great. If not, backtrack and choose the next possibility. One good
  3392. thing about Pencil Marks is that it reduces the degree of branching in
  3393. the search tree. Nevertheless, backtracking can be terribly time
  3394. consuming. One way to reduce the amount of backtracking is to use the
  3395. most-constrained-first heuristic. That is, when choosing a square,
  3396. always choose one with the fewest possibilities left (the vertex with
  3397. the highest saturation). The idea is that choosing highly constrained
  3398. squares earlier rather than later is better because later on there may
  3399. not be any possibilities left in the highly saturated squares.
  3400. However, register allocation is easier than Sudoku because the
  3401. register allocator can map variables to stack locations when the
  3402. registers run out. Thus, it makes sense to replace backtracking with
  3403. greedy search: make the best choice at the time and keep going. We
  3404. still wish to minimize the number of colors needed, so we use the
  3405. most-constrained-first heuristic in the greedy search.
  3406. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3407. algorithm for register allocation based on saturation and the
  3408. most-constrained-first heuristic. It is roughly equivalent to the
  3409. DSATUR
  3410. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3411. as in Sudoku, the algorithm represents colors with integers. The
  3412. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3413. for register allocation. The integers $k$ and larger correspond to
  3414. stack locations. The registers that are not used for register
  3415. allocation, such as \code{rax}, are assigned to negative integers. In
  3416. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3417. %% One might wonder why we include registers at all in the liveness
  3418. %% analysis and interference graph. For example, we never allocate a
  3419. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3420. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3421. %% to use register for passing arguments to functions, it will be
  3422. %% necessary for those registers to appear in the interference graph
  3423. %% because those registers will also be assigned to variables, and we
  3424. %% don't want those two uses to encroach on each other. Regarding
  3425. %% registers such as \code{rax} and \code{rsp} that are not used for
  3426. %% variables, we could omit them from the interference graph but that
  3427. %% would require adding special cases to our algorithm, which would
  3428. %% complicate the logic for little gain.
  3429. \begin{figure}[btp]
  3430. \centering
  3431. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3432. Algorithm: DSATUR
  3433. Input: a graph |$G$|
  3434. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3435. |$W \gets \mathrm{vertices}(G)$|
  3436. while |$W \neq \emptyset$| do
  3437. pick a vertex |$u$| from |$W$| with the highest saturation,
  3438. breaking ties randomly
  3439. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3440. |$\mathrm{color}[u] \gets c$|
  3441. |$W \gets W - \{u\}$|
  3442. \end{lstlisting}
  3443. \caption{The saturation-based greedy graph coloring algorithm.}
  3444. \label{fig:satur-algo}
  3445. \end{figure}
  3446. With the DSATUR algorithm in hand, let us return to the running
  3447. example and consider how to color the interference graph in
  3448. Figure~\ref{fig:interfere}.
  3449. %
  3450. We start by assigning the register nodes to their own color. For
  3451. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3452. assigned $-2$. The variables are not yet colored, so they are
  3453. annotated with a dash. We then update the saturation for vertices that
  3454. are adjacent to a register, obtaining the following annotated
  3455. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3456. it interferes with both \code{rax} and \code{rsp}.
  3457. \[
  3458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3459. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3460. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3461. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3462. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3463. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3464. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3465. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3466. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3467. \draw (t1) to (rax);
  3468. \draw (t1) to (z);
  3469. \draw (z) to (y);
  3470. \draw (z) to (w);
  3471. \draw (x) to (w);
  3472. \draw (y) to (w);
  3473. \draw (v) to (w);
  3474. \draw (v) to (rsp);
  3475. \draw (w) to (rsp);
  3476. \draw (x) to (rsp);
  3477. \draw (y) to (rsp);
  3478. \path[-.,bend left=15] (z) edge node {} (rsp);
  3479. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3480. \draw (rax) to (rsp);
  3481. \end{tikzpicture}
  3482. \]
  3483. The algorithm says to select a maximally saturated vertex. So we pick
  3484. $\ttm{t}$ and color it with the first available integer, which is
  3485. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3486. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3487. \[
  3488. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3489. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3490. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3491. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3492. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3493. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3494. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3495. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3496. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3497. \draw (t1) to (rax);
  3498. \draw (t1) to (z);
  3499. \draw (z) to (y);
  3500. \draw (z) to (w);
  3501. \draw (x) to (w);
  3502. \draw (y) to (w);
  3503. \draw (v) to (w);
  3504. \draw (v) to (rsp);
  3505. \draw (w) to (rsp);
  3506. \draw (x) to (rsp);
  3507. \draw (y) to (rsp);
  3508. \path[-.,bend left=15] (z) edge node {} (rsp);
  3509. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3510. \draw (rax) to (rsp);
  3511. \end{tikzpicture}
  3512. \]
  3513. We repeat the process, selecting the next maximally saturated vertex,
  3514. which is \code{z}, and color it with the first available number, which
  3515. is $1$. We add $1$ to the saturation for the neighboring vertices
  3516. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3517. \[
  3518. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3519. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3520. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3521. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3522. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3523. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3524. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3525. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3526. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3527. \draw (t1) to (rax);
  3528. \draw (t1) to (z);
  3529. \draw (z) to (y);
  3530. \draw (z) to (w);
  3531. \draw (x) to (w);
  3532. \draw (y) to (w);
  3533. \draw (v) to (w);
  3534. \draw (v) to (rsp);
  3535. \draw (w) to (rsp);
  3536. \draw (x) to (rsp);
  3537. \draw (y) to (rsp);
  3538. \path[-.,bend left=15] (z) edge node {} (rsp);
  3539. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3540. \draw (rax) to (rsp);
  3541. \end{tikzpicture}
  3542. \]
  3543. The most saturated vertices are now \code{w} and \code{y}. We color
  3544. \code{w} with the first available color, which is $0$.
  3545. \[
  3546. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3547. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3548. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3549. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3550. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3551. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3552. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3553. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3554. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3555. \draw (t1) to (rax);
  3556. \draw (t1) to (z);
  3557. \draw (z) to (y);
  3558. \draw (z) to (w);
  3559. \draw (x) to (w);
  3560. \draw (y) to (w);
  3561. \draw (v) to (w);
  3562. \draw (v) to (rsp);
  3563. \draw (w) to (rsp);
  3564. \draw (x) to (rsp);
  3565. \draw (y) to (rsp);
  3566. \path[-.,bend left=15] (z) edge node {} (rsp);
  3567. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3568. \draw (rax) to (rsp);
  3569. \end{tikzpicture}
  3570. \]
  3571. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3572. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3573. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3574. and \code{z}, whose colors are $0$ and $1$ respectively.
  3575. \[
  3576. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3577. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3578. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3579. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3580. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3581. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3582. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3583. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3584. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3585. \draw (t1) to (rax);
  3586. \draw (t1) to (z);
  3587. \draw (z) to (y);
  3588. \draw (z) to (w);
  3589. \draw (x) to (w);
  3590. \draw (y) to (w);
  3591. \draw (v) to (w);
  3592. \draw (v) to (rsp);
  3593. \draw (w) to (rsp);
  3594. \draw (x) to (rsp);
  3595. \draw (y) to (rsp);
  3596. \path[-.,bend left=15] (z) edge node {} (rsp);
  3597. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3598. \draw (rax) to (rsp);
  3599. \end{tikzpicture}
  3600. \]
  3601. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3602. \[
  3603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3604. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3605. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3606. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3607. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3608. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3609. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3610. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3611. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3612. \draw (t1) to (rax);
  3613. \draw (t1) to (z);
  3614. \draw (z) to (y);
  3615. \draw (z) to (w);
  3616. \draw (x) to (w);
  3617. \draw (y) to (w);
  3618. \draw (v) to (w);
  3619. \draw (v) to (rsp);
  3620. \draw (w) to (rsp);
  3621. \draw (x) to (rsp);
  3622. \draw (y) to (rsp);
  3623. \path[-.,bend left=15] (z) edge node {} (rsp);
  3624. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3625. \draw (rax) to (rsp);
  3626. \end{tikzpicture}
  3627. \]
  3628. In the last step of the algorithm, we color \code{x} with $1$.
  3629. \[
  3630. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3631. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3632. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3633. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3634. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3635. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3636. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3637. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3638. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3639. \draw (t1) to (rax);
  3640. \draw (t1) to (z);
  3641. \draw (z) to (y);
  3642. \draw (z) to (w);
  3643. \draw (x) to (w);
  3644. \draw (y) to (w);
  3645. \draw (v) to (w);
  3646. \draw (v) to (rsp);
  3647. \draw (w) to (rsp);
  3648. \draw (x) to (rsp);
  3649. \draw (y) to (rsp);
  3650. \path[-.,bend left=15] (z) edge node {} (rsp);
  3651. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3652. \draw (rax) to (rsp);
  3653. \end{tikzpicture}
  3654. \]
  3655. We recommend creating an auxiliary function named \code{color-graph}
  3656. that takes an interference graph and a list of all the variables in
  3657. the program. This function should return a mapping of variables to
  3658. their colors (represented as natural numbers). By creating this helper
  3659. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3660. when we add support for functions.
  3661. To prioritize the processing of highly saturated nodes inside the
  3662. \code{color-graph} function, we recommend using the priority queue
  3663. data structure described in Figure~\ref{fig:priority-queue}. In
  3664. addition, you will need to maintain a mapping from variables to their
  3665. ``handles'' in the priority queue so that you can notify the priority
  3666. queue when their saturation changes.
  3667. \begin{figure}[tp]
  3668. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  3669. \small
  3670. \begin{tcolorbox}[title=Priority Queue]
  3671. A \emph{priority queue} is a collection of items in which the
  3672. removal of items is governed by priority. In a ``min'' queue,
  3673. lower priority items are removed first. An implementation is in
  3674. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  3675. queue} \index{subject}{minimum priority queue}
  3676. \begin{description}
  3677. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3678. priority queue that uses the $\itm{cmp}$ predicate to determine
  3679. whether its first argument has lower or equal priority to its
  3680. second argument.
  3681. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3682. items in the queue.
  3683. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3684. the item into the queue and returns a handle for the item in the
  3685. queue.
  3686. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3687. the lowest priority.
  3688. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3689. notifies the queue that the priority has decreased for the item
  3690. associated with the given handle.
  3691. \end{description}
  3692. \end{tcolorbox}
  3693. %\end{wrapfigure}
  3694. \caption{The priority queue data structure.}
  3695. \label{fig:priority-queue}
  3696. \end{figure}
  3697. With the coloring complete, we finalize the assignment of variables to
  3698. registers and stack locations. We map the first $k$ colors to the $k$
  3699. registers and the rest of the colors to stack locations. Suppose for
  3700. the moment that we have just one register to use for register
  3701. allocation, \key{rcx}. Then we have the following map from colors to
  3702. locations.
  3703. \[
  3704. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3705. \]
  3706. Composing this mapping with the coloring, we arrive at the following
  3707. assignment of variables to locations.
  3708. \begin{gather*}
  3709. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3710. \ttm{w} \mapsto \key{\%rcx}, \,
  3711. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3712. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3713. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3714. \ttm{t} \mapsto \key{\%rcx} \}
  3715. \end{gather*}
  3716. Adapt the code from the \code{assign-homes} pass
  3717. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3718. assigned location. Applying the above assignment to our running
  3719. example, on the left, yields the program on the right.
  3720. % why frame size of 32? -JGS
  3721. \begin{center}
  3722. \begin{minipage}{0.3\textwidth}
  3723. \begin{lstlisting}
  3724. movq $1, v
  3725. movq $42, w
  3726. movq v, x
  3727. addq $7, x
  3728. movq x, y
  3729. movq x, z
  3730. addq w, z
  3731. movq y, t
  3732. negq t
  3733. movq z, %rax
  3734. addq t, %rax
  3735. jmp conclusion
  3736. \end{lstlisting}
  3737. \end{minipage}
  3738. $\Rightarrow\qquad$
  3739. \begin{minipage}{0.45\textwidth}
  3740. \begin{lstlisting}
  3741. movq $1, -8(%rbp)
  3742. movq $42, %rcx
  3743. movq -8(%rbp), -8(%rbp)
  3744. addq $7, -8(%rbp)
  3745. movq -8(%rbp), -16(%rbp)
  3746. movq -8(%rbp), -8(%rbp)
  3747. addq %rcx, -8(%rbp)
  3748. movq -16(%rbp), %rcx
  3749. negq %rcx
  3750. movq -8(%rbp), %rax
  3751. addq %rcx, %rax
  3752. jmp conclusion
  3753. \end{lstlisting}
  3754. \end{minipage}
  3755. \end{center}
  3756. \begin{exercise}\normalfont
  3757. %
  3758. Implement the compiler pass \code{allocate-registers}.
  3759. %
  3760. Create five programs that exercise all of the register allocation
  3761. algorithm, including spilling variables to the stack.
  3762. %
  3763. Replace \code{assign-homes} in the list of \code{passes} in the
  3764. \code{run-tests.rkt} script with the three new passes:
  3765. \code{uncover-live}, \code{build-interference}, and
  3766. \code{allocate-registers}.
  3767. %
  3768. Temporarily remove the \code{print-x86} pass from the list of passes
  3769. and the call to \code{compiler-tests}.
  3770. %
  3771. Run the script to test the register allocator.
  3772. \end{exercise}
  3773. \section{Patch Instructions}
  3774. \label{sec:patch-instructions}
  3775. The remaining step in the compilation to x86 is to ensure that the
  3776. instructions have at most one argument that is a memory access.
  3777. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3778. is problematic. The fix is to first move \code{-8(\%rbp)}
  3779. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3780. %
  3781. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3782. problematic, but they can be fixed by simply deleting them. In
  3783. general, we recommend deleting all the trivial moves whose source and
  3784. destination are the same location.
  3785. %
  3786. The following is the output of \code{patch-instructions} on the
  3787. running example.
  3788. \begin{center}
  3789. \begin{minipage}{0.4\textwidth}
  3790. \begin{lstlisting}
  3791. movq $1, -8(%rbp)
  3792. movq $42, %rcx
  3793. movq -8(%rbp), -8(%rbp)
  3794. addq $7, -8(%rbp)
  3795. movq -8(%rbp), -16(%rbp)
  3796. movq -8(%rbp), -8(%rbp)
  3797. addq %rcx, -8(%rbp)
  3798. movq -16(%rbp), %rcx
  3799. negq %rcx
  3800. movq -8(%rbp), %rax
  3801. addq %rcx, %rax
  3802. jmp conclusion
  3803. \end{lstlisting}
  3804. \end{minipage}
  3805. $\Rightarrow\qquad$
  3806. \begin{minipage}{0.45\textwidth}
  3807. \begin{lstlisting}
  3808. movq $1, -8(%rbp)
  3809. movq $42, %rcx
  3810. addq $7, -8(%rbp)
  3811. movq -8(%rbp), %rax
  3812. movq %rax, -16(%rbp)
  3813. addq %rcx, -8(%rbp)
  3814. movq -16(%rbp), %rcx
  3815. negq %rcx
  3816. movq -8(%rbp), %rax
  3817. addq %rcx, %rax
  3818. jmp conclusion
  3819. \end{lstlisting}
  3820. \end{minipage}
  3821. \end{center}
  3822. \begin{exercise}\normalfont
  3823. %
  3824. Implement the \code{patch-instructions} compiler pass.
  3825. %
  3826. Insert it after \code{allocate-registers} in the list of \code{passes}
  3827. in the \code{run-tests.rkt} script.
  3828. %
  3829. Run the script to test the \code{patch-instructions} pass.
  3830. \end{exercise}
  3831. \section{Print x86}
  3832. \label{sec:print-x86-reg-alloc}
  3833. \index{subject}{calling conventions}
  3834. \index{subject}{prelude}\index{subject}{conclusion}
  3835. Recall that the \code{print-x86} pass generates the prelude and
  3836. conclusion instructions to satisfy the x86 calling conventions
  3837. (Section~\ref{sec:calling-conventions}). With the addition of the
  3838. register allocator, the callee-saved registers used by the register
  3839. allocator must be saved in the prelude and restored in the conclusion.
  3840. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3841. of \code{X86Program} named \code{used-callee} that stores the set of
  3842. callee-saved registers that were assigned to variables. The
  3843. \code{print-x86} pass can then access this information to decide which
  3844. callee-saved registers need to be saved and restored.
  3845. %
  3846. When calculating the size of the frame to adjust the \code{rsp} in the
  3847. prelude, make sure to take into account the space used for saving the
  3848. callee-saved registers. Also, don't forget that the frame needs to be
  3849. a multiple of 16 bytes!
  3850. An overview of all of the passes involved in register allocation is
  3851. shown in Figure~\ref{fig:reg-alloc-passes}.
  3852. \begin{figure}[tbp]
  3853. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3854. \node (Rvar) at (0,2) {\large \LangVar{}};
  3855. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3856. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3857. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3858. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3859. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3860. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3861. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3862. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3863. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3864. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3865. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3866. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3867. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3868. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3869. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3870. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3871. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3872. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3873. \end{tikzpicture}
  3874. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3875. \label{fig:reg-alloc-passes}
  3876. \end{figure}
  3877. \begin{exercise}\normalfont
  3878. Update the \code{print-x86} pass as described in this section.
  3879. %
  3880. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3881. list of passes and the call to \code{compiler-tests}.
  3882. %
  3883. Run the script to test the complete compiler for \LangVar{} that
  3884. performs register allocation.
  3885. \end{exercise}
  3886. \section{Challenge: Move Biasing}
  3887. \label{sec:move-biasing}
  3888. \index{subject}{move biasing}
  3889. This section describes an enhancement to the register allocator for
  3890. students looking for an extra challenge or who have a deeper interest
  3891. in register allocation.
  3892. To motivate the need for move biasing we return to the running example
  3893. but this time use all of the general purpose registers. So we have
  3894. the following mapping of color numbers to registers.
  3895. \[
  3896. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3897. \]
  3898. Using the same assignment of variables to color numbers that was
  3899. produced by the register allocator described in the last section, we
  3900. get the following program.
  3901. \begin{center}
  3902. \begin{minipage}{0.3\textwidth}
  3903. \begin{lstlisting}
  3904. movq $1, v
  3905. movq $42, w
  3906. movq v, x
  3907. addq $7, x
  3908. movq x, y
  3909. movq x, z
  3910. addq w, z
  3911. movq y, t
  3912. negq t
  3913. movq z, %rax
  3914. addq t, %rax
  3915. jmp conclusion
  3916. \end{lstlisting}
  3917. \end{minipage}
  3918. $\Rightarrow\qquad$
  3919. \begin{minipage}{0.45\textwidth}
  3920. \begin{lstlisting}
  3921. movq $1, %rdx
  3922. movq $42, %rcx
  3923. movq %rdx, %rdx
  3924. addq $7, %rdx
  3925. movq %rdx, %rsi
  3926. movq %rdx, %rdx
  3927. addq %rcx, %rdx
  3928. movq %rsi, %rcx
  3929. negq %rcx
  3930. movq %rdx, %rax
  3931. addq %rcx, %rax
  3932. jmp conclusion
  3933. \end{lstlisting}
  3934. \end{minipage}
  3935. \end{center}
  3936. In the above output code there are two \key{movq} instructions that
  3937. can be removed because their source and target are the same. However,
  3938. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3939. register, we could instead remove three \key{movq} instructions. We
  3940. can accomplish this by taking into account which variables appear in
  3941. \key{movq} instructions with which other variables.
  3942. We say that two variables $p$ and $q$ are \emph{move
  3943. related}\index{subject}{move related} if they participate together in a
  3944. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3945. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3946. for a variable, it should prefer a color that has already been used
  3947. for a move-related variable (assuming that they do not interfere). Of
  3948. course, this preference should not override the preference for
  3949. registers over stack locations. This preference should be used as a
  3950. tie breaker when choosing between registers or when choosing between
  3951. stack locations.
  3952. We recommend representing the move relationships in a graph, similar
  3953. to how we represented interference. The following is the \emph{move
  3954. graph} for our running example.
  3955. \[
  3956. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3957. \node (rax) at (0,0) {$\ttm{rax}$};
  3958. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3959. \node (t) at (0,2) {$\ttm{t}$};
  3960. \node (z) at (3,2) {$\ttm{z}$};
  3961. \node (x) at (6,2) {$\ttm{x}$};
  3962. \node (y) at (3,0) {$\ttm{y}$};
  3963. \node (w) at (6,0) {$\ttm{w}$};
  3964. \node (v) at (9,0) {$\ttm{v}$};
  3965. \draw (v) to (x);
  3966. \draw (x) to (y);
  3967. \draw (x) to (z);
  3968. \draw (y) to (t);
  3969. \end{tikzpicture}
  3970. \]
  3971. Now we replay the graph coloring, pausing to see the coloring of
  3972. \code{y}. Recall the following configuration. The most saturated vertices
  3973. were \code{w} and \code{y}.
  3974. \[
  3975. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3976. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3977. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3978. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3979. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3980. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3981. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3982. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3983. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3984. \draw (t1) to (rax);
  3985. \draw (t1) to (z);
  3986. \draw (z) to (y);
  3987. \draw (z) to (w);
  3988. \draw (x) to (w);
  3989. \draw (y) to (w);
  3990. \draw (v) to (w);
  3991. \draw (v) to (rsp);
  3992. \draw (w) to (rsp);
  3993. \draw (x) to (rsp);
  3994. \draw (y) to (rsp);
  3995. \path[-.,bend left=15] (z) edge node {} (rsp);
  3996. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3997. \draw (rax) to (rsp);
  3998. \end{tikzpicture}
  3999. \]
  4000. %
  4001. Last time we chose to color \code{w} with $0$. But this time we see
  4002. that \code{w} is not move related to any vertex, but \code{y} is move
  4003. related to \code{t}. So we choose to color \code{y} the same color as
  4004. \code{t}, $0$.
  4005. \[
  4006. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4007. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4008. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4009. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4010. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4011. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4012. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  4013. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  4014. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4015. \draw (t1) to (rax);
  4016. \draw (t1) to (z);
  4017. \draw (z) to (y);
  4018. \draw (z) to (w);
  4019. \draw (x) to (w);
  4020. \draw (y) to (w);
  4021. \draw (v) to (w);
  4022. \draw (v) to (rsp);
  4023. \draw (w) to (rsp);
  4024. \draw (x) to (rsp);
  4025. \draw (y) to (rsp);
  4026. \path[-.,bend left=15] (z) edge node {} (rsp);
  4027. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4028. \draw (rax) to (rsp);
  4029. \end{tikzpicture}
  4030. \]
  4031. Now \code{w} is the most saturated, so we color it $2$.
  4032. \[
  4033. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4034. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4035. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4036. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4037. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4038. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  4039. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4040. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4041. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  4042. \draw (t1) to (rax);
  4043. \draw (t1) to (z);
  4044. \draw (z) to (y);
  4045. \draw (z) to (w);
  4046. \draw (x) to (w);
  4047. \draw (y) to (w);
  4048. \draw (v) to (w);
  4049. \draw (v) to (rsp);
  4050. \draw (w) to (rsp);
  4051. \draw (x) to (rsp);
  4052. \draw (y) to (rsp);
  4053. \path[-.,bend left=15] (z) edge node {} (rsp);
  4054. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4055. \draw (rax) to (rsp);
  4056. \end{tikzpicture}
  4057. \]
  4058. At this point, vertices \code{x} and \code{v} are most saturated, but
  4059. \code{x} is move related to \code{y} and \code{z}, so we color
  4060. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  4061. \[
  4062. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4063. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4064. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4065. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4066. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4067. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  4068. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4069. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4070. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  4071. \draw (t1) to (rax);
  4072. \draw (t) to (z);
  4073. \draw (z) to (y);
  4074. \draw (z) to (w);
  4075. \draw (x) to (w);
  4076. \draw (y) to (w);
  4077. \draw (v) to (w);
  4078. \draw (v) to (rsp);
  4079. \draw (w) to (rsp);
  4080. \draw (x) to (rsp);
  4081. \draw (y) to (rsp);
  4082. \path[-.,bend left=15] (z) edge node {} (rsp);
  4083. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4084. \draw (rax) to (rsp);
  4085. \end{tikzpicture}
  4086. \]
  4087. So we have the following assignment of variables to registers.
  4088. \begin{gather*}
  4089. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  4090. \ttm{w} \mapsto \key{\%rsi}, \,
  4091. \ttm{x} \mapsto \key{\%rcx}, \,
  4092. \ttm{y} \mapsto \key{\%rcx}, \,
  4093. \ttm{z} \mapsto \key{\%rdx}, \,
  4094. \ttm{t} \mapsto \key{\%rcx} \}
  4095. \end{gather*}
  4096. We apply this register assignment to the running example, on the left,
  4097. to obtain the code in the middle. The \code{patch-instructions} then
  4098. removes the three trivial moves to obtain the code on the right.
  4099. \begin{minipage}{0.25\textwidth}
  4100. \begin{lstlisting}
  4101. movq $1, v
  4102. movq $42, w
  4103. movq v, x
  4104. addq $7, x
  4105. movq x, y
  4106. movq x, z
  4107. addq w, z
  4108. movq y, t
  4109. negq t
  4110. movq z, %rax
  4111. addq t, %rax
  4112. jmp conclusion
  4113. \end{lstlisting}
  4114. \end{minipage}
  4115. $\Rightarrow\qquad$
  4116. \begin{minipage}{0.25\textwidth}
  4117. \begin{lstlisting}
  4118. movq $1, %rcx
  4119. movq $42, %rsi
  4120. movq %rcx, %rcx
  4121. addq $7, %rcx
  4122. movq %rcx, %rcx
  4123. movq %rcx, %rdx
  4124. addq %rsi, %rdx
  4125. movq %rcx, %rcx
  4126. negq %rcx
  4127. movq %rdx, %rax
  4128. addq %rcx, %rax
  4129. jmp conclusion
  4130. \end{lstlisting}
  4131. \end{minipage}
  4132. $\Rightarrow\qquad$
  4133. \begin{minipage}{0.25\textwidth}
  4134. \begin{lstlisting}
  4135. movq $1, %rcx
  4136. movq $42, %rsi
  4137. addq $7, %rcx
  4138. movq %rcx, %rdx
  4139. addq %rsi, %rdx
  4140. negq %rcx
  4141. movq %rdx, %rax
  4142. addq %rcx, %rax
  4143. jmp conclusion
  4144. \end{lstlisting}
  4145. \end{minipage}
  4146. \begin{exercise}\normalfont
  4147. Change your implementation of \code{allocate-registers} to take move
  4148. biasing into account. Create two new tests that include at least one
  4149. opportunity for move biasing and visually inspect the output x86
  4150. programs to make sure that your move biasing is working properly. Make
  4151. sure that your compiler still passes all of the tests.
  4152. \end{exercise}
  4153. %To do: another neat challenge would be to do
  4154. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  4155. %% \subsection{Output of the Running Example}
  4156. %% \label{sec:reg-alloc-output}
  4157. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4158. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  4159. and move biasing. To demonstrate both the use of registers and the
  4160. stack, we have limited the register allocator to use just two
  4161. registers: \code{rbx} and \code{rcx}. In the prelude\index{subject}{prelude}
  4162. of the \code{main} function, we push \code{rbx} onto the stack because
  4163. it is a callee-saved register and it was assigned to variable by the
  4164. register allocator. We subtract \code{8} from the \code{rsp} at the
  4165. end of the prelude to reserve space for the one spilled variable.
  4166. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  4167. Moving on the the \code{start} block, we see how the registers were
  4168. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  4169. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  4170. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  4171. that the prelude saved the callee-save register \code{rbx} onto the
  4172. stack. The spilled variables must be placed lower on the stack than
  4173. the saved callee-save registers, so in this case \code{w} is placed at
  4174. \code{-16(\%rbp)}.
  4175. In the \code{conclusion}\index{subject}{conclusion}, we undo the work that was
  4176. done in the prelude. We move the stack pointer up by \code{8} bytes
  4177. (the room for spilled variables), then we pop the old values of
  4178. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4179. \code{retq} to return control to the operating system.
  4180. \begin{figure}[tbp]
  4181. % var_test_28.rkt
  4182. % (use-minimal-set-of-registers! #t)
  4183. % and only rbx rcx
  4184. % tmp 0 rbx
  4185. % z 1 rcx
  4186. % y 0 rbx
  4187. % w 2 16(%rbp)
  4188. % v 0 rbx
  4189. % x 0 rbx
  4190. \begin{lstlisting}
  4191. start:
  4192. movq $1, %rbx
  4193. movq $42, -16(%rbp)
  4194. addq $7, %rbx
  4195. movq %rbx, %rcx
  4196. addq -16(%rbp), %rcx
  4197. negq %rbx
  4198. movq %rcx, %rax
  4199. addq %rbx, %rax
  4200. jmp conclusion
  4201. .globl main
  4202. main:
  4203. pushq %rbp
  4204. movq %rsp, %rbp
  4205. pushq %rbx
  4206. subq $8, %rsp
  4207. jmp start
  4208. conclusion:
  4209. addq $8, %rsp
  4210. popq %rbx
  4211. popq %rbp
  4212. retq
  4213. \end{lstlisting}
  4214. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  4215. \label{fig:running-example-x86}
  4216. \end{figure}
  4217. % challenge: prioritize variables based on execution frequencies
  4218. % and the number of uses of a variable
  4219. % challenge: enhance the coloring algorithm using Chaitin's
  4220. % approach of prioritizing high-degree variables
  4221. % by removing low-degree variables (coloring them later)
  4222. % from the interference graph
  4223. \section{Further Reading}
  4224. \label{sec:register-allocation-further-reading}
  4225. Early register allocation algorithms were developed for Fortran
  4226. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  4227. of graph coloring began in the late 1970s and early 1980s with the
  4228. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  4229. algorithm is based on the following observation of
  4230. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  4231. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  4232. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  4233. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  4234. different colors, but since there are less than $k$ of them, there
  4235. will be one or more colors left over to use for coloring $v$ in $G$.
  4236. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  4237. less than $k$ from the graph and recursively colors the rest of the
  4238. graph. Upon returning from the recursion, it colors $v$ with one of
  4239. the available colors and returns. \citet{Chaitin:1982vn} augments
  4240. this algorithm to handle spilling as follows. If there are no vertices
  4241. of degree lower than $k$ then pick a vertex at random, spill it,
  4242. remove it from the graph, and proceed recursively to color the rest of
  4243. the graph.
  4244. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  4245. move-related and that don't interfere with each other, a process
  4246. called \emph{coalescing}. While coalescing decreases the number of
  4247. moves, it can make the graph more difficult to
  4248. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  4249. which two variables are merged only if they have fewer than $k$
  4250. neighbors of high degree. \citet{George:1996aa} observe that
  4251. conservative coalescing is sometimes too conservative and make it more
  4252. aggressive by iterating the coalescing with the removal of low-degree
  4253. vertices.
  4254. %
  4255. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  4256. also propose \emph{biased coloring} in which a variable is assigned to
  4257. the same color as another move-related variable if possible, as
  4258. discussed in Section~\ref{sec:move-biasing}.
  4259. %
  4260. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  4261. performs coalescing, graph coloring, and spill code insertion until
  4262. all variables have been assigned a location.
  4263. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  4264. spills variables that don't have to be: a high-degree variable can be
  4265. colorable if many of its neighbors are assigned the same color.
  4266. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  4267. high-degree vertex is not immediately spilled. Instead the decision is
  4268. deferred until after the recursive call, at which point it is apparent
  4269. whether there is actually an available color or not. We observe that
  4270. this algorithm is equivalent to the smallest-last ordering
  4271. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  4272. be registers and the rest to be stack locations.
  4273. %% biased coloring
  4274. Earlier editions of the compiler course at Indiana University
  4275. \citep{Dybvig:2010aa} were based on the algorithm of
  4276. \citet{Briggs:1994kx}.
  4277. The smallest-last ordering algorithm is one of many \emph{greedy}
  4278. coloring algorithms. A greedy coloring algorithm visits all the
  4279. vertices in a particular order and assigns each one the first
  4280. available color. An \emph{offline} greedy algorithm chooses the
  4281. ordering up-front, prior to assigning colors. The algorithm of
  4282. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4283. ordering does not depend on the colors assigned, so the algorithm
  4284. could be split into two phases. Other orderings are possible. For
  4285. example, \citet{Chow:1984ys} order variables according an estimate of
  4286. runtime cost.
  4287. An \emph{online} greedy coloring algorithm uses information about the
  4288. current assignment of colors to influence the order in which the
  4289. remaining vertices are colored. The saturation-based algorithm
  4290. described in this chapter is one such algorithm. We choose to use
  4291. saturation-based coloring is because it is fun to introduce graph
  4292. coloring via Sudoku.
  4293. A register allocator may choose to map each variable to just one
  4294. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4295. variable to one or more locations. The later can be achieved by
  4296. \emph{live range splitting}, where a variable is replaced by several
  4297. variables that each handle part of its live
  4298. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4299. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4300. %% replacement algorithm, bottom-up local
  4301. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4302. %% Cooper: top-down (priority bassed), bottom-up
  4303. %% top-down
  4304. %% order variables by priority (estimated cost)
  4305. %% caveat: split variables into two groups:
  4306. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4307. %% color the constrained ones first
  4308. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4309. %% cite J. Cocke for an algorithm that colors variables
  4310. %% in a high-degree first ordering
  4311. %Register Allocation via Usage Counts, Freiburghouse CACM
  4312. \citet{Palsberg:2007si} observe that many of the interference graphs
  4313. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4314. that is, every cycle with four or more edges has an edge which is not
  4315. part of the cycle but which connects two vertices on the cycle. Such
  4316. graphs can be optimally colored by the greedy algorithm with a vertex
  4317. ordering determined by maximum cardinality search.
  4318. In situations where compile time is of utmost importance, such as in
  4319. just-in-time compilers, graph coloring algorithms can be too expensive
  4320. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4321. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4322. \chapter{Booleans and Control Flow}
  4323. \label{ch:Rif}
  4324. \index{subject}{Boolean}
  4325. \index{subject}{control flow}
  4326. \index{subject}{conditional expression}
  4327. The \LangInt{} and \LangVar{} languages only have a single kind of
  4328. value, integers. In this chapter we add a second kind of value, the
  4329. Booleans, to create the \LangIf{} language. The Boolean values
  4330. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4331. respectively in Racket. The \LangIf{} language includes several
  4332. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4333. \key{<}, etc.) and the conditional \key{if} expression. With the
  4334. addition of \key{if}, programs can have non-trivial control flow which
  4335. impacts \code{explicate-control} and liveness analysis. Also, because
  4336. we now have two kinds of values, we need to handle programs that apply
  4337. an operation to the wrong kind of value, such as \code{(not 1)}.
  4338. There are two language design options for such situations. One option
  4339. is to signal an error and the other is to provide a wider
  4340. interpretation of the operation. The Racket language uses a mixture of
  4341. these two options, depending on the operation and the kind of
  4342. value. For example, the result of \code{(not 1)} in Racket is
  4343. \code{\#f} because Racket treats non-zero integers as if they were
  4344. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4345. error in Racket because \code{car} expects a pair.
  4346. Typed Racket makes similar design choices as Racket, except much of
  4347. the error detection happens at compile time instead of run time. Typed
  4348. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4349. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4350. because Typed Racket expects the type of the argument to be of the
  4351. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4352. The \LangIf{} language performs type checking during compilation like
  4353. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4354. alternative choice, that is, a dynamically typed language like Racket.
  4355. The \LangIf{} language is a subset of Typed Racket; for some
  4356. operations we are more restrictive, for example, rejecting
  4357. \code{(not 1)}.
  4358. This chapter is organized as follows. We begin by defining the syntax
  4359. and interpreter for the \LangIf{} language
  4360. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4361. checking and build a type checker for \LangIf{}
  4362. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4363. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4364. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4365. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4366. discuss how our compiler passes change to accommodate Booleans and
  4367. conditional control flow. There is one new pass, named \code{shrink},
  4368. that translates some operators into others, thereby reducing the
  4369. number of operators that need to be handled in later passes. The
  4370. largest changes occur in \code{explicate-control}, to translate
  4371. \code{if} expressions into control-flow graphs
  4372. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4373. allocation, the liveness analysis now has multiple basic blocks to
  4374. process and there is the interesting question of how to handle
  4375. conditional jumps.
  4376. \section{The \LangIf{} Language}
  4377. \label{sec:lang-if}
  4378. The concrete syntax of the \LangIf{} language is defined in
  4379. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4380. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4381. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4382. \code{\#f}, and the conditional \code{if} expression. We expand the
  4383. operators to include
  4384. \begin{enumerate}
  4385. \item subtraction on integers,
  4386. \item the logical operators \key{and}, \key{or} and \key{not},
  4387. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4388. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4389. comparing integers.
  4390. \end{enumerate}
  4391. We reorganize the abstract syntax for the primitive operations in
  4392. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4393. them. This means that the grammar no longer checks whether the arity
  4394. of an operators matches the number of arguments. That responsibility
  4395. is moved to the type checker for \LangIf{}, which we introduce in
  4396. Section~\ref{sec:type-check-Rif}.
  4397. \begin{figure}[tp]
  4398. \centering
  4399. \fbox{
  4400. \begin{minipage}{0.96\textwidth}
  4401. \[
  4402. \begin{array}{lcl}
  4403. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4404. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4405. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4406. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4407. &\mid& \itm{bool}
  4408. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4409. \mid (\key{not}\;\Exp) \\
  4410. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4411. \LangIfM{} &::=& \Exp
  4412. \end{array}
  4413. \]
  4414. \end{minipage}
  4415. }
  4416. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4417. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  4418. \label{fig:Rif-concrete-syntax}
  4419. \end{figure}
  4420. \begin{figure}[tp]
  4421. \centering
  4422. \fbox{
  4423. \begin{minipage}{0.96\textwidth}
  4424. \[
  4425. \begin{array}{lcl}
  4426. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4427. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4428. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4429. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4430. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4431. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4432. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4433. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4434. \end{array}
  4435. \]
  4436. \end{minipage}
  4437. }
  4438. \caption{The abstract syntax of \LangIf{}.}
  4439. \label{fig:Rif-syntax}
  4440. \end{figure}
  4441. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4442. which inherits from the interpreter for \LangVar{}
  4443. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4444. evaluate to the corresponding Boolean values. The conditional
  4445. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4446. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4447. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4448. operations \code{not} and \code{and} behave as you might expect, but
  4449. note that the \code{and} operation is short-circuiting. That is, given
  4450. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4451. evaluated if $e_1$ evaluates to \code{\#f}.
  4452. With the increase in the number of primitive operations, the
  4453. interpreter would become repetitive without some care. We refactor
  4454. the case for \code{Prim}, moving the code that differs with each
  4455. operation into the \code{interp-op} method shown in in
  4456. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4457. separately because of its short-circuiting behavior.
  4458. \begin{figure}[tbp]
  4459. \begin{lstlisting}
  4460. (define interp-Rif-class
  4461. (class interp-Rvar-class
  4462. (super-new)
  4463. (define/public (interp-op op) ...)
  4464. (define/override ((interp-exp env) e)
  4465. (define recur (interp-exp env))
  4466. (match e
  4467. [(Bool b) b]
  4468. [(If cnd thn els)
  4469. (match (recur cnd)
  4470. [#t (recur thn)]
  4471. [#f (recur els)])]
  4472. [(Prim 'and (list e1 e2))
  4473. (match (recur e1)
  4474. [#t (match (recur e2) [#t #t] [#f #f])]
  4475. [#f #f])]
  4476. [(Prim op args)
  4477. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4478. [else ((super interp-exp env) e)]))
  4479. ))
  4480. (define (interp-Rif p)
  4481. (send (new interp-Rif-class) interp-program p))
  4482. \end{lstlisting}
  4483. \caption{Interpreter for the \LangIf{} language. (See
  4484. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4485. \label{fig:interp-Rif}
  4486. \end{figure}
  4487. \begin{figure}[tbp]
  4488. \begin{lstlisting}
  4489. (define/public (interp-op op)
  4490. (match op
  4491. ['+ fx+]
  4492. ['- fx-]
  4493. ['read read-fixnum]
  4494. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4495. ['or (lambda (v1 v2)
  4496. (cond [(and (boolean? v1) (boolean? v2))
  4497. (or v1 v2)]))]
  4498. ['eq? (lambda (v1 v2)
  4499. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4500. (and (boolean? v1) (boolean? v2))
  4501. (and (vector? v1) (vector? v2)))
  4502. (eq? v1 v2)]))]
  4503. ['< (lambda (v1 v2)
  4504. (cond [(and (fixnum? v1) (fixnum? v2))
  4505. (< v1 v2)]))]
  4506. ['<= (lambda (v1 v2)
  4507. (cond [(and (fixnum? v1) (fixnum? v2))
  4508. (<= v1 v2)]))]
  4509. ['> (lambda (v1 v2)
  4510. (cond [(and (fixnum? v1) (fixnum? v2))
  4511. (> v1 v2)]))]
  4512. ['>= (lambda (v1 v2)
  4513. (cond [(and (fixnum? v1) (fixnum? v2))
  4514. (>= v1 v2)]))]
  4515. [else (error 'interp-op "unknown operator")]))
  4516. \end{lstlisting}
  4517. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4518. \label{fig:interp-op-Rif}
  4519. \end{figure}
  4520. \section{Type Checking \LangIf{} Programs}
  4521. \label{sec:type-check-Rif}
  4522. \index{subject}{type checking}
  4523. \index{subject}{semantic analysis}
  4524. It is helpful to think about type checking in two complementary
  4525. ways. A type checker predicts the type of value that will be produced
  4526. by each expression in the program. For \LangIf{}, we have just two types,
  4527. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4528. \begin{lstlisting}
  4529. (+ 10 (- (+ 12 20)))
  4530. \end{lstlisting}
  4531. produces an \key{Integer} while
  4532. \begin{lstlisting}
  4533. (and (not #f) #t)
  4534. \end{lstlisting}
  4535. produces a \key{Boolean}.
  4536. Another way to think about type checking is that it enforces a set of
  4537. rules about which operators can be applied to which kinds of
  4538. values. For example, our type checker for \LangIf{} signals an error
  4539. for the below expression
  4540. \begin{lstlisting}
  4541. (not (+ 10 (- (+ 12 20))))
  4542. \end{lstlisting}
  4543. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4544. but the type checker enforces the rule that the argument of \code{not}
  4545. must be a \key{Boolean}.
  4546. We implement type checking using classes and methods because they
  4547. provide the open recursion needed to reuse code as we extend the type
  4548. checker in later chapters, analogous to the use of classes and methods
  4549. for the interpreters (Section~\ref{sec:extensible-interp}).
  4550. We separate the type checker for the \LangVar{} fragment into its own
  4551. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4552. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4553. from the type checker for \LangVar{}. These type checkers are in the
  4554. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4555. support code.
  4556. %
  4557. Each type checker is a structurally recursive function over the AST.
  4558. Given an input expression \code{e}, the type checker either signals an
  4559. error or returns an expression and its type (\key{Integer} or
  4560. \key{Boolean}). It returns an expression because there are situations
  4561. in which we want to change or update the expression.
  4562. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4563. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4564. \code{Integer}. To handle variables, the type checker uses the
  4565. environment \code{env} to map variables to types. Consider the case
  4566. for \key{let}. We type check the initializing expression to obtain
  4567. its type \key{T} and then associate type \code{T} with the variable
  4568. \code{x} in the environment used to type check the body of the
  4569. \key{let}. Thus, when the type checker encounters a use of variable
  4570. \code{x}, it can find its type in the environment. Regarding
  4571. primitive operators, we recursively analyze the arguments and then
  4572. invoke \code{type-check-op} to check whether the argument types are
  4573. allowed.
  4574. Several auxiliary methods are used in the type checker. The method
  4575. \code{operator-types} defines a dictionary that maps the operator
  4576. names to their parameter and return types. The \code{type-equal?}
  4577. method determines whether two types are equal, which for now simply
  4578. dispatches to \code{equal?} (deep equality). The
  4579. \code{check-type-equal?} method triggers an error if the two types are
  4580. not equal. The \code{type-check-op} method looks up the operator in
  4581. the \code{operator-types} dictionary and then checks whether the
  4582. argument types are equal to the parameter types. The result is the
  4583. return type of the operator.
  4584. \begin{figure}[tbp]
  4585. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4586. (define type-check-Rvar-class
  4587. (class object%
  4588. (super-new)
  4589. (define/public (operator-types)
  4590. '((+ . ((Integer Integer) . Integer))
  4591. (- . ((Integer) . Integer))
  4592. (read . (() . Integer))))
  4593. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4594. (define/public (check-type-equal? t1 t2 e)
  4595. (unless (type-equal? t1 t2)
  4596. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4597. (define/public (type-check-op op arg-types e)
  4598. (match (dict-ref (operator-types) op)
  4599. [`(,param-types . ,return-type)
  4600. (for ([at arg-types] [pt param-types])
  4601. (check-type-equal? at pt e))
  4602. return-type]
  4603. [else (error 'type-check-op "unrecognized ~a" op)]))
  4604. (define/public (type-check-exp env)
  4605. (lambda (e)
  4606. (match e
  4607. [(Int n) (values (Int n) 'Integer)]
  4608. [(Var x) (values (Var x) (dict-ref env x))]
  4609. [(Let x e body)
  4610. (define-values (e^ Te) ((type-check-exp env) e))
  4611. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4612. (values (Let x e^ b) Tb)]
  4613. [(Prim op es)
  4614. (define-values (new-es ts)
  4615. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4616. (values (Prim op new-es) (type-check-op op ts e))]
  4617. [else (error 'type-check-exp "couldn't match" e)])))
  4618. (define/public (type-check-program e)
  4619. (match e
  4620. [(Program info body)
  4621. (define-values (body^ Tb) ((type-check-exp '()) body))
  4622. (check-type-equal? Tb 'Integer body)
  4623. (Program info body^)]
  4624. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4625. ))
  4626. (define (type-check-Rvar p)
  4627. (send (new type-check-Rvar-class) type-check-program p))
  4628. \end{lstlisting}
  4629. \caption{Type checker for the \LangVar{} language.}
  4630. \label{fig:type-check-Rvar}
  4631. \end{figure}
  4632. \begin{figure}[tbp]
  4633. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4634. (define type-check-Rif-class
  4635. (class type-check-Rvar-class
  4636. (super-new)
  4637. (inherit check-type-equal?)
  4638. (define/override (operator-types)
  4639. (append '((- . ((Integer Integer) . Integer))
  4640. (and . ((Boolean Boolean) . Boolean))
  4641. (or . ((Boolean Boolean) . Boolean))
  4642. (< . ((Integer Integer) . Boolean))
  4643. (<= . ((Integer Integer) . Boolean))
  4644. (> . ((Integer Integer) . Boolean))
  4645. (>= . ((Integer Integer) . Boolean))
  4646. (not . ((Boolean) . Boolean))
  4647. )
  4648. (super operator-types)))
  4649. (define/override (type-check-exp env)
  4650. (lambda (e)
  4651. (match e
  4652. [(Prim 'eq? (list e1 e2))
  4653. (define-values (e1^ T1) ((type-check-exp env) e1))
  4654. (define-values (e2^ T2) ((type-check-exp env) e2))
  4655. (check-type-equal? T1 T2 e)
  4656. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4657. [(Bool b) (values (Bool b) 'Boolean)]
  4658. [(If cnd thn els)
  4659. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4660. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4661. (define-values (els^ Te) ((type-check-exp env) els))
  4662. (check-type-equal? Tc 'Boolean e)
  4663. (check-type-equal? Tt Te e)
  4664. (values (If cnd^ thn^ els^) Te)]
  4665. [else ((super type-check-exp env) e)])))
  4666. ))
  4667. (define (type-check-Rif p)
  4668. (send (new type-check-Rif-class) type-check-program p))
  4669. \end{lstlisting}
  4670. \caption{Type checker for the \LangIf{} language.}
  4671. \label{fig:type-check-Rif}
  4672. \end{figure}
  4673. Next we discuss the type checker for \LangIf{} in
  4674. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4675. two arguments to have the same type. The type of a Boolean constant is
  4676. \code{Boolean}. The condition of an \code{if} must be of
  4677. \code{Boolean} type and the two branches must have the same type. The
  4678. \code{operator-types} function adds dictionary entries for the other
  4679. new operators.
  4680. \begin{exercise}\normalfont
  4681. Create 10 new test programs in \LangIf{}. Half of the programs should
  4682. have a type error. For those programs, create an empty file with the
  4683. same base name but with file extension \code{.tyerr}. For example, if
  4684. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4685. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4686. \code{interp-tests} and \code{compiler-tests} that a type error is
  4687. expected. The other half of the test programs should not have type
  4688. errors.
  4689. In the \code{run-tests.rkt} script, change the second argument of
  4690. \code{interp-tests} and \code{compiler-tests} to
  4691. \code{type-check-Rif}, which causes the type checker to run prior to
  4692. the compiler passes. Temporarily change the \code{passes} to an empty
  4693. list and run the script, thereby checking that the new test programs
  4694. either type check or not as intended.
  4695. \end{exercise}
  4696. \section{The \LangCIf{} Intermediate Language}
  4697. \label{sec:Cif}
  4698. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4699. \LangCIf{} intermediate language. (The concrete syntax is in the
  4700. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4701. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4702. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4703. \key{\#f} to the \Arg{} non-terminal.
  4704. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4705. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4706. statement is a comparison operation and the branches are \code{goto}
  4707. statements, making it straightforward to compile \code{if} statements
  4708. to x86.
  4709. \begin{figure}[tp]
  4710. \fbox{
  4711. \begin{minipage}{0.96\textwidth}
  4712. \small
  4713. \[
  4714. \begin{array}{lcl}
  4715. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4716. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4717. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4718. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4719. &\mid& \UNIOP{\key{'not}}{\Atm}
  4720. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4721. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4722. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4723. \mid \GOTO{\itm{label}} \\
  4724. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4725. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4726. \end{array}
  4727. \]
  4728. \end{minipage}
  4729. }
  4730. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4731. (Figure~\ref{fig:c0-syntax}).}
  4732. \label{fig:c1-syntax}
  4733. \end{figure}
  4734. \section{The \LangXIf{} Language}
  4735. \label{sec:x86-if}
  4736. \index{subject}{x86} To implement the new logical operations, the comparison
  4737. operations, and the \key{if} expression, we need to delve further into
  4738. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4739. define the concrete and abstract syntax for the \LangXIf{} subset
  4740. of x86, which includes instructions for logical operations,
  4741. comparisons, and conditional jumps.
  4742. One challenge is that x86 does not provide an instruction that
  4743. directly implements logical negation (\code{not} in \LangIf{} and
  4744. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4745. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4746. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4747. bit of its arguments, and writes the results into its second argument.
  4748. Recall the truth table for exclusive-or:
  4749. \begin{center}
  4750. \begin{tabular}{l|cc}
  4751. & 0 & 1 \\ \hline
  4752. 0 & 0 & 1 \\
  4753. 1 & 1 & 0
  4754. \end{tabular}
  4755. \end{center}
  4756. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4757. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4758. for the bit $1$, the result is the opposite of the second bit. Thus,
  4759. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4760. the first argument:
  4761. \[
  4762. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4763. \qquad\Rightarrow\qquad
  4764. \begin{array}{l}
  4765. \key{movq}~ \Arg\key{,} \Var\\
  4766. \key{xorq}~ \key{\$1,} \Var
  4767. \end{array}
  4768. \]
  4769. \begin{figure}[tp]
  4770. \fbox{
  4771. \begin{minipage}{0.96\textwidth}
  4772. \[
  4773. \begin{array}{lcl}
  4774. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4775. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4776. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4777. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4778. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4779. \key{subq} \; \Arg\key{,} \Arg \mid
  4780. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4781. && \gray{ \key{callq} \; \itm{label} \mid
  4782. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4783. && \gray{ \itm{label}\key{:}\; \Instr }
  4784. \mid \key{xorq}~\Arg\key{,}~\Arg
  4785. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4786. && \key{set}cc~\Arg
  4787. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4788. \mid \key{j}cc~\itm{label}
  4789. \\
  4790. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  4791. & & \gray{ \key{main:} \; \Instr\ldots }
  4792. \end{array}
  4793. \]
  4794. \end{minipage}
  4795. }
  4796. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4797. \label{fig:x86-1-concrete}
  4798. \end{figure}
  4799. \begin{figure}[tp]
  4800. \fbox{
  4801. \begin{minipage}{0.98\textwidth}
  4802. \small
  4803. \[
  4804. \begin{array}{lcl}
  4805. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4806. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4807. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4808. \mid \BYTEREG{\itm{bytereg}} \\
  4809. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4810. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4811. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4812. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4813. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4814. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4815. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4816. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4817. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4818. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4819. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4820. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4821. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4822. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4823. \end{array}
  4824. \]
  4825. \end{minipage}
  4826. }
  4827. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4828. \label{fig:x86-1}
  4829. \end{figure}
  4830. Next we consider the x86 instructions that are relevant for compiling
  4831. the comparison operations. The \key{cmpq} instruction compares its two
  4832. arguments to determine whether one argument is less than, equal, or
  4833. greater than the other argument. The \key{cmpq} instruction is unusual
  4834. regarding the order of its arguments and where the result is
  4835. placed. The argument order is backwards: if you want to test whether
  4836. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4837. \key{cmpq} is placed in the special EFLAGS register. This register
  4838. cannot be accessed directly but it can be queried by a number of
  4839. instructions, including the \key{set} instruction. The instruction
  4840. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4841. depending on whether the comparison comes out according to the
  4842. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4843. for less-or-equal, \key{g} for greater, \key{ge} for
  4844. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4845. that its destination argument must be single byte register, such as
  4846. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4847. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4848. instruction can be used to move from a single byte register to a
  4849. normal 64-bit register. The abstract syntax for the \code{set}
  4850. instruction differs from the concrete syntax in that it separates the
  4851. instruction name from the condition code.
  4852. The x86 instruction for conditional jump is relevant to the
  4853. compilation of \key{if} expressions. The instruction
  4854. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4855. the instruction after \itm{label} depending on whether the result in
  4856. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4857. jump instruction falls through to the next instruction. Like the
  4858. abstract syntax for \code{set}, the abstract syntax for conditional
  4859. jump separates the instruction name from the condition code. For
  4860. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4861. the conditional jump instruction relies on the EFLAGS register, it is
  4862. common for it to be immediately preceded by a \key{cmpq} instruction
  4863. to set the EFLAGS register.
  4864. \section{Shrink the \LangIf{} Language}
  4865. \label{sec:shrink-Rif}
  4866. The \LangIf{} language includes several operators that are easily
  4867. expressible with other operators. For example, subtraction is
  4868. expressible using addition and negation.
  4869. \[
  4870. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4871. \]
  4872. Several of the comparison operations are expressible using less-than
  4873. and logical negation.
  4874. \[
  4875. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4876. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4877. \]
  4878. The \key{let} is needed in the above translation to ensure that
  4879. expression $e_1$ is evaluated before $e_2$.
  4880. By performing these translations in the front-end of the compiler, the
  4881. later passes of the compiler do not need to deal with these operators,
  4882. making the passes shorter.
  4883. %% On the other hand, sometimes
  4884. %% these translations make it more difficult to generate the most
  4885. %% efficient code with respect to the number of instructions. However,
  4886. %% these differences typically do not affect the number of accesses to
  4887. %% memory, which is the primary factor that determines execution time on
  4888. %% modern computer architectures.
  4889. \begin{exercise}\normalfont
  4890. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4891. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4892. translating them to other constructs in \LangIf{}.
  4893. %
  4894. Create six test programs that involve these operators.
  4895. %
  4896. In the \code{run-tests.rkt} script, add the following entry for
  4897. \code{shrink} to the list of passes (it should be the only pass at
  4898. this point).
  4899. \begin{lstlisting}
  4900. (list "shrink" shrink interp-Rif type-check-Rif)
  4901. \end{lstlisting}
  4902. This instructs \code{interp-tests} to run the intepreter
  4903. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4904. output of \code{shrink}.
  4905. %
  4906. Run the script to test your compiler on all the test programs.
  4907. \end{exercise}
  4908. \section{Uniquify Variables}
  4909. \label{sec:uniquify-Rif}
  4910. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4911. \code{if} expressions.
  4912. \begin{exercise}\normalfont
  4913. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4914. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4915. \begin{lstlisting}
  4916. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4917. \end{lstlisting}
  4918. Run the script to test your compiler.
  4919. \end{exercise}
  4920. \section{Remove Complex Operands}
  4921. \label{sec:remove-complex-opera-Rif}
  4922. The output language for this pass is \LangIfANF{}
  4923. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4924. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4925. \code{If} is not. All three sub-expressions of an \code{If} are
  4926. allowed to be complex expressions but the operands of \code{not} and
  4927. the comparisons must be atoms.
  4928. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4929. \code{rco-atom} functions according to whether the output needs to be
  4930. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4931. Regarding \code{If}, it is particularly important to \textbf{not}
  4932. replace its condition with a temporary variable because that would
  4933. interfere with the generation of high-quality output in the
  4934. \code{explicate-control} pass.
  4935. \begin{figure}[tp]
  4936. \centering
  4937. \fbox{
  4938. \begin{minipage}{0.96\textwidth}
  4939. \[
  4940. \begin{array}{rcl}
  4941. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4942. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4943. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4944. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4945. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4946. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4947. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4948. \end{array}
  4949. \]
  4950. \end{minipage}
  4951. }
  4952. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4953. \label{fig:Rif-anf-syntax}
  4954. \end{figure}
  4955. \begin{exercise}\normalfont
  4956. %
  4957. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4958. and \code{rco-exp} functions in \code{compiler.rkt}.
  4959. %
  4960. Create three new \LangInt{} programs that exercise the interesting
  4961. code in this pass.
  4962. %
  4963. In the \code{run-tests.rkt} script, add the following entry to the
  4964. list of \code{passes} and then run the script to test your compiler.
  4965. \begin{lstlisting}
  4966. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4967. \end{lstlisting}
  4968. \end{exercise}
  4969. \section{Explicate Control}
  4970. \label{sec:explicate-control-Rif}
  4971. Recall that the purpose of \code{explicate-control} is to make the
  4972. order of evaluation explicit in the syntax of the program. With the
  4973. addition of \key{if} this get more interesting.
  4974. As a motivating example, consider the following program that has an
  4975. \key{if} expression nested in the predicate of another \key{if}.
  4976. % cond_test_41.rkt, if_lt_eq.py
  4977. \begin{center}
  4978. \begin{minipage}{0.96\textwidth}
  4979. \begin{lstlisting}
  4980. (let ([x (read)])
  4981. (let ([y (read)])
  4982. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4983. (+ y 2)
  4984. (+ y 10))))
  4985. \end{lstlisting}
  4986. \end{minipage}
  4987. \end{center}
  4988. %
  4989. The naive way to compile \key{if} and the comparison would be to
  4990. handle each of them in isolation, regardless of their context. Each
  4991. comparison would be translated into a \key{cmpq} instruction followed
  4992. by a couple instructions to move the result from the EFLAGS register
  4993. into a general purpose register or stack location. Each \key{if} would
  4994. be translated into a \key{cmpq} instruction followed by a conditional
  4995. jump. The generated code for the inner \key{if} in the above example
  4996. would be as follows.
  4997. \begin{center}
  4998. \begin{minipage}{0.96\textwidth}
  4999. \begin{lstlisting}
  5000. ...
  5001. cmpq $1, x ;; (< x 1)
  5002. setl %al
  5003. movzbq %al, tmp
  5004. cmpq $1, tmp ;; (if ...)
  5005. je then_branch_1
  5006. jmp else_branch_1
  5007. ...
  5008. \end{lstlisting}
  5009. \end{minipage}
  5010. \end{center}
  5011. However, if we take context into account we can do better and reduce
  5012. the use of \key{cmpq} instructions for accessing the EFLAG register.
  5013. Our goal will be compile \key{if} expressions so that the relevant
  5014. comparison instruction appears directly before the conditional jump.
  5015. For example, we want to generate the following code for the inner
  5016. \code{if}.
  5017. \begin{center}
  5018. \begin{minipage}{0.96\textwidth}
  5019. \begin{lstlisting}
  5020. ...
  5021. cmpq $1, x
  5022. je then_branch_1
  5023. jmp else_branch_1
  5024. ...
  5025. \end{lstlisting}
  5026. \end{minipage}
  5027. \end{center}
  5028. One way to achieve this is to reorganize the code at the level of
  5029. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  5030. the following code.
  5031. \begin{center}
  5032. \begin{minipage}{0.96\textwidth}
  5033. \begin{lstlisting}
  5034. (let ([x (read)])
  5035. (let ([y (read)])
  5036. (if (< x 1)
  5037. (if (eq? x 0)
  5038. (+ y 2)
  5039. (+ y 10))
  5040. (if (eq? x 2)
  5041. (+ y 2)
  5042. (+ y 10)))))
  5043. \end{lstlisting}
  5044. \end{minipage}
  5045. \end{center}
  5046. Unfortunately, this approach duplicates the two branches from the
  5047. outer \code{if} and a compiler must never duplicate code!
  5048. We need a way to perform the above transformation but without
  5049. duplicating code. That is, we need a way for different parts of a
  5050. program to refer to the same piece of code. At the level of x86
  5051. assembly this is straightforward because we can label the code for
  5052. each branch and insert jumps in all the places that need to execute
  5053. the branch. In our intermediate language, we need to move away from
  5054. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  5055. particular, we use a standard program representation called a
  5056. \emph{control flow graph} (CFG), due to Frances Elizabeth
  5057. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  5058. labeled sequence of code, called a \emph{basic block}, and each edge
  5059. represents a jump to another block. The \key{CProgram} construct of
  5060. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  5061. as an alist mapping labels to basic blocks. Each basic block is
  5062. represented by the $\Tail$ non-terminal.
  5063. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  5064. \code{remove-complex-opera*} pass and then the
  5065. \code{explicate-control} pass on the example program. We walk through
  5066. the output program and then discuss the algorithm.
  5067. %
  5068. Following the order of evaluation in the output of
  5069. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  5070. and then the comparison \lstinline{(< x 1)} in the predicate of the
  5071. inner \key{if}. In the output of \code{explicate-control}, in the
  5072. block labeled \code{start}, is two assignment statements followed by a
  5073. \code{if} statement that branches to \code{block40} or
  5074. \code{block41}. The blocks associated with those labels contain the
  5075. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  5076. respectively. In particular, we start \code{block40} with the
  5077. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  5078. \code{block39}, the two branches of the outer \key{if}, i.e.,
  5079. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  5080. \code{block41} is similar.
  5081. \begin{figure}[tbp]
  5082. \begin{tabular}{lll}
  5083. \begin{minipage}{0.4\textwidth}
  5084. % cond_test_41.rkt
  5085. \begin{lstlisting}
  5086. (let ([x (read)])
  5087. (let ([y (read)])
  5088. (if (if (< x 1)
  5089. (eq? x 0)
  5090. (eq? x 2))
  5091. (+ y 2)
  5092. (+ y 10))))
  5093. \end{lstlisting}
  5094. \hspace{40pt}$\Downarrow$
  5095. \begin{lstlisting}
  5096. (let ([x (read)])
  5097. (let ([y (read)])
  5098. (if (if (< x 1)
  5099. (eq? x 0)
  5100. (eq? x 2))
  5101. (+ y 2)
  5102. (+ y 10))))
  5103. \end{lstlisting}
  5104. \end{minipage}
  5105. &
  5106. $\Rightarrow$
  5107. &
  5108. \begin{minipage}{0.55\textwidth}
  5109. \begin{lstlisting}
  5110. start:
  5111. x = (read);
  5112. y = (read);
  5113. if (< x 1) goto block40;
  5114. else goto block41;
  5115. block40:
  5116. if (eq? x 0) goto block38;
  5117. else goto block39;
  5118. block41:
  5119. if (eq? x 2) goto block38;
  5120. else goto block39;
  5121. block38:
  5122. return (+ y 2);
  5123. block39:
  5124. return (+ y 10);
  5125. \end{lstlisting}
  5126. \end{minipage}
  5127. \end{tabular}
  5128. \caption{Translation from \LangIf{} to \LangCIf{}
  5129. via the \code{explicate-control}.}
  5130. \label{fig:explicate-control-s1-38}
  5131. \end{figure}
  5132. %% The nice thing about the output of \code{explicate-control} is that
  5133. %% there are no unnecessary comparisons and every comparison is part of a
  5134. %% conditional jump.
  5135. %% The down-side of this output is that it includes
  5136. %% trivial blocks, such as the blocks labeled \code{block92} through
  5137. %% \code{block95}, that only jump to another block. We discuss a solution
  5138. %% to this problem in Section~\ref{sec:opt-jumps}.
  5139. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  5140. \code{explicate-control} for \LangVar{} using two mutually recursive
  5141. functions, \code{explicate-tail} and \code{explicate-assign}. The
  5142. former function translates expressions in tail position whereas the
  5143. later function translates expressions on the right-hand-side of a
  5144. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  5145. have a new kind of position to deal with: the predicate position of
  5146. the \key{if}. We need another function, \code{explicate-pred}, that
  5147. takes an \LangIf{} expression and two blocks for the then-branch and
  5148. else-branch. The output of \code{explicate-pred} is a block.
  5149. %
  5150. In the following paragraphs we discuss specific cases in the
  5151. \code{explicate-pred} function as well as additions to the
  5152. \code{explicate-tail} and \code{explicate-assign} functions.
  5153. \begin{figure}[tbp]
  5154. \begin{lstlisting}
  5155. (define (explicate-pred cnd thn els)
  5156. (match cnd
  5157. [(Var x) ___]
  5158. [(Let x rhs body) ___]
  5159. [(Prim 'not (list e)) ___]
  5160. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  5161. (IfStmt (Prim op arg*) (force (block->goto thn))
  5162. (force (block->goto els)))]
  5163. [(Bool b) (if b thn els)]
  5164. [(If cnd^ thn^ els^) ___]
  5165. [else (error "explicate-pred unhandled case" cnd)]))
  5166. \end{lstlisting}
  5167. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  5168. \label{fig:explicate-pred}
  5169. \end{figure}
  5170. The skeleton for the \code{explicate-pred} function is given in
  5171. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  5172. that can have type \code{Boolean}. We detail a few cases here and
  5173. leave the rest for the reader. The input to this function is an
  5174. expression and two blocks, \code{thn} and \code{els}, for the two
  5175. branches of the enclosing \key{if}.
  5176. %
  5177. Consider the case for Boolean constants in
  5178. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  5179. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  5180. or \code{els} branch depending on whether the constant is true or
  5181. false. This case demonstrates that we sometimes discard the \code{thn}
  5182. or \code{els} blocks that are input to \code{explicate-pred}.
  5183. The case for \key{if} in \code{explicate-pred} is particularly
  5184. illuminating because it deals with the challenges we discussed above
  5185. regarding nested \key{if} expressions
  5186. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  5187. \lstinline{els^} branches of the \key{if} inherit their context from
  5188. the current one, that is, predicate context. So you should recursively
  5189. apply \code{explicate-pred} to the \lstinline{thn^} and
  5190. \lstinline{els^} branches. For both of those recursive calls, pass
  5191. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  5192. and \code{els} may get used twice, once inside each recursive call. As
  5193. discussed above, to avoid duplicating code, we need to add them to the
  5194. control-flow graph so that we can instead refer to them by name and
  5195. execute them with a \key{goto}. However, as we saw in the cases above
  5196. for Boolean constants, the blocks \code{thn} and \code{els} may not
  5197. get used at all and we don't want to prematurely add them to the
  5198. control-flow graph if they end up being discarded.
  5199. The solution to this conundrum is to use \emph{lazy
  5200. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  5201. adding the blocks to the control-flow graph until the points where we
  5202. know they will be used. Racket provides support for lazy evaluation
  5203. with the
  5204. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  5205. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  5206. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  5207. evaluation of the expressions is postponed. When \key{(force}
  5208. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  5209. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  5210. $e_n$ is cached in the promise and returned. If \code{force} is
  5211. applied again to the same promise, then the cached result is returned.
  5212. If \code{force} is applied to an argument that is not a promise,
  5213. \code{force} simply returns the argument.
  5214. We use lazy evaluation for the input and output blocks of the
  5215. functions \code{explicate-pred} and \code{explicate-assign} and for
  5216. the output block of \code{explicate-tail}. So instead of taking and
  5217. returning blocks, they take and return promises. Furthermore, when we
  5218. come to a situation in which we a block might be used more than once,
  5219. as in the case for \code{if} in \code{explicate-pred}, we transform
  5220. the promise into a new promise that will add the block to the
  5221. control-flow graph and return a \code{goto}. The following auxiliary
  5222. function named \code{block->goto} accomplishes this task. It begins
  5223. with \code{delay} to create a promise. When forced, this promise will
  5224. force the original promise. If that returns a \code{goto} (because the
  5225. block was already added to the control-flow graph), then we return the
  5226. \code{goto}. Otherwise we add the block to the control-flow graph with
  5227. another auxiliary function named \code{add-node}. That function
  5228. returns the label for the new block, which we use to create a
  5229. \code{goto}.
  5230. \begin{lstlisting}
  5231. (define (block->goto block)
  5232. (delay
  5233. (define b (force block))
  5234. (match b
  5235. [(Goto label) (Goto label)]
  5236. [else (Goto (add-node b))])))
  5237. \end{lstlisting}
  5238. Returning to the discussion of \code{explicate-pred}
  5239. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  5240. operators. This is one of the base cases of the recursive function so
  5241. we translate the comparison to an \code{if} statement. We apply
  5242. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  5243. that will add then to the control-flow graph, which we can immediately
  5244. \code{force} to obtain the two goto's that form the branches of the
  5245. \code{if} statement.
  5246. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  5247. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  5248. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  5249. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  5250. %% results from the two recursive calls. We complete the case for
  5251. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  5252. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  5253. %% the result $B_5$.
  5254. %% \[
  5255. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  5256. %% \quad\Rightarrow\quad
  5257. %% B_5
  5258. %% \]
  5259. The \code{explicate-tail} and \code{explicate-assign} functions need
  5260. additional cases for Boolean constants and \key{if}.
  5261. %
  5262. In the cases for \code{if}, the two branches inherit the current
  5263. context, so in \code{explicate-tail} they are in tail position and in
  5264. \code{explicate-assign} they are in assignment position. The
  5265. \code{cont} parameter of \code{explicate-assign} is used in both
  5266. recursive calls, so make sure to use \code{block->goto} on it.
  5267. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  5268. %% inherit the current context, so they are in tail position. Thus, the
  5269. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  5270. %% \code{explicate-tail}.
  5271. %% %
  5272. %% We need to pass $B_0$ as the accumulator argument for both of these
  5273. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  5274. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  5275. %% to the control-flow graph and obtain a promised goto $G_0$.
  5276. %% %
  5277. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5278. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5279. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5280. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5281. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5282. %% \[
  5283. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5284. %% \]
  5285. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5286. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5287. %% should not be confused with the labels for the blocks that appear in
  5288. %% the generated code. We initially construct unlabeled blocks; we only
  5289. %% attach labels to blocks when we add them to the control-flow graph, as
  5290. %% we see in the next case.
  5291. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5292. %% function. The context of the \key{if} is an assignment to some
  5293. %% variable $x$ and then the control continues to some promised block
  5294. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5295. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5296. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5297. %% branches of the \key{if} inherit the current context, so they are in
  5298. %% assignment positions. Let $B_2$ be the result of applying
  5299. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5300. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5301. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5302. %% the result of applying \code{explicate-pred} to the predicate
  5303. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5304. %% translates to the promise $B_4$.
  5305. %% \[
  5306. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5307. %% \]
  5308. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5309. The way in which the \code{shrink} pass transforms logical operations
  5310. such as \code{and} and \code{or} can impact the quality of code
  5311. generated by \code{explicate-control}. For example, consider the
  5312. following program.
  5313. % cond_test_21.rkt, and_eq_input.py
  5314. \begin{lstlisting}
  5315. (if (and (eq? (read) 0) (eq? (read) 1))
  5316. 0
  5317. 42)
  5318. \end{lstlisting}
  5319. The \code{and} operation should transform into something that the
  5320. \code{explicate-pred} function can still analyze and descend through to
  5321. reach the underlying \code{eq?} conditions. Ideally, your
  5322. \code{explicate-control} pass should generate code similar to the
  5323. following for the above program.
  5324. \begin{center}
  5325. \begin{lstlisting}
  5326. start:
  5327. tmp1 = (read);
  5328. if (eq? tmp1 0) goto block40;
  5329. else goto block39;
  5330. block40:
  5331. tmp2 = (read);
  5332. if (eq? tmp2 1) goto block38;
  5333. else goto block39;
  5334. block38:
  5335. return 0;
  5336. block39:
  5337. return 42;
  5338. \end{lstlisting}
  5339. \end{center}
  5340. \begin{exercise}\normalfont
  5341. Implement the pass \code{explicate-control} by adding the cases for
  5342. Boolean constants and \key{if} to the \code{explicate-tail} and
  5343. \code{explicate-assign}. Implement the auxiliary function
  5344. \code{explicate-pred} for predicate contexts.
  5345. %
  5346. Create test cases that exercise all of the new cases in the code for
  5347. this pass.
  5348. %
  5349. Add the following entry to the list of \code{passes} in
  5350. \code{run-tests.rkt} and then run this script to test your compiler.
  5351. \begin{lstlisting}
  5352. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5353. \end{lstlisting}
  5354. \end{exercise}
  5355. \section{Select Instructions}
  5356. \label{sec:select-Rif}
  5357. \index{subject}{instruction selection}
  5358. The \code{select-instructions} pass translate \LangCIf{} to
  5359. \LangXIfVar{}. Recall that we implement this pass using three
  5360. auxiliary functions, one for each of the non-terminals $\Atm$,
  5361. $\Stmt$, and $\Tail$.
  5362. For $\Atm$, we have new cases for the Booleans. We take the usual
  5363. approach of encoding them as integers, with true as 1 and false as 0.
  5364. \[
  5365. \key{\#t} \Rightarrow \key{1}
  5366. \qquad
  5367. \key{\#f} \Rightarrow \key{0}
  5368. \]
  5369. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5370. be implemented in terms of \code{xorq} as we discussed at the
  5371. beginning of this section. Given an assignment
  5372. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5373. if the left-hand side $\itm{var}$ is
  5374. the same as $\Atm$, then just the \code{xorq} suffices.
  5375. \[
  5376. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5377. \quad\Rightarrow\quad
  5378. \key{xorq}~\key{\$}1\key{,}~\Var
  5379. \]
  5380. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5381. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5382. x86. Then we have
  5383. \[
  5384. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5385. \quad\Rightarrow\quad
  5386. \begin{array}{l}
  5387. \key{movq}~\Arg\key{,}~\Var\\
  5388. \key{xorq}~\key{\$}1\key{,}~\Var
  5389. \end{array}
  5390. \]
  5391. Next consider the cases for \code{eq?} and less-than comparison.
  5392. Translating these operations to x86 is slightly involved due to the
  5393. unusual nature of the \key{cmpq} instruction discussed above. We
  5394. recommend translating an assignment from \code{eq?} into the following
  5395. sequence of three instructions. \\
  5396. \begin{tabular}{lll}
  5397. \begin{minipage}{0.4\textwidth}
  5398. \begin{lstlisting}
  5399. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5400. \end{lstlisting}
  5401. \end{minipage}
  5402. &
  5403. $\Rightarrow$
  5404. &
  5405. \begin{minipage}{0.4\textwidth}
  5406. \begin{lstlisting}
  5407. cmpq |$\Arg_2$|, |$\Arg_1$|
  5408. sete %al
  5409. movzbq %al, |$\Var$|
  5410. \end{lstlisting}
  5411. \end{minipage}
  5412. \end{tabular} \\
  5413. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5414. and \key{if} statements. Both are straightforward to translate to
  5415. x86. A \key{goto} becomes a jump instruction.
  5416. \[
  5417. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5418. \]
  5419. An \key{if} statement becomes a compare instruction followed by a
  5420. conditional jump (for the ``then'' branch) and the fall-through is to
  5421. a regular jump (for the ``else'' branch).\\
  5422. \begin{tabular}{lll}
  5423. \begin{minipage}{0.4\textwidth}
  5424. \begin{lstlisting}
  5425. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5426. else goto |$\ell_2$|;
  5427. \end{lstlisting}
  5428. \end{minipage}
  5429. &
  5430. $\Rightarrow$
  5431. &
  5432. \begin{minipage}{0.4\textwidth}
  5433. \begin{lstlisting}
  5434. cmpq |$\Arg_2$|, |$\Arg_1$|
  5435. je |$\ell_1$|
  5436. jmp |$\ell_2$|
  5437. \end{lstlisting}
  5438. \end{minipage}
  5439. \end{tabular} \\
  5440. \begin{exercise}\normalfont
  5441. Expand your \code{select-instructions} pass to handle the new features
  5442. of the \LangIf{} language.
  5443. %
  5444. Add the following entry to the list of \code{passes} in
  5445. \code{run-tests.rkt}
  5446. \begin{lstlisting}
  5447. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5448. \end{lstlisting}
  5449. %
  5450. Run the script to test your compiler on all the test programs.
  5451. \end{exercise}
  5452. \section{Register Allocation}
  5453. \label{sec:register-allocation-Rif}
  5454. \index{subject}{register allocation}
  5455. The changes required for \LangIf{} affect liveness analysis, building the
  5456. interference graph, and assigning homes, but the graph coloring
  5457. algorithm itself does not change.
  5458. \subsection{Liveness Analysis}
  5459. \label{sec:liveness-analysis-Rif}
  5460. \index{subject}{liveness analysis}
  5461. Recall that for \LangVar{} we implemented liveness analysis for a single
  5462. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5463. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5464. produces many basic blocks arranged in a control-flow graph. We
  5465. recommend that you create a new auxiliary function named
  5466. \code{uncover-live-CFG} that applies liveness analysis to a
  5467. control-flow graph.
  5468. The first question we is: what order should we process the basic
  5469. blocks in the control-flow graph? Recall that to perform liveness
  5470. analysis on a basic block we need to know its live-after set. If a
  5471. basic block has no successors (i.e. no out-edges in the control flow
  5472. graph), then it has an empty live-after set and we can immediately
  5473. apply liveness analysis to it. If a basic block has some successors,
  5474. then we need to complete liveness analysis on those blocks first. In
  5475. graph theory, a sequence of nodes is in \emph{topological
  5476. order}\index{subject}{topological order} if each vertex comes before its
  5477. successors. We need the opposite, so we can transpose the graph
  5478. before computing a topological order.
  5479. %
  5480. Use the \code{tsort} and \code{transpose} functions of the Racket
  5481. \code{graph} package to accomplish this.
  5482. %
  5483. As an aside, a topological ordering is only guaranteed to exist if the
  5484. graph does not contain any cycles. That is indeed the case for the
  5485. control-flow graphs that we generate from \LangIf{} programs.
  5486. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5487. learn how to handle cycles in the control-flow graph.
  5488. You'll need to construct a directed graph to represent the
  5489. control-flow graph. Do not use the \code{directed-graph} of the
  5490. \code{graph} package because that only allows at most one edge between
  5491. each pair of vertices, but a control-flow graph may have multiple
  5492. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5493. the support code implements a graph representation that allows
  5494. multiple edges between a pair of vertices.
  5495. The next question is how to analyze jump instructions. Recall that in
  5496. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5497. \code{label->live} that maps each label to the set of live locations
  5498. at the beginning of its block. We use \code{label->live} to determine
  5499. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5500. that we have many basic blocks, \code{label->live} needs to be updated
  5501. as we process the blocks. In particular, after performing liveness
  5502. analysis on a block, we take the live-before set of its first
  5503. instruction and associate that with the block's label in the
  5504. \code{label->live}.
  5505. In \LangXIfVar{} we also have the conditional jump
  5506. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5507. this instruction is particularly interesting because during
  5508. compilation we do not know which way a conditional jump will go. So
  5509. we do not know whether to use the live-before set for the following
  5510. instruction or the live-before set for the $\itm{label}$. However,
  5511. there is no harm to the correctness of the compiler if we classify
  5512. more locations as live than the ones that are truly live during a
  5513. particular execution of the instruction. Thus, we can take the union
  5514. of the live-before sets from the following instruction and from the
  5515. mapping for $\itm{label}$ in \code{label->live}.
  5516. The auxiliary functions for computing the variables in an
  5517. instruction's argument and for computing the variables read-from ($R$)
  5518. or written-to ($W$) by an instruction need to be updated to handle the
  5519. new kinds of arguments and instructions in \LangXIfVar{}.
  5520. \begin{exercise}\normalfont
  5521. Update the \code{uncover-live} pass and implement the
  5522. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5523. to the control-flow graph. Add the following entry to the list of
  5524. \code{passes} in the \code{run-tests.rkt} script.
  5525. \begin{lstlisting}
  5526. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5527. \end{lstlisting}
  5528. \end{exercise}
  5529. \subsection{Build the Interference Graph}
  5530. \label{sec:build-interference-Rif}
  5531. Many of the new instructions in \LangXIfVar{} can be handled in the
  5532. same way as the instructions in \LangXVar{}. Thus, if your code was
  5533. already quite general, it will not need to be changed to handle the
  5534. new instructions. If you code is not general enough, we recommend that
  5535. you change your code to be more general. For example, you can factor
  5536. out the computing of the the read and write sets for each kind of
  5537. instruction into two auxiliary functions.
  5538. Note that the \key{movzbq} instruction requires some special care,
  5539. similar to the \key{movq} instruction. See rule number 1 in
  5540. Section~\ref{sec:build-interference}.
  5541. \begin{exercise}\normalfont
  5542. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5543. following entries to the list of \code{passes} in the
  5544. \code{run-tests.rkt} script.
  5545. \begin{lstlisting}
  5546. (list "build-interference" build-interference interp-pseudo-x86-1)
  5547. (list "allocate-registers" allocate-registers interp-x86-1)
  5548. \end{lstlisting}
  5549. Run the script to test your compiler on all the \LangIf{} test
  5550. programs.
  5551. \end{exercise}
  5552. \section{Patch Instructions}
  5553. The second argument of the \key{cmpq} instruction must not be an
  5554. immediate value (such as an integer). So if you are comparing two
  5555. immediates, we recommend inserting a \key{movq} instruction to put the
  5556. second argument in \key{rax}. Also, recall that instructions may have
  5557. at most one memory reference.
  5558. %
  5559. The second argument of the \key{movzbq} must be a register.
  5560. %
  5561. There are no special restrictions on the jump instructions.
  5562. \begin{exercise}\normalfont
  5563. %
  5564. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5565. %
  5566. Add the following entry to the list of \code{passes} in
  5567. \code{run-tests.rkt} and then run this script to test your compiler.
  5568. \begin{lstlisting}
  5569. (list "patch-instructions" patch-instructions interp-x86-1)
  5570. \end{lstlisting}
  5571. \end{exercise}
  5572. \begin{figure}[tbp]
  5573. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5574. \node (Rif) at (0,2) {\large \LangIf{}};
  5575. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5576. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5577. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5578. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5579. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5580. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5581. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5582. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5583. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5584. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5585. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5586. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5587. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5588. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5589. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5590. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5591. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5592. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5593. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5594. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5595. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5596. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5597. \end{tikzpicture}
  5598. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5599. \label{fig:Rif-passes}
  5600. \end{figure}
  5601. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5602. compilation of \LangIf{}.
  5603. \section{An Example Translation}
  5604. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5605. \LangIf{} translated to x86, showing the results of
  5606. \code{explicate-control}, \code{select-instructions}, and the final
  5607. x86 assembly code.
  5608. \begin{figure}[tbp]
  5609. \begin{tabular}{lll}
  5610. \begin{minipage}{0.4\textwidth}
  5611. % cond_test_20.rkt, eq_input.py
  5612. \begin{lstlisting}
  5613. (if (eq? (read) 1) 42 0)
  5614. \end{lstlisting}
  5615. $\Downarrow$
  5616. \begin{lstlisting}
  5617. start:
  5618. tmp7951 = (read);
  5619. if (eq? tmp7951 1)
  5620. goto block7952;
  5621. else
  5622. goto block7953;
  5623. block7952:
  5624. return 42;
  5625. block7953:
  5626. return 0;
  5627. \end{lstlisting}
  5628. $\Downarrow$
  5629. \begin{lstlisting}
  5630. start:
  5631. callq read_int
  5632. movq %rax, tmp7951
  5633. cmpq $1, tmp7951
  5634. je block7952
  5635. jmp block7953
  5636. block7953:
  5637. movq $0, %rax
  5638. jmp conclusion
  5639. block7952:
  5640. movq $42, %rax
  5641. jmp conclusion
  5642. \end{lstlisting}
  5643. \end{minipage}
  5644. &
  5645. $\Rightarrow\qquad$
  5646. \begin{minipage}{0.4\textwidth}
  5647. \begin{lstlisting}
  5648. start:
  5649. callq read_int
  5650. movq %rax, %rcx
  5651. cmpq $1, %rcx
  5652. je block7952
  5653. jmp block7953
  5654. block7953:
  5655. movq $0, %rax
  5656. jmp conclusion
  5657. block7952:
  5658. movq $42, %rax
  5659. jmp conclusion
  5660. .globl main
  5661. main:
  5662. pushq %rbp
  5663. movq %rsp, %rbp
  5664. pushq %r13
  5665. pushq %r12
  5666. pushq %rbx
  5667. pushq %r14
  5668. subq $0, %rsp
  5669. jmp start
  5670. conclusion:
  5671. addq $0, %rsp
  5672. popq %r14
  5673. popq %rbx
  5674. popq %r12
  5675. popq %r13
  5676. popq %rbp
  5677. retq
  5678. \end{lstlisting}
  5679. \end{minipage}
  5680. \end{tabular}
  5681. \caption{Example compilation of an \key{if} expression to x86.}
  5682. \label{fig:if-example-x86}
  5683. \end{figure}
  5684. \section{Challenge: Remove Jumps}
  5685. \label{sec:opt-jumps}
  5686. %% Recall that in the example output of \code{explicate-control} in
  5687. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5688. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5689. %% block. The first goal of this challenge assignment is to remove those
  5690. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5691. %% \code{explicate-control} on the left and shows the result of bypassing
  5692. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5693. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5694. %% \code{block55}. The optimized code on the right of
  5695. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5696. %% \code{then} branch jumping directly to \code{block55}. The story is
  5697. %% similar for the \code{else} branch, as well as for the two branches in
  5698. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5699. %% have been optimized in this way, there are no longer any jumps to
  5700. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5701. %% \begin{figure}[tbp]
  5702. %% \begin{tabular}{lll}
  5703. %% \begin{minipage}{0.4\textwidth}
  5704. %% \begin{lstlisting}
  5705. %% block62:
  5706. %% tmp54 = (read);
  5707. %% if (eq? tmp54 2) then
  5708. %% goto block59;
  5709. %% else
  5710. %% goto block60;
  5711. %% block61:
  5712. %% tmp53 = (read);
  5713. %% if (eq? tmp53 0) then
  5714. %% goto block57;
  5715. %% else
  5716. %% goto block58;
  5717. %% block60:
  5718. %% goto block56;
  5719. %% block59:
  5720. %% goto block55;
  5721. %% block58:
  5722. %% goto block56;
  5723. %% block57:
  5724. %% goto block55;
  5725. %% block56:
  5726. %% return (+ 700 77);
  5727. %% block55:
  5728. %% return (+ 10 32);
  5729. %% start:
  5730. %% tmp52 = (read);
  5731. %% if (eq? tmp52 1) then
  5732. %% goto block61;
  5733. %% else
  5734. %% goto block62;
  5735. %% \end{lstlisting}
  5736. %% \end{minipage}
  5737. %% &
  5738. %% $\Rightarrow$
  5739. %% &
  5740. %% \begin{minipage}{0.55\textwidth}
  5741. %% \begin{lstlisting}
  5742. %% block62:
  5743. %% tmp54 = (read);
  5744. %% if (eq? tmp54 2) then
  5745. %% goto block55;
  5746. %% else
  5747. %% goto block56;
  5748. %% block61:
  5749. %% tmp53 = (read);
  5750. %% if (eq? tmp53 0) then
  5751. %% goto block55;
  5752. %% else
  5753. %% goto block56;
  5754. %% block56:
  5755. %% return (+ 700 77);
  5756. %% block55:
  5757. %% return (+ 10 32);
  5758. %% start:
  5759. %% tmp52 = (read);
  5760. %% if (eq? tmp52 1) then
  5761. %% goto block61;
  5762. %% else
  5763. %% goto block62;
  5764. %% \end{lstlisting}
  5765. %% \end{minipage}
  5766. %% \end{tabular}
  5767. %% \caption{Optimize jumps by removing trivial blocks.}
  5768. %% \label{fig:optimize-jumps}
  5769. %% \end{figure}
  5770. %% The name of this pass is \code{optimize-jumps}. We recommend
  5771. %% implementing this pass in two phases. The first phrase builds a hash
  5772. %% table that maps labels to possibly improved labels. The second phase
  5773. %% changes the target of each \code{goto} to use the improved label. If
  5774. %% the label is for a trivial block, then the hash table should map the
  5775. %% label to the first non-trivial block that can be reached from this
  5776. %% label by jumping through trivial blocks. If the label is for a
  5777. %% non-trivial block, then the hash table should map the label to itself;
  5778. %% we do not want to change jumps to non-trivial blocks.
  5779. %% The first phase can be accomplished by constructing an empty hash
  5780. %% table, call it \code{short-cut}, and then iterating over the control
  5781. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5782. %% then update the hash table, mapping the block's source to the target
  5783. %% of the \code{goto}. Also, the hash table may already have mapped some
  5784. %% labels to the block's source, to you must iterate through the hash
  5785. %% table and update all of those so that they instead map to the target
  5786. %% of the \code{goto}.
  5787. %% For the second phase, we recommend iterating through the $\Tail$ of
  5788. %% each block in the program, updating the target of every \code{goto}
  5789. %% according to the mapping in \code{short-cut}.
  5790. %% \begin{exercise}\normalfont
  5791. %% Implement the \code{optimize-jumps} pass as a transformation from
  5792. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5793. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5794. %% example programs. Then check that your compiler still passes all of
  5795. %% your tests.
  5796. %% \end{exercise}
  5797. There is an opportunity for optimizing jumps that is apparent in the
  5798. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5799. ends with a jump to \code{block7953} and there are no other jumps to
  5800. \code{block7953} in the rest of the program. In this situation we can
  5801. avoid the runtime overhead of this jump by merging \code{block7953}
  5802. into the preceding block, in this case the \code{start} block.
  5803. Figure~\ref{fig:remove-jumps} shows the output of
  5804. \code{select-instructions} on the left and the result of this
  5805. optimization on the right.
  5806. \begin{figure}[tbp]
  5807. \begin{tabular}{lll}
  5808. \begin{minipage}{0.5\textwidth}
  5809. % cond_test_20.rkt
  5810. \begin{lstlisting}
  5811. start:
  5812. callq read_int
  5813. movq %rax, tmp7951
  5814. cmpq $1, tmp7951
  5815. je block7952
  5816. jmp block7953
  5817. block7953:
  5818. movq $0, %rax
  5819. jmp conclusion
  5820. block7952:
  5821. movq $42, %rax
  5822. jmp conclusion
  5823. \end{lstlisting}
  5824. \end{minipage}
  5825. &
  5826. $\Rightarrow\qquad$
  5827. \begin{minipage}{0.4\textwidth}
  5828. \begin{lstlisting}
  5829. start:
  5830. callq read_int
  5831. movq %rax, tmp7951
  5832. cmpq $1, tmp7951
  5833. je block7952
  5834. movq $0, %rax
  5835. jmp conclusion
  5836. block7952:
  5837. movq $42, %rax
  5838. jmp conclusion
  5839. \end{lstlisting}
  5840. \end{minipage}
  5841. \end{tabular}
  5842. \caption{Merging basic blocks by removing unnecessary jumps.}
  5843. \label{fig:remove-jumps}
  5844. \end{figure}
  5845. \begin{exercise}\normalfont
  5846. %
  5847. Implement a pass named \code{remove-jumps} that merges basic blocks
  5848. into their preceding basic block, when there is only one preceding
  5849. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5850. %
  5851. In the \code{run-tests.rkt} script, add the following entry to the
  5852. list of \code{passes} between \code{allocate-registers}
  5853. and \code{patch-instructions}.
  5854. \begin{lstlisting}
  5855. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5856. \end{lstlisting}
  5857. Run this script to test your compiler.
  5858. %
  5859. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5860. blocks on several test programs.
  5861. \end{exercise}
  5862. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5863. \chapter{Tuples and Garbage Collection}
  5864. \label{ch:Rvec}
  5865. \index{subject}{tuple}
  5866. \index{subject}{vector}
  5867. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5868. %% all the IR grammars are spelled out! \\ --Jeremy}
  5869. %% \margincomment{\scriptsize Be more explicit about how to deal with
  5870. %% the root stack. \\ --Jeremy}
  5871. In this chapter we study the implementation of mutable tuples, called
  5872. vectors in Racket. This language feature is the first to use the
  5873. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  5874. tuple is indefinite, that is, a tuple lives forever from the
  5875. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5876. is important to reclaim the space associated with a tuple when it is
  5877. no longer needed, which is why we also study \emph{garbage collection}
  5878. \emph{garbage collection} techniques in this chapter.
  5879. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5880. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5881. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5882. \code{void} value. The reason for including the later is that the
  5883. \code{vector-set!} operation returns a value of type
  5884. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5885. called the \code{Unit} type in the programming languages
  5886. literature. Racket's \code{Void} type is inhabited by a single value
  5887. \code{void} which corresponds to \code{unit} or \code{()} in the
  5888. literature~\citep{Pierce:2002hj}.}.
  5889. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5890. copying live objects back and forth between two halves of the
  5891. heap. The garbage collector requires coordination with the compiler so
  5892. that it can see all of the \emph{root} pointers, that is, pointers in
  5893. registers or on the procedure call stack.
  5894. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5895. discuss all the necessary changes and additions to the compiler
  5896. passes, including a new compiler pass named \code{expose-allocation}.
  5897. \section{The \LangVec{} Language}
  5898. \label{sec:r3}
  5899. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5900. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5901. \LangVec{} language includes three new forms: \code{vector} for creating a
  5902. tuple, \code{vector-ref} for reading an element of a tuple, and
  5903. \code{vector-set!} for writing to an element of a tuple. The program
  5904. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5905. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5906. the 3-tuple, demonstrating that tuples are first-class values. The
  5907. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5908. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5909. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5910. 1-tuple. So the result of the program is \code{42}.
  5911. \begin{figure}[tbp]
  5912. \centering
  5913. \fbox{
  5914. \begin{minipage}{0.96\textwidth}
  5915. \[
  5916. \begin{array}{lcl}
  5917. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5918. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5919. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5920. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5921. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5922. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5923. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5924. \mid \LP\key{not}\;\Exp\RP } \\
  5925. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5926. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5927. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5928. \mid \LP\key{vector-length}\;\Exp\RP \\
  5929. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5930. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5931. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5932. \LangVecM{} &::=& \Exp
  5933. \end{array}
  5934. \]
  5935. \end{minipage}
  5936. }
  5937. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5938. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5939. \label{fig:Rvec-concrete-syntax}
  5940. \end{figure}
  5941. \begin{figure}[tbp]
  5942. \begin{lstlisting}
  5943. (let ([t (vector 40 #t (vector 2))])
  5944. (if (vector-ref t 1)
  5945. (+ (vector-ref t 0)
  5946. (vector-ref (vector-ref t 2) 0))
  5947. 44))
  5948. \end{lstlisting}
  5949. \caption{Example program that creates tuples and reads from them.}
  5950. \label{fig:vector-eg}
  5951. \end{figure}
  5952. \begin{figure}[tp]
  5953. \centering
  5954. \fbox{
  5955. \begin{minipage}{0.96\textwidth}
  5956. \[
  5957. \begin{array}{lcl}
  5958. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5959. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5960. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5961. \mid \BOOL{\itm{bool}}
  5962. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5963. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5964. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5965. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5966. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5967. \end{array}
  5968. \]
  5969. \end{minipage}
  5970. }
  5971. \caption{The abstract syntax of \LangVec{}.}
  5972. \label{fig:Rvec-syntax}
  5973. \end{figure}
  5974. \index{subject}{allocate}
  5975. \index{subject}{heap allocate}
  5976. Tuples are our first encounter with heap-allocated data, which raises
  5977. several interesting issues. First, variable binding performs a
  5978. shallow-copy when dealing with tuples, which means that different
  5979. variables can refer to the same tuple, that is, different variables
  5980. can be \emph{aliases} for the same entity. Consider the following
  5981. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5982. Thus, the mutation through \code{t2} is visible when referencing the
  5983. tuple from \code{t1}, so the result of this program is \code{42}.
  5984. \index{subject}{alias}\index{subject}{mutation}
  5985. \begin{center}
  5986. \begin{minipage}{0.96\textwidth}
  5987. \begin{lstlisting}
  5988. (let ([t1 (vector 3 7)])
  5989. (let ([t2 t1])
  5990. (let ([_ (vector-set! t2 0 42)])
  5991. (vector-ref t1 0))))
  5992. \end{lstlisting}
  5993. \end{minipage}
  5994. \end{center}
  5995. The next issue concerns the lifetime of tuples. Of course, they are
  5996. created by the \code{vector} form, but when does their lifetime end?
  5997. Notice that \LangVec{} does not include an operation for deleting
  5998. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5999. of static scoping. For example, the following program returns
  6000. \code{42} even though the variable \code{w} goes out of scope prior to
  6001. the \code{vector-ref} that reads from the vector it was bound to.
  6002. \begin{center}
  6003. \begin{minipage}{0.96\textwidth}
  6004. \begin{lstlisting}
  6005. (let ([v (vector (vector 44))])
  6006. (let ([x (let ([w (vector 42)])
  6007. (let ([_ (vector-set! v 0 w)])
  6008. 0))])
  6009. (+ x (vector-ref (vector-ref v 0) 0))))
  6010. \end{lstlisting}
  6011. \end{minipage}
  6012. \end{center}
  6013. From the perspective of programmer-observable behavior, tuples live
  6014. forever. Of course, if they really lived forever, then many programs
  6015. would run out of memory.\footnote{The \LangVec{} language does not have
  6016. looping or recursive functions, so it is nigh impossible to write a
  6017. program in \LangVec{} that will run out of memory. However, we add
  6018. recursive functions in the next Chapter!} A Racket implementation
  6019. must therefore perform automatic garbage collection.
  6020. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  6021. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  6022. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  6023. terms of the corresponding operations in Racket. One subtle point is
  6024. that the \code{vector-set!} operation returns the \code{\#<void>}
  6025. value. The \code{\#<void>} value can be passed around just like other
  6026. values inside an \LangVec{} program and a \code{\#<void>} value can be
  6027. compared for equality with another \code{\#<void>} value. However,
  6028. there are no other operations specific to the the \code{\#<void>}
  6029. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  6030. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  6031. otherwise.
  6032. \begin{figure}[tbp]
  6033. \begin{lstlisting}
  6034. (define interp-Rvec-class
  6035. (class interp-Rif-class
  6036. (super-new)
  6037. (define/override (interp-op op)
  6038. (match op
  6039. ['eq? (lambda (v1 v2)
  6040. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6041. (and (boolean? v1) (boolean? v2))
  6042. (and (vector? v1) (vector? v2))
  6043. (and (void? v1) (void? v2)))
  6044. (eq? v1 v2)]))]
  6045. ['vector vector]
  6046. ['vector-length vector-length]
  6047. ['vector-ref vector-ref]
  6048. ['vector-set! vector-set!]
  6049. [else (super interp-op op)]
  6050. ))
  6051. (define/override ((interp-exp env) e)
  6052. (define recur (interp-exp env))
  6053. (match e
  6054. [(HasType e t) (recur e)]
  6055. [(Void) (void)]
  6056. [else ((super interp-exp env) e)]
  6057. ))
  6058. ))
  6059. (define (interp-Rvec p)
  6060. (send (new interp-Rvec-class) interp-program p))
  6061. \end{lstlisting}
  6062. \caption{Interpreter for the \LangVec{} language.}
  6063. \label{fig:interp-Rvec}
  6064. \end{figure}
  6065. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  6066. deserves some explanation. When allocating a vector, we need to know
  6067. which elements of the vector are pointers (i.e. are also vectors). We
  6068. can obtain this information during type checking. The type checker in
  6069. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  6070. expression, it also wraps every \key{vector} creation with the form
  6071. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  6072. %
  6073. To create the s-expression for the \code{Vector} type in
  6074. Figure~\ref{fig:type-check-Rvec}, we use the
  6075. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  6076. operator} \code{,@} to insert the list \code{t*} without its usual
  6077. start and end parentheses. \index{subject}{unquote-slicing}
  6078. \begin{figure}[tp]
  6079. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6080. (define type-check-Rvec-class
  6081. (class type-check-Rif-class
  6082. (super-new)
  6083. (inherit check-type-equal?)
  6084. (define/override (type-check-exp env)
  6085. (lambda (e)
  6086. (define recur (type-check-exp env))
  6087. (match e
  6088. [(Void) (values (Void) 'Void)]
  6089. [(Prim 'vector es)
  6090. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  6091. (define t `(Vector ,@t*))
  6092. (values (HasType (Prim 'vector e*) t) t)]
  6093. [(Prim 'vector-ref (list e1 (Int i)))
  6094. (define-values (e1^ t) (recur e1))
  6095. (match t
  6096. [`(Vector ,ts ...)
  6097. (unless (and (0 . <= . i) (i . < . (length ts)))
  6098. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6099. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  6100. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6101. [(Prim 'vector-set! (list e1 (Int i) arg) )
  6102. (define-values (e-vec t-vec) (recur e1))
  6103. (define-values (e-arg^ t-arg) (recur arg))
  6104. (match t-vec
  6105. [`(Vector ,ts ...)
  6106. (unless (and (0 . <= . i) (i . < . (length ts)))
  6107. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6108. (check-type-equal? (list-ref ts i) t-arg e)
  6109. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  6110. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  6111. [(Prim 'vector-length (list e))
  6112. (define-values (e^ t) (recur e))
  6113. (match t
  6114. [`(Vector ,ts ...)
  6115. (values (Prim 'vector-length (list e^)) 'Integer)]
  6116. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6117. [(Prim 'eq? (list arg1 arg2))
  6118. (define-values (e1 t1) (recur arg1))
  6119. (define-values (e2 t2) (recur arg2))
  6120. (match* (t1 t2)
  6121. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  6122. [(other wise) (check-type-equal? t1 t2 e)])
  6123. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  6124. [(HasType (Prim 'vector es) t)
  6125. ((type-check-exp env) (Prim 'vector es))]
  6126. [(HasType e1 t)
  6127. (define-values (e1^ t^) (recur e1))
  6128. (check-type-equal? t t^ e)
  6129. (values (HasType e1^ t) t)]
  6130. [else ((super type-check-exp env) e)]
  6131. )))
  6132. ))
  6133. (define (type-check-Rvec p)
  6134. (send (new type-check-Rvec-class) type-check-program p))
  6135. \end{lstlisting}
  6136. \caption{Type checker for the \LangVec{} language.}
  6137. \label{fig:type-check-Rvec}
  6138. \end{figure}
  6139. \section{Garbage Collection}
  6140. \label{sec:GC}
  6141. Here we study a relatively simple algorithm for garbage collection
  6142. that is the basis of state-of-the-art garbage
  6143. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  6144. particular, we describe a two-space copying
  6145. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  6146. perform the
  6147. copy~\citep{Cheney:1970aa}.
  6148. \index{subject}{copying collector}
  6149. \index{subject}{two-space copying collector}
  6150. Figure~\ref{fig:copying-collector} gives a
  6151. coarse-grained depiction of what happens in a two-space collector,
  6152. showing two time steps, prior to garbage collection (on the top) and
  6153. after garbage collection (on the bottom). In a two-space collector,
  6154. the heap is divided into two parts named the FromSpace and the
  6155. ToSpace. Initially, all allocations go to the FromSpace until there is
  6156. not enough room for the next allocation request. At that point, the
  6157. garbage collector goes to work to make more room.
  6158. \index{subject}{ToSpace}
  6159. \index{subject}{FromSpace}
  6160. The garbage collector must be careful not to reclaim tuples that will
  6161. be used by the program in the future. Of course, it is impossible in
  6162. general to predict what a program will do, but we can over approximate
  6163. the will-be-used tuples by preserving all tuples that could be
  6164. accessed by \emph{any} program given the current computer state. A
  6165. program could access any tuple whose address is in a register or on
  6166. the procedure call stack. These addresses are called the \emph{root
  6167. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  6168. transitively reachable from the root set. Thus, it is safe for the
  6169. garbage collector to reclaim the tuples that are not reachable in this
  6170. way.
  6171. So the goal of the garbage collector is twofold:
  6172. \begin{enumerate}
  6173. \item preserve all tuple that are reachable from the root set via a
  6174. path of pointers, that is, the \emph{live} tuples, and
  6175. \item reclaim the memory of everything else, that is, the
  6176. \emph{garbage}.
  6177. \end{enumerate}
  6178. A copying collector accomplishes this by copying all of the live
  6179. objects from the FromSpace into the ToSpace and then performs a sleight
  6180. of hand, treating the ToSpace as the new FromSpace and the old
  6181. FromSpace as the new ToSpace. In the example of
  6182. Figure~\ref{fig:copying-collector}, there are three pointers in the
  6183. root set, one in a register and two on the stack. All of the live
  6184. objects have been copied to the ToSpace (the right-hand side of
  6185. Figure~\ref{fig:copying-collector}) in a way that preserves the
  6186. pointer relationships. For example, the pointer in the register still
  6187. points to a 2-tuple whose first element is a 3-tuple and whose second
  6188. element is a 2-tuple. There are four tuples that are not reachable
  6189. from the root set and therefore do not get copied into the ToSpace.
  6190. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  6191. created by a well-typed program in \LangVec{} because it contains a
  6192. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  6193. We design the garbage collector to deal with cycles to begin with so
  6194. we will not need to revisit this issue.
  6195. \begin{figure}[tbp]
  6196. \centering
  6197. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  6198. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  6199. \caption{A copying collector in action.}
  6200. \label{fig:copying-collector}
  6201. \end{figure}
  6202. There are many alternatives to copying collectors (and their bigger
  6203. siblings, the generational collectors) when its comes to garbage
  6204. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  6205. reference counting~\citep{Collins:1960aa}. The strengths of copying
  6206. collectors are that allocation is fast (just a comparison and pointer
  6207. increment), there is no fragmentation, cyclic garbage is collected,
  6208. and the time complexity of collection only depends on the amount of
  6209. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  6210. main disadvantages of a two-space copying collector is that it uses a
  6211. lot of space and takes a long time to perform the copy, though these
  6212. problems are ameliorated in generational collectors. Racket and
  6213. Scheme programs tend to allocate many small objects and generate a lot
  6214. of garbage, so copying and generational collectors are a good fit.
  6215. Garbage collection is an active research topic, especially concurrent
  6216. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  6217. developing new techniques and revisiting old
  6218. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  6219. meet every year at the International Symposium on Memory Management to
  6220. present these findings.
  6221. \subsection{Graph Copying via Cheney's Algorithm}
  6222. \label{sec:cheney}
  6223. \index{subject}{Cheney's algorithm}
  6224. Let us take a closer look at the copying of the live objects. The
  6225. allocated objects and pointers can be viewed as a graph and we need to
  6226. copy the part of the graph that is reachable from the root set. To
  6227. make sure we copy all of the reachable vertices in the graph, we need
  6228. an exhaustive graph traversal algorithm, such as depth-first search or
  6229. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  6230. such algorithms take into account the possibility of cycles by marking
  6231. which vertices have already been visited, so as to ensure termination
  6232. of the algorithm. These search algorithms also use a data structure
  6233. such as a stack or queue as a to-do list to keep track of the vertices
  6234. that need to be visited. We use breadth-first search and a trick
  6235. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  6236. and copying tuples into the ToSpace.
  6237. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  6238. copy progresses. The queue is represented by a chunk of contiguous
  6239. memory at the beginning of the ToSpace, using two pointers to track
  6240. the front and the back of the queue. The algorithm starts by copying
  6241. all tuples that are immediately reachable from the root set into the
  6242. ToSpace to form the initial queue. When we copy a tuple, we mark the
  6243. old tuple to indicate that it has been visited. We discuss how this
  6244. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  6245. pointers inside the copied tuples in the queue still point back to the
  6246. FromSpace. Once the initial queue has been created, the algorithm
  6247. enters a loop in which it repeatedly processes the tuple at the front
  6248. of the queue and pops it off the queue. To process a tuple, the
  6249. algorithm copies all the tuple that are directly reachable from it to
  6250. the ToSpace, placing them at the back of the queue. The algorithm then
  6251. updates the pointers in the popped tuple so they point to the newly
  6252. copied tuples.
  6253. \begin{figure}[tbp]
  6254. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  6255. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  6256. \label{fig:cheney}
  6257. \end{figure}
  6258. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  6259. tuple whose second element is $42$ to the back of the queue. The other
  6260. pointer goes to a tuple that has already been copied, so we do not
  6261. need to copy it again, but we do need to update the pointer to the new
  6262. location. This can be accomplished by storing a \emph{forwarding
  6263. pointer} to the new location in the old tuple, back when we initially
  6264. copied the tuple into the ToSpace. This completes one step of the
  6265. algorithm. The algorithm continues in this way until the front of the
  6266. queue is empty, that is, until the front catches up with the back.
  6267. \subsection{Data Representation}
  6268. \label{sec:data-rep-gc}
  6269. The garbage collector places some requirements on the data
  6270. representations used by our compiler. First, the garbage collector
  6271. needs to distinguish between pointers and other kinds of data. There
  6272. are several ways to accomplish this.
  6273. \begin{enumerate}
  6274. \item Attached a tag to each object that identifies what type of
  6275. object it is~\citep{McCarthy:1960dz}.
  6276. \item Store different types of objects in different
  6277. regions~\citep{Steele:1977ab}.
  6278. \item Use type information from the program to either generate
  6279. type-specific code for collecting or to generate tables that can
  6280. guide the
  6281. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6282. \end{enumerate}
  6283. Dynamically typed languages, such as Lisp, need to tag objects
  6284. anyways, so option 1 is a natural choice for those languages.
  6285. However, \LangVec{} is a statically typed language, so it would be
  6286. unfortunate to require tags on every object, especially small and
  6287. pervasive objects like integers and Booleans. Option 3 is the
  6288. best-performing choice for statically typed languages, but comes with
  6289. a relatively high implementation complexity. To keep this chapter
  6290. within a 2-week time budget, we recommend a combination of options 1
  6291. and 2, using separate strategies for the stack and the heap.
  6292. Regarding the stack, we recommend using a separate stack for pointers,
  6293. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  6294. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6295. is, when a local variable needs to be spilled and is of type
  6296. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6297. stack instead of the normal procedure call stack. Furthermore, we
  6298. always spill vector-typed variables if they are live during a call to
  6299. the collector, thereby ensuring that no pointers are in registers
  6300. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6301. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6302. the data layout using a root stack. The root stack contains the two
  6303. pointers from the regular stack and also the pointer in the second
  6304. register.
  6305. \begin{figure}[tbp]
  6306. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6307. \caption{Maintaining a root stack to facilitate garbage collection.}
  6308. \label{fig:shadow-stack}
  6309. \end{figure}
  6310. The problem of distinguishing between pointers and other kinds of data
  6311. also arises inside of each tuple on the heap. We solve this problem by
  6312. attaching a tag, an extra 64-bits, to each
  6313. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6314. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6315. that we have drawn the bits in a big-endian way, from right-to-left,
  6316. with bit location 0 (the least significant bit) on the far right,
  6317. which corresponds to the direction of the x86 shifting instructions
  6318. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6319. is dedicated to specifying which elements of the tuple are pointers,
  6320. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6321. indicates there is a pointer and a 0 bit indicates some other kind of
  6322. data. The pointer mask starts at bit location 7. We have limited
  6323. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6324. the pointer mask. The tag also contains two other pieces of
  6325. information. The length of the tuple (number of elements) is stored in
  6326. bits location 1 through 6. Finally, the bit at location 0 indicates
  6327. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6328. value 1, then this tuple has not yet been copied. If the bit has
  6329. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6330. of a pointer are always zero anyways because our tuples are 8-byte
  6331. aligned.)
  6332. \begin{figure}[tbp]
  6333. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6334. \caption{Representation of tuples in the heap.}
  6335. \label{fig:tuple-rep}
  6336. \end{figure}
  6337. \subsection{Implementation of the Garbage Collector}
  6338. \label{sec:organize-gz}
  6339. \index{subject}{prelude}
  6340. An implementation of the copying collector is provided in the
  6341. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6342. interface to the garbage collector that is used by the compiler. The
  6343. \code{initialize} function creates the FromSpace, ToSpace, and root
  6344. stack and should be called in the prelude of the \code{main}
  6345. function. The arguments of \code{initialize} are the root stack size
  6346. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6347. good choice for both. The \code{initialize} function puts the address
  6348. of the beginning of the FromSpace into the global variable
  6349. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6350. the address that is 1-past the last element of the FromSpace. (We use
  6351. half-open intervals to represent chunks of
  6352. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6353. points to the first element of the root stack.
  6354. As long as there is room left in the FromSpace, your generated code
  6355. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6356. %
  6357. The amount of room left in FromSpace is the difference between the
  6358. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6359. function should be called when there is not enough room left in the
  6360. FromSpace for the next allocation. The \code{collect} function takes
  6361. a pointer to the current top of the root stack (one past the last item
  6362. that was pushed) and the number of bytes that need to be
  6363. allocated. The \code{collect} function performs the copying collection
  6364. and leaves the heap in a state such that the next allocation will
  6365. succeed.
  6366. \begin{figure}[tbp]
  6367. \begin{lstlisting}
  6368. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6369. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6370. int64_t* free_ptr;
  6371. int64_t* fromspace_begin;
  6372. int64_t* fromspace_end;
  6373. int64_t** rootstack_begin;
  6374. \end{lstlisting}
  6375. \caption{The compiler's interface to the garbage collector.}
  6376. \label{fig:gc-header}
  6377. \end{figure}
  6378. %% \begin{exercise}
  6379. %% In the file \code{runtime.c} you will find the implementation of
  6380. %% \code{initialize} and a partial implementation of \code{collect}.
  6381. %% The \code{collect} function calls another function, \code{cheney},
  6382. %% to perform the actual copy, and that function is left to the reader
  6383. %% to implement. The following is the prototype for \code{cheney}.
  6384. %% \begin{lstlisting}
  6385. %% static void cheney(int64_t** rootstack_ptr);
  6386. %% \end{lstlisting}
  6387. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6388. %% rootstack (which is an array of pointers). The \code{cheney} function
  6389. %% also communicates with \code{collect} through the global
  6390. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6391. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6392. %% the ToSpace:
  6393. %% \begin{lstlisting}
  6394. %% static int64_t* tospace_begin;
  6395. %% static int64_t* tospace_end;
  6396. %% \end{lstlisting}
  6397. %% The job of the \code{cheney} function is to copy all the live
  6398. %% objects (reachable from the root stack) into the ToSpace, update
  6399. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6400. %% update the root stack so that it points to the objects in the
  6401. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6402. %% and ToSpace.
  6403. %% \end{exercise}
  6404. %% \section{Compiler Passes}
  6405. %% \label{sec:code-generation-gc}
  6406. The introduction of garbage collection has a non-trivial impact on our
  6407. compiler passes. We introduce a new compiler pass named
  6408. \code{expose-allocation}. We make
  6409. significant changes to \code{select-instructions},
  6410. \code{build-interference}, \code{allocate-registers}, and
  6411. \code{print-x86} and make minor changes in several more passes. The
  6412. following program will serve as our running example. It creates two
  6413. tuples, one nested inside the other. Both tuples have length one. The
  6414. program accesses the element in the inner tuple tuple via two vector
  6415. references.
  6416. % tests/s2_17.rkt
  6417. \begin{lstlisting}
  6418. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6419. \end{lstlisting}
  6420. \section{Shrink}
  6421. \label{sec:shrink-Rvec}
  6422. Recall that the \code{shrink} pass translates the primitives operators
  6423. into a smaller set of primitives. Because this pass comes after type
  6424. checking, but before the passes that require the type information in
  6425. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6426. to wrap \code{HasType} around each AST node that it generates.
  6427. \section{Expose Allocation}
  6428. \label{sec:expose-allocation}
  6429. The pass \code{expose-allocation} lowers the \code{vector} creation
  6430. form into a conditional call to the collector followed by the
  6431. allocation. We choose to place the \code{expose-allocation} pass
  6432. before \code{remove-complex-opera*} because the code generated by
  6433. \code{expose-allocation} contains complex operands. We also place
  6434. \code{expose-allocation} before \code{explicate-control} because
  6435. \code{expose-allocation} introduces new variables using \code{let},
  6436. but \code{let} is gone after \code{explicate-control}.
  6437. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6438. extends \LangVec{} with the three new forms that we use in the translation
  6439. of the \code{vector} form.
  6440. \[
  6441. \begin{array}{lcl}
  6442. \Exp &::=& \cdots
  6443. \mid (\key{collect} \,\itm{int})
  6444. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6445. \mid (\key{global-value} \,\itm{name})
  6446. \end{array}
  6447. \]
  6448. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6449. $n$ bytes. It will become a call to the \code{collect} function in
  6450. \code{runtime.c} in \code{select-instructions}. The
  6451. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6452. \index{subject}{allocate}
  6453. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6454. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6455. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6456. a global variable, such as \code{free\_ptr}.
  6457. In the following, we show the transformation for the \code{vector}
  6458. form into 1) a sequence of let-bindings for the initializing
  6459. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6460. \code{allocate}, and 4) the initialization of the vector. In the
  6461. following, \itm{len} refers to the length of the vector and
  6462. \itm{bytes} is how many total bytes need to be allocated for the
  6463. vector, which is 8 for the tag plus \itm{len} times 8.
  6464. \begin{lstlisting}
  6465. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6466. |$\Longrightarrow$|
  6467. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6468. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6469. (global-value fromspace_end))
  6470. (void)
  6471. (collect |\itm{bytes}|))])
  6472. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6473. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6474. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6475. |$v$|) ... )))) ...)
  6476. \end{lstlisting}
  6477. In the above, we suppressed all of the \code{has-type} forms in the
  6478. output for the sake of readability. The placement of the initializing
  6479. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6480. sequence of \code{vector-set!} is important, as those expressions may
  6481. trigger garbage collection and we cannot have an allocated but
  6482. uninitialized tuple on the heap during a collection.
  6483. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6484. \code{expose-allocation} pass on our running example.
  6485. \begin{figure}[tbp]
  6486. % tests/s2_17.rkt
  6487. \begin{lstlisting}
  6488. (vector-ref
  6489. (vector-ref
  6490. (let ([vecinit7976
  6491. (let ([vecinit7972 42])
  6492. (let ([collectret7974
  6493. (if (< (+ (global-value free_ptr) 16)
  6494. (global-value fromspace_end))
  6495. (void)
  6496. (collect 16)
  6497. )])
  6498. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6499. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6500. alloc7971)
  6501. )
  6502. )
  6503. )
  6504. ])
  6505. (let ([collectret7978
  6506. (if (< (+ (global-value free_ptr) 16)
  6507. (global-value fromspace_end))
  6508. (void)
  6509. (collect 16)
  6510. )])
  6511. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6512. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6513. alloc7975)
  6514. )
  6515. )
  6516. )
  6517. 0)
  6518. 0)
  6519. \end{lstlisting}
  6520. \caption{Output of the \code{expose-allocation} pass, minus
  6521. all of the \code{has-type} forms.}
  6522. \label{fig:expose-alloc-output}
  6523. \end{figure}
  6524. \section{Remove Complex Operands}
  6525. \label{sec:remove-complex-opera-Rvec}
  6526. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6527. should all be treated as complex operands.
  6528. %% A new case for
  6529. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6530. %% handled carefully to prevent the \code{Prim} node from being separated
  6531. %% from its enclosing \code{HasType}.
  6532. Figure~\ref{fig:Rvec-anf-syntax}
  6533. shows the grammar for the output language \LangVecANF{} of this
  6534. pass, which is \LangVec{} in administrative normal form.
  6535. \begin{figure}[tp]
  6536. \centering
  6537. \fbox{
  6538. \begin{minipage}{0.96\textwidth}
  6539. \small
  6540. \[
  6541. \begin{array}{rcl}
  6542. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6543. \mid \VOID{} \\
  6544. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6545. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6546. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6547. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6548. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6549. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6550. \mid \LP\key{GlobalValue}~\Var\RP\\
  6551. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6552. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6553. \end{array}
  6554. \]
  6555. \end{minipage}
  6556. }
  6557. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6558. \label{fig:Rvec-anf-syntax}
  6559. \end{figure}
  6560. \section{Explicate Control and the \LangCVec{} language}
  6561. \label{sec:explicate-control-r3}
  6562. \begin{figure}[tp]
  6563. \fbox{
  6564. \begin{minipage}{0.96\textwidth}
  6565. \small
  6566. \[
  6567. \begin{array}{lcl}
  6568. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6569. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6570. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6571. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6572. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6573. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6574. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6575. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6576. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6577. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6578. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6579. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6580. \mid \GOTO{\itm{label}} } \\
  6581. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6582. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6583. \end{array}
  6584. \]
  6585. \end{minipage}
  6586. }
  6587. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6588. (Figure~\ref{fig:c1-syntax}).}
  6589. \label{fig:c2-syntax}
  6590. \end{figure}
  6591. The output of \code{explicate-control} is a program in the
  6592. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6593. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6594. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6595. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6596. \key{vector-set!}, and \key{global-value} expressions and the
  6597. \code{collect} statement. The \code{explicate-control} pass can treat
  6598. these new forms much like the other expression forms that we've
  6599. already encoutered.
  6600. \section{Select Instructions and the \LangXGlobal{} Language}
  6601. \label{sec:select-instructions-gc}
  6602. \index{subject}{instruction selection}
  6603. %% void (rep as zero)
  6604. %% allocate
  6605. %% collect (callq collect)
  6606. %% vector-ref
  6607. %% vector-set!
  6608. %% global (postpone)
  6609. In this pass we generate x86 code for most of the new operations that
  6610. were needed to compile tuples, including \code{Allocate},
  6611. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6612. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6613. the later has a different concrete syntax (see
  6614. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6615. \index{subject}{x86}
  6616. The \code{vector-ref} and \code{vector-set!} forms translate into
  6617. \code{movq} instructions. (The plus one in the offset is to get past
  6618. the tag at the beginning of the tuple representation.)
  6619. \begin{lstlisting}
  6620. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6621. |$\Longrightarrow$|
  6622. movq |$\itm{vec}'$|, %r11
  6623. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6624. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6625. |$\Longrightarrow$|
  6626. movq |$\itm{vec}'$|, %r11
  6627. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6628. movq $0, |$\itm{lhs'}$|
  6629. \end{lstlisting}
  6630. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6631. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6632. register \code{r11} ensures that offset expression
  6633. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6634. removing \code{r11} from consideration by the register allocating.
  6635. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6636. \code{rax}. Then the generated code for \code{vector-set!} would be
  6637. \begin{lstlisting}
  6638. movq |$\itm{vec}'$|, %rax
  6639. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6640. movq $0, |$\itm{lhs}'$|
  6641. \end{lstlisting}
  6642. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6643. \code{patch-instructions} would insert a move through \code{rax}
  6644. as follows.
  6645. \begin{lstlisting}
  6646. movq |$\itm{vec}'$|, %rax
  6647. movq |$\itm{arg}'$|, %rax
  6648. movq %rax, |$8(n+1)$|(%rax)
  6649. movq $0, |$\itm{lhs}'$|
  6650. \end{lstlisting}
  6651. But the above sequence of instructions does not work because we're
  6652. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6653. $\itm{arg}'$) at the same time!
  6654. We compile the \code{allocate} form to operations on the
  6655. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6656. is the next free address in the FromSpace, so we copy it into
  6657. \code{r11} and then move it forward by enough space for the tuple
  6658. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6659. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6660. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6661. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6662. tag is organized. We recommend using the Racket operations
  6663. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6664. during compilation. The type annotation in the \code{vector} form is
  6665. used to determine the pointer mask region of the tag.
  6666. \begin{lstlisting}
  6667. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6668. |$\Longrightarrow$|
  6669. movq free_ptr(%rip), %r11
  6670. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6671. movq $|$\itm{tag}$|, 0(%r11)
  6672. movq %r11, |$\itm{lhs}'$|
  6673. \end{lstlisting}
  6674. The \code{collect} form is compiled to a call to the \code{collect}
  6675. function in the runtime. The arguments to \code{collect} are 1) the
  6676. top of the root stack and 2) the number of bytes that need to be
  6677. allocated. We use another dedicated register, \code{r15}, to
  6678. store the pointer to the top of the root stack. So \code{r15} is not
  6679. available for use by the register allocator.
  6680. \begin{lstlisting}
  6681. (collect |$\itm{bytes}$|)
  6682. |$\Longrightarrow$|
  6683. movq %r15, %rdi
  6684. movq $|\itm{bytes}|, %rsi
  6685. callq collect
  6686. \end{lstlisting}
  6687. \begin{figure}[tp]
  6688. \fbox{
  6689. \begin{minipage}{0.96\textwidth}
  6690. \[
  6691. \begin{array}{lcl}
  6692. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6693. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  6694. & & \gray{ \key{main:} \; \Instr\ldots }
  6695. \end{array}
  6696. \]
  6697. \end{minipage}
  6698. }
  6699. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6700. \label{fig:x86-2-concrete}
  6701. \end{figure}
  6702. \begin{figure}[tp]
  6703. \fbox{
  6704. \begin{minipage}{0.96\textwidth}
  6705. \small
  6706. \[
  6707. \begin{array}{lcl}
  6708. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6709. \mid \BYTEREG{\Reg}} \\
  6710. &\mid& (\key{Global}~\Var) \\
  6711. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6712. \end{array}
  6713. \]
  6714. \end{minipage}
  6715. }
  6716. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6717. \label{fig:x86-2}
  6718. \end{figure}
  6719. The concrete and abstract syntax of the \LangXGlobal{} language is
  6720. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6721. differs from \LangXIf{} just in the addition of the form for global
  6722. variables.
  6723. %
  6724. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6725. \code{select-instructions} pass on the running example.
  6726. \begin{figure}[tbp]
  6727. \centering
  6728. % tests/s2_17.rkt
  6729. \begin{minipage}[t]{0.5\textwidth}
  6730. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6731. block35:
  6732. movq free_ptr(%rip), alloc9024
  6733. addq $16, free_ptr(%rip)
  6734. movq alloc9024, %r11
  6735. movq $131, 0(%r11)
  6736. movq alloc9024, %r11
  6737. movq vecinit9025, 8(%r11)
  6738. movq $0, initret9026
  6739. movq alloc9024, %r11
  6740. movq 8(%r11), tmp9034
  6741. movq tmp9034, %r11
  6742. movq 8(%r11), %rax
  6743. jmp conclusion
  6744. block36:
  6745. movq $0, collectret9027
  6746. jmp block35
  6747. block38:
  6748. movq free_ptr(%rip), alloc9020
  6749. addq $16, free_ptr(%rip)
  6750. movq alloc9020, %r11
  6751. movq $3, 0(%r11)
  6752. movq alloc9020, %r11
  6753. movq vecinit9021, 8(%r11)
  6754. movq $0, initret9022
  6755. movq alloc9020, vecinit9025
  6756. movq free_ptr(%rip), tmp9031
  6757. movq tmp9031, tmp9032
  6758. addq $16, tmp9032
  6759. movq fromspace_end(%rip), tmp9033
  6760. cmpq tmp9033, tmp9032
  6761. jl block36
  6762. jmp block37
  6763. block37:
  6764. movq %r15, %rdi
  6765. movq $16, %rsi
  6766. callq 'collect
  6767. jmp block35
  6768. block39:
  6769. movq $0, collectret9023
  6770. jmp block38
  6771. \end{lstlisting}
  6772. \end{minipage}
  6773. \begin{minipage}[t]{0.45\textwidth}
  6774. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6775. start:
  6776. movq $42, vecinit9021
  6777. movq free_ptr(%rip), tmp9028
  6778. movq tmp9028, tmp9029
  6779. addq $16, tmp9029
  6780. movq fromspace_end(%rip), tmp9030
  6781. cmpq tmp9030, tmp9029
  6782. jl block39
  6783. jmp block40
  6784. block40:
  6785. movq %r15, %rdi
  6786. movq $16, %rsi
  6787. callq 'collect
  6788. jmp block38
  6789. \end{lstlisting}
  6790. \end{minipage}
  6791. \caption{Output of the \code{select-instructions} pass.}
  6792. \label{fig:select-instr-output-gc}
  6793. \end{figure}
  6794. \clearpage
  6795. \section{Register Allocation}
  6796. \label{sec:reg-alloc-gc}
  6797. \index{subject}{register allocation}
  6798. As discussed earlier in this chapter, the garbage collector needs to
  6799. access all the pointers in the root set, that is, all variables that
  6800. are vectors. It will be the responsibility of the register allocator
  6801. to make sure that:
  6802. \begin{enumerate}
  6803. \item the root stack is used for spilling vector-typed variables, and
  6804. \item if a vector-typed variable is live during a call to the
  6805. collector, it must be spilled to ensure it is visible to the
  6806. collector.
  6807. \end{enumerate}
  6808. The later responsibility can be handled during construction of the
  6809. interference graph, by adding interference edges between the call-live
  6810. vector-typed variables and all the callee-saved registers. (They
  6811. already interfere with the caller-saved registers.) The type
  6812. information for variables is in the \code{Program} form, so we
  6813. recommend adding another parameter to the \code{build-interference}
  6814. function to communicate this alist.
  6815. The spilling of vector-typed variables to the root stack can be
  6816. handled after graph coloring, when choosing how to assign the colors
  6817. (integers) to registers and stack locations. The \code{Program} output
  6818. of this pass changes to also record the number of spills to the root
  6819. stack.
  6820. % build-interference
  6821. %
  6822. % callq
  6823. % extra parameter for var->type assoc. list
  6824. % update 'program' and 'if'
  6825. % allocate-registers
  6826. % allocate spilled vectors to the rootstack
  6827. % don't change color-graph
  6828. \section{Print x86}
  6829. \label{sec:print-x86-gc}
  6830. \index{subject}{prelude}\index{subject}{conclusion}
  6831. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6832. \code{print-x86} pass on the running example. In the prelude and
  6833. conclusion of the \code{main} function, we treat the root stack very
  6834. much like the regular stack in that we move the root stack pointer
  6835. (\code{r15}) to make room for the spills to the root stack, except
  6836. that the root stack grows up instead of down. For the running
  6837. example, there was just one spill so we increment \code{r15} by 8
  6838. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6839. One issue that deserves special care is that there may be a call to
  6840. \code{collect} prior to the initializing assignments for all the
  6841. variables in the root stack. We do not want the garbage collector to
  6842. accidentally think that some uninitialized variable is a pointer that
  6843. needs to be followed. Thus, we zero-out all locations on the root
  6844. stack in the prelude of \code{main}. In
  6845. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6846. %
  6847. \lstinline{movq $0, (%r15)}
  6848. %
  6849. accomplishes this task. The garbage collector tests each root to see
  6850. if it is null prior to dereferencing it.
  6851. \begin{figure}[htbp]
  6852. \begin{minipage}[t]{0.5\textwidth}
  6853. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6854. block35:
  6855. movq free_ptr(%rip), %rcx
  6856. addq $16, free_ptr(%rip)
  6857. movq %rcx, %r11
  6858. movq $131, 0(%r11)
  6859. movq %rcx, %r11
  6860. movq -8(%r15), %rax
  6861. movq %rax, 8(%r11)
  6862. movq $0, %rdx
  6863. movq %rcx, %r11
  6864. movq 8(%r11), %rcx
  6865. movq %rcx, %r11
  6866. movq 8(%r11), %rax
  6867. jmp conclusion
  6868. block36:
  6869. movq $0, %rcx
  6870. jmp block35
  6871. block38:
  6872. movq free_ptr(%rip), %rcx
  6873. addq $16, free_ptr(%rip)
  6874. movq %rcx, %r11
  6875. movq $3, 0(%r11)
  6876. movq %rcx, %r11
  6877. movq %rbx, 8(%r11)
  6878. movq $0, %rdx
  6879. movq %rcx, -8(%r15)
  6880. movq free_ptr(%rip), %rcx
  6881. addq $16, %rcx
  6882. movq fromspace_end(%rip), %rdx
  6883. cmpq %rdx, %rcx
  6884. jl block36
  6885. movq %r15, %rdi
  6886. movq $16, %rsi
  6887. callq collect
  6888. jmp block35
  6889. block39:
  6890. movq $0, %rcx
  6891. jmp block38
  6892. \end{lstlisting}
  6893. \end{minipage}
  6894. \begin{minipage}[t]{0.45\textwidth}
  6895. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6896. start:
  6897. movq $42, %rbx
  6898. movq free_ptr(%rip), %rdx
  6899. addq $16, %rdx
  6900. movq fromspace_end(%rip), %rcx
  6901. cmpq %rcx, %rdx
  6902. jl block39
  6903. movq %r15, %rdi
  6904. movq $16, %rsi
  6905. callq collect
  6906. jmp block38
  6907. .globl main
  6908. main:
  6909. pushq %rbp
  6910. movq %rsp, %rbp
  6911. pushq %r13
  6912. pushq %r12
  6913. pushq %rbx
  6914. pushq %r14
  6915. subq $0, %rsp
  6916. movq $16384, %rdi
  6917. movq $16384, %rsi
  6918. callq initialize
  6919. movq rootstack_begin(%rip), %r15
  6920. movq $0, (%r15)
  6921. addq $8, %r15
  6922. jmp start
  6923. conclusion:
  6924. subq $8, %r15
  6925. addq $0, %rsp
  6926. popq %r14
  6927. popq %rbx
  6928. popq %r12
  6929. popq %r13
  6930. popq %rbp
  6931. retq
  6932. \end{lstlisting}
  6933. \end{minipage}
  6934. \caption{Output of the \code{print-x86} pass.}
  6935. \label{fig:print-x86-output-gc}
  6936. \end{figure}
  6937. \begin{figure}[p]
  6938. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6939. \node (Rvec) at (0,2) {\large \LangVec{}};
  6940. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6941. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6942. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6943. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6944. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6945. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6946. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6947. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6948. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6949. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6950. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6951. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6952. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6953. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6954. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6955. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6956. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6957. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6958. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6959. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6960. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6961. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6962. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6963. \end{tikzpicture}
  6964. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6965. \label{fig:Rvec-passes}
  6966. \end{figure}
  6967. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6968. for the compilation of \LangVec{}.
  6969. \section{Challenge: Simple Structures}
  6970. \label{sec:simple-structures}
  6971. \index{subject}{struct}
  6972. \index{subject}{structure}
  6973. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6974. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6975. Recall that a \code{struct} in Typed Racket is a user-defined data
  6976. type that contains named fields and that is heap allocated, similar to
  6977. a vector. The following is an example of a structure definition, in
  6978. this case the definition of a \code{point} type.
  6979. \begin{lstlisting}
  6980. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6981. \end{lstlisting}
  6982. \begin{figure}[tbp]
  6983. \centering
  6984. \fbox{
  6985. \begin{minipage}{0.96\textwidth}
  6986. \[
  6987. \begin{array}{lcl}
  6988. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6989. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6990. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6991. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6992. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6993. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6994. \mid (\key{and}\;\Exp\;\Exp)
  6995. \mid (\key{or}\;\Exp\;\Exp)
  6996. \mid (\key{not}\;\Exp) } \\
  6997. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6998. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6999. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  7000. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  7001. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  7002. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  7003. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  7004. \LangStruct{} &::=& \Def \ldots \; \Exp
  7005. \end{array}
  7006. \]
  7007. \end{minipage}
  7008. }
  7009. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  7010. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7011. \label{fig:r3s-concrete-syntax}
  7012. \end{figure}
  7013. An instance of a structure is created using function call syntax, with
  7014. the name of the structure in the function position:
  7015. \begin{lstlisting}
  7016. (point 7 12)
  7017. \end{lstlisting}
  7018. Function-call syntax is also used to read the value in a field of a
  7019. structure. The function name is formed by the structure name, a dash,
  7020. and the field name. The following example uses \code{point-x} and
  7021. \code{point-y} to access the \code{x} and \code{y} fields of two point
  7022. instances.
  7023. \begin{center}
  7024. \begin{lstlisting}
  7025. (let ([pt1 (point 7 12)])
  7026. (let ([pt2 (point 4 3)])
  7027. (+ (- (point-x pt1) (point-x pt2))
  7028. (- (point-y pt1) (point-y pt2)))))
  7029. \end{lstlisting}
  7030. \end{center}
  7031. Similarly, to write to a field of a structure, use its set function,
  7032. whose name starts with \code{set-}, followed by the structure name,
  7033. then a dash, then the field name, and concluded with an exclamation
  7034. mark. The following example uses \code{set-point-x!} to change the
  7035. \code{x} field from \code{7} to \code{42}.
  7036. \begin{center}
  7037. \begin{lstlisting}
  7038. (let ([pt (point 7 12)])
  7039. (let ([_ (set-point-x! pt 42)])
  7040. (point-x pt)))
  7041. \end{lstlisting}
  7042. \end{center}
  7043. \begin{exercise}\normalfont
  7044. Extend your compiler with support for simple structures, compiling
  7045. \LangStruct{} to x86 assembly code. Create five new test cases that use
  7046. structures and test your compiler.
  7047. \end{exercise}
  7048. \section{Challenge: Generational Collection}
  7049. The copying collector described in Section~\ref{sec:GC} can incur
  7050. significant runtime overhead because the call to \code{collect} takes
  7051. time proportional to all of the live data. One way to reduce this
  7052. overhead is to reduce how much data is inspected in each call to
  7053. \code{collect}. In particular, researchers have observed that recently
  7054. allocated data is more likely to become garbage then data that has
  7055. survived one or more previous calls to \code{collect}. This insight
  7056. motivated the creation of \emph{generational garbage collectors}
  7057. \index{subject}{generational garbage collector} that
  7058. 1) segregates data according to its age into two or more generations,
  7059. 2) allocates less space for younger generations, so collecting them is
  7060. faster, and more space for the older generations, and 3) performs
  7061. collection on the younger generations more frequently then for older
  7062. generations~\citep{Wilson:1992fk}.
  7063. For this challenge assignment, the goal is to adapt the copying
  7064. collector implemented in \code{runtime.c} to use two generations, one
  7065. for young data and one for old data. Each generation consists of a
  7066. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  7067. \code{collect} function to use the two generations.
  7068. \begin{enumerate}
  7069. \item Copy the young generation's FromSpace to its ToSpace then switch
  7070. the role of the ToSpace and FromSpace
  7071. \item If there is enough space for the requested number of bytes in
  7072. the young FromSpace, then return from \code{collect}.
  7073. \item If there is not enough space in the young FromSpace for the
  7074. requested bytes, then move the data from the young generation to the
  7075. old one with the following steps:
  7076. \begin{enumerate}
  7077. \item If there is enough room in the old FromSpace, copy the young
  7078. FromSpace to the old FromSpace and then return.
  7079. \item If there is not enough room in the old FromSpace, then collect
  7080. the old generation by copying the old FromSpace to the old ToSpace
  7081. and swap the roles of the old FromSpace and ToSpace.
  7082. \item If there is enough room now, copy the young FromSpace to the
  7083. old FromSpace and return. Otherwise, allocate a larger FromSpace
  7084. and ToSpace for the old generation. Copy the young FromSpace and
  7085. the old FromSpace into the larger FromSpace for the old
  7086. generation and then return.
  7087. \end{enumerate}
  7088. \end{enumerate}
  7089. We recommend that you generalize the \code{cheney} function so that it
  7090. can be used for all the copies mentioned above: between the young
  7091. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  7092. between the young FromSpace and old FromSpace. This can be
  7093. accomplished by adding parameters to \code{cheney} that replace its
  7094. use of the global variables \code{fromspace\_begin},
  7095. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  7096. Note that the collection of the young generation does not traverse the
  7097. old generation. This introduces a potential problem: there may be
  7098. young data that is only reachable through pointers in the old
  7099. generation. If these pointers are not taken into account, the
  7100. collector could throw away young data that is live! One solution,
  7101. called \emph{pointer recording}, is to maintain a set of all the
  7102. pointers from the old generation into the new generation and consider
  7103. this set as part of the root set. To maintain this set, the compiler
  7104. must insert extra instructions around every \code{vector-set!}. If the
  7105. vector being modified is in the old generation, and if the value being
  7106. written is a pointer into the new generation, than that pointer must
  7107. be added to the set. Also, if the value being overwritten was a
  7108. pointer into the new generation, then that pointer should be removed
  7109. from the set.
  7110. \begin{exercise}\normalfont
  7111. Adapt the \code{collect} function in \code{runtime.c} to implement
  7112. generational garbage collection, as outlined in this section.
  7113. Update the code generation for \code{vector-set!} to implement
  7114. pointer recording. Make sure that your new compiler and runtime
  7115. passes your test suite.
  7116. \end{exercise}
  7117. % Further Reading
  7118. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7119. \chapter{Functions}
  7120. \label{ch:Rfun}
  7121. \index{subject}{function}
  7122. This chapter studies the compilation of functions similar to those
  7123. found in the C language. This corresponds to a subset of Typed Racket
  7124. in which only top-level function definitions are allowed. This kind of
  7125. function is an important stepping stone to implementing
  7126. lexically-scoped functions, that is, \key{lambda} abstractions, which
  7127. is the topic of Chapter~\ref{ch:Rlam}.
  7128. \section{The \LangFun{} Language}
  7129. The concrete and abstract syntax for function definitions and function
  7130. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  7131. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  7132. \LangFun{} begin with zero or more function definitions. The function
  7133. names from these definitions are in-scope for the entire program,
  7134. including all other function definitions (so the ordering of function
  7135. definitions does not matter). The concrete syntax for function
  7136. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  7137. where the first expression must
  7138. evaluate to a function and the rest are the arguments.
  7139. The abstract syntax for function application is
  7140. $\APPLY{\Exp}{\Exp\ldots}$.
  7141. %% The syntax for function application does not include an explicit
  7142. %% keyword, which is error prone when using \code{match}. To alleviate
  7143. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  7144. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  7145. Functions are first-class in the sense that a function pointer
  7146. \index{subject}{function pointer} is data and can be stored in memory or passed
  7147. as a parameter to another function. Thus, we introduce a function
  7148. type, written
  7149. \begin{lstlisting}
  7150. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  7151. \end{lstlisting}
  7152. for a function whose $n$ parameters have the types $\Type_1$ through
  7153. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  7154. these functions (with respect to Racket functions) is that they are
  7155. not lexically scoped. That is, the only external entities that can be
  7156. referenced from inside a function body are other globally-defined
  7157. functions. The syntax of \LangFun{} prevents functions from being nested
  7158. inside each other.
  7159. \begin{figure}[tp]
  7160. \centering
  7161. \fbox{
  7162. \begin{minipage}{0.96\textwidth}
  7163. \small
  7164. \[
  7165. \begin{array}{lcl}
  7166. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  7167. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  7168. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  7169. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7170. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7171. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  7172. \mid (\key{and}\;\Exp\;\Exp)
  7173. \mid (\key{or}\;\Exp\;\Exp)
  7174. \mid (\key{not}\;\Exp)} \\
  7175. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7176. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7177. (\key{vector-ref}\;\Exp\;\Int)} \\
  7178. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7179. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  7180. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  7181. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  7182. \LangFunM{} &::=& \Def \ldots \; \Exp
  7183. \end{array}
  7184. \]
  7185. \end{minipage}
  7186. }
  7187. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7188. \label{fig:Rfun-concrete-syntax}
  7189. \end{figure}
  7190. \begin{figure}[tp]
  7191. \centering
  7192. \fbox{
  7193. \begin{minipage}{0.96\textwidth}
  7194. \small
  7195. \[
  7196. \begin{array}{lcl}
  7197. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7198. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7199. &\mid& \gray{ \BOOL{\itm{bool}}
  7200. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7201. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  7202. \mid \APPLY{\Exp}{\Exp\ldots}\\
  7203. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  7204. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  7205. \end{array}
  7206. \]
  7207. \end{minipage}
  7208. }
  7209. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  7210. \label{fig:Rfun-syntax}
  7211. \end{figure}
  7212. The program in Figure~\ref{fig:Rfun-function-example} is a
  7213. representative example of defining and using functions in \LangFun{}. We
  7214. define a function \code{map-vec} that applies some other function
  7215. \code{f} to both elements of a vector and returns a new
  7216. vector containing the results. We also define a function \code{add1}.
  7217. The program applies
  7218. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  7219. \code{(vector 1 42)}, from which we return the \code{42}.
  7220. \begin{figure}[tbp]
  7221. \begin{lstlisting}
  7222. (define (map-vec [f : (Integer -> Integer)]
  7223. [v : (Vector Integer Integer)])
  7224. : (Vector Integer Integer)
  7225. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  7226. (define (add1 [x : Integer]) : Integer
  7227. (+ x 1))
  7228. (vector-ref (map-vec add1 (vector 0 41)) 1)
  7229. \end{lstlisting}
  7230. \caption{Example of using functions in \LangFun{}.}
  7231. \label{fig:Rfun-function-example}
  7232. \end{figure}
  7233. The definitional interpreter for \LangFun{} is in
  7234. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  7235. responsible for setting up the mutual recursion between the top-level
  7236. function definitions. We use the classic back-patching \index{subject}{back-patching}
  7237. approach that uses mutable variables and makes two passes over the function
  7238. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  7239. top-level environment using a mutable cons cell for each function
  7240. definition. Note that the \code{lambda} value for each function is
  7241. incomplete; it does not yet include the environment. Once the
  7242. top-level environment is constructed, we then iterate over it and
  7243. update the \code{lambda} values to use the top-level environment.
  7244. \begin{figure}[tp]
  7245. \begin{lstlisting}
  7246. (define interp-Rfun-class
  7247. (class interp-Rvec-class
  7248. (super-new)
  7249. (define/override ((interp-exp env) e)
  7250. (define recur (interp-exp env))
  7251. (match e
  7252. [(Var x) (unbox (dict-ref env x))]
  7253. [(Let x e body)
  7254. (define new-env (dict-set env x (box (recur e))))
  7255. ((interp-exp new-env) body)]
  7256. [(Apply fun args)
  7257. (define fun-val (recur fun))
  7258. (define arg-vals (for/list ([e args]) (recur e)))
  7259. (match fun-val
  7260. [`(function (,xs ...) ,body ,fun-env)
  7261. (define params-args (for/list ([x xs] [arg arg-vals])
  7262. (cons x (box arg))))
  7263. (define new-env (append params-args fun-env))
  7264. ((interp-exp new-env) body)]
  7265. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  7266. [else ((super interp-exp env) e)]
  7267. ))
  7268. (define/public (interp-def d)
  7269. (match d
  7270. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  7271. (cons f (box `(function ,xs ,body ())))]))
  7272. (define/override (interp-program p)
  7273. (match p
  7274. [(ProgramDefsExp info ds body)
  7275. (let ([top-level (for/list ([d ds]) (interp-def d))])
  7276. (for/list ([f (in-dict-values top-level)])
  7277. (set-box! f (match (unbox f)
  7278. [`(function ,xs ,body ())
  7279. `(function ,xs ,body ,top-level)])))
  7280. ((interp-exp top-level) body))]))
  7281. ))
  7282. (define (interp-Rfun p)
  7283. (send (new interp-Rfun-class) interp-program p))
  7284. \end{lstlisting}
  7285. \caption{Interpreter for the \LangFun{} language.}
  7286. \label{fig:interp-Rfun}
  7287. \end{figure}
  7288. %\margincomment{TODO: explain type checker}
  7289. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  7290. \begin{figure}[tp]
  7291. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7292. (define type-check-Rfun-class
  7293. (class type-check-Rvec-class
  7294. (super-new)
  7295. (inherit check-type-equal?)
  7296. (define/public (type-check-apply env e es)
  7297. (define-values (e^ ty) ((type-check-exp env) e))
  7298. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7299. ((type-check-exp env) e)))
  7300. (match ty
  7301. [`(,ty^* ... -> ,rt)
  7302. (for ([arg-ty ty*] [param-ty ty^*])
  7303. (check-type-equal? arg-ty param-ty (Apply e es)))
  7304. (values e^ e* rt)]))
  7305. (define/override (type-check-exp env)
  7306. (lambda (e)
  7307. (match e
  7308. [(FunRef f)
  7309. (values (FunRef f) (dict-ref env f))]
  7310. [(Apply e es)
  7311. (define-values (e^ es^ rt) (type-check-apply env e es))
  7312. (values (Apply e^ es^) rt)]
  7313. [(Call e es)
  7314. (define-values (e^ es^ rt) (type-check-apply env e es))
  7315. (values (Call e^ es^) rt)]
  7316. [else ((super type-check-exp env) e)])))
  7317. (define/public (type-check-def env)
  7318. (lambda (e)
  7319. (match e
  7320. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7321. (define new-env (append (map cons xs ps) env))
  7322. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7323. (check-type-equal? ty^ rt body)
  7324. (Def f p:t* rt info body^)])))
  7325. (define/public (fun-def-type d)
  7326. (match d
  7327. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7328. (define/override (type-check-program e)
  7329. (match e
  7330. [(ProgramDefsExp info ds body)
  7331. (define new-env (for/list ([d ds])
  7332. (cons (Def-name d) (fun-def-type d))))
  7333. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7334. (define-values (body^ ty) ((type-check-exp new-env) body))
  7335. (check-type-equal? ty 'Integer body)
  7336. (ProgramDefsExp info ds^ body^)]))))
  7337. (define (type-check-Rfun p)
  7338. (send (new type-check-Rfun-class) type-check-program p))
  7339. \end{lstlisting}
  7340. \caption{Type checker for the \LangFun{} language.}
  7341. \label{fig:type-check-Rfun}
  7342. \end{figure}
  7343. \section{Functions in x86}
  7344. \label{sec:fun-x86}
  7345. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  7346. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7347. %% \margincomment{\tiny Talk about the return address on the
  7348. %% stack and what callq and retq does.\\ --Jeremy }
  7349. The x86 architecture provides a few features to support the
  7350. implementation of functions. We have already seen that x86 provides
  7351. labels so that one can refer to the location of an instruction, as is
  7352. needed for jump instructions. Labels can also be used to mark the
  7353. beginning of the instructions for a function. Going further, we can
  7354. obtain the address of a label by using the \key{leaq} instruction and
  7355. PC-relative addressing. For example, the following puts the
  7356. address of the \code{add1} label into the \code{rbx} register.
  7357. \begin{lstlisting}
  7358. leaq add1(%rip), %rbx
  7359. \end{lstlisting}
  7360. The instruction pointer register \key{rip} (aka. the program counter
  7361. \index{subject}{program counter}) always points to the next instruction to be
  7362. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7363. linker computes the distance $d$ between the address of \code{add1}
  7364. and where the \code{rip} would be at that moment and then changes
  7365. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7366. the address of \code{add1}.
  7367. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7368. jump to a function whose location is given by a label. To support
  7369. function calls in this chapter we instead will be jumping to a
  7370. function whose location is given by an address in a register, that is,
  7371. we need to make an \emph{indirect function call}. The x86 syntax for
  7372. this is a \code{callq} instruction but with an asterisk before the
  7373. register name.\index{subject}{indirect function call}
  7374. \begin{lstlisting}
  7375. callq *%rbx
  7376. \end{lstlisting}
  7377. \subsection{Calling Conventions}
  7378. \index{subject}{calling conventions}
  7379. The \code{callq} instruction provides partial support for implementing
  7380. functions: it pushes the return address on the stack and it jumps to
  7381. the target. However, \code{callq} does not handle
  7382. \begin{enumerate}
  7383. \item parameter passing,
  7384. \item pushing frames on the procedure call stack and popping them off,
  7385. or
  7386. \item determining how registers are shared by different functions.
  7387. \end{enumerate}
  7388. Regarding (1) parameter passing, recall that the following six
  7389. registers are used to pass arguments to a function, in this order.
  7390. \begin{lstlisting}
  7391. rdi rsi rdx rcx r8 r9
  7392. \end{lstlisting}
  7393. If there are
  7394. more than six arguments, then the convention is to use space on the
  7395. frame of the caller for the rest of the arguments. However, to ease
  7396. the implementation of efficient tail calls
  7397. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7398. arguments.
  7399. %
  7400. Also recall that the register \code{rax} is for the return value of
  7401. the function.
  7402. \index{subject}{prelude}\index{subject}{conclusion}
  7403. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  7404. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  7405. the stack grows down, with each function call using a chunk of space
  7406. called a frame. The caller sets the stack pointer, register
  7407. \code{rsp}, to the last data item in its frame. The callee must not
  7408. change anything in the caller's frame, that is, anything that is at or
  7409. above the stack pointer. The callee is free to use locations that are
  7410. below the stack pointer.
  7411. Recall that we are storing variables of vector type on the root stack.
  7412. So the prelude needs to move the root stack pointer \code{r15} up and
  7413. the conclusion needs to move the root stack pointer back down. Also,
  7414. the prelude must initialize to \code{0} this frame's slots in the root
  7415. stack to signal to the garbage collector that those slots do not yet
  7416. contain a pointer to a vector. Otherwise the garbage collector will
  7417. interpret the garbage bits in those slots as memory addresses and try
  7418. to traverse them, causing serious mayhem!
  7419. Regarding (3) the sharing of registers between different functions,
  7420. recall from Section~\ref{sec:calling-conventions} that the registers
  7421. are divided into two groups, the caller-saved registers and the
  7422. callee-saved registers. The caller should assume that all the
  7423. caller-saved registers get overwritten with arbitrary values by the
  7424. callee. That is why we recommend in
  7425. Section~\ref{sec:calling-conventions} that variables that are live
  7426. during a function call should not be assigned to caller-saved
  7427. registers.
  7428. On the flip side, if the callee wants to use a callee-saved register,
  7429. the callee must save the contents of those registers on their stack
  7430. frame and then put them back prior to returning to the caller. That
  7431. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7432. the register allocator assigns a variable to a callee-saved register,
  7433. then the prelude of the \code{main} function must save that register
  7434. to the stack and the conclusion of \code{main} must restore it. This
  7435. recommendation now generalizes to all functions.
  7436. Also recall that the base pointer, register \code{rbp}, is used as a
  7437. point-of-reference within a frame, so that each local variable can be
  7438. accessed at a fixed offset from the base pointer
  7439. (Section~\ref{sec:x86}).
  7440. %
  7441. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7442. and callee frames.
  7443. \begin{figure}[tbp]
  7444. \centering
  7445. \begin{tabular}{r|r|l|l} \hline
  7446. Caller View & Callee View & Contents & Frame \\ \hline
  7447. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7448. 0(\key{\%rbp}) & & old \key{rbp} \\
  7449. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7450. \ldots & & \ldots \\
  7451. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7452. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7453. \ldots & & \ldots \\
  7454. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7455. %% & & \\
  7456. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7457. %% & \ldots & \ldots \\
  7458. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7459. \hline
  7460. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7461. & 0(\key{\%rbp}) & old \key{rbp} \\
  7462. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7463. & \ldots & \ldots \\
  7464. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7465. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7466. & \ldots & \ldots \\
  7467. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7468. \end{tabular}
  7469. \caption{Memory layout of caller and callee frames.}
  7470. \label{fig:call-frames}
  7471. \end{figure}
  7472. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7473. %% local variables and for storing the values of callee-saved registers
  7474. %% (we shall refer to all of these collectively as ``locals''), and that
  7475. %% at the beginning of a function we move the stack pointer \code{rsp}
  7476. %% down to make room for them.
  7477. %% We recommend storing the local variables
  7478. %% first and then the callee-saved registers, so that the local variables
  7479. %% can be accessed using \code{rbp} the same as before the addition of
  7480. %% functions.
  7481. %% To make additional room for passing arguments, we shall
  7482. %% move the stack pointer even further down. We count how many stack
  7483. %% arguments are needed for each function call that occurs inside the
  7484. %% body of the function and find their maximum. Adding this number to the
  7485. %% number of locals gives us how much the \code{rsp} should be moved at
  7486. %% the beginning of the function. In preparation for a function call, we
  7487. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7488. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7489. %% so on.
  7490. %% Upon calling the function, the stack arguments are retrieved by the
  7491. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7492. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7493. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7494. %% the layout of the caller and callee frames. Notice how important it is
  7495. %% that we correctly compute the maximum number of arguments needed for
  7496. %% function calls; if that number is too small then the arguments and
  7497. %% local variables will smash into each other!
  7498. \subsection{Efficient Tail Calls}
  7499. \label{sec:tail-call}
  7500. In general, the amount of stack space used by a program is determined
  7501. by the longest chain of nested function calls. That is, if function
  7502. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7503. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7504. $n$ can grow quite large in the case of recursive or mutually
  7505. recursive functions. However, in some cases we can arrange to use only
  7506. constant space, i.e. $O(1)$, instead of $O(n)$.
  7507. If a function call is the last action in a function body, then that
  7508. call is said to be a \emph{tail call}\index{subject}{tail call}.
  7509. For example, in the following
  7510. program, the recursive call to \code{tail-sum} is a tail call.
  7511. \begin{center}
  7512. \begin{lstlisting}
  7513. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7514. (if (eq? n 0)
  7515. r
  7516. (tail-sum (- n 1) (+ n r))))
  7517. (+ (tail-sum 5 0) 27)
  7518. \end{lstlisting}
  7519. \end{center}
  7520. At a tail call, the frame of the caller is no longer needed, so we
  7521. can pop the caller's frame before making the tail call. With this
  7522. approach, a recursive function that only makes tail calls will only
  7523. use $O(1)$ stack space. Functional languages like Racket typically
  7524. rely heavily on recursive functions, so they typically guarantee that
  7525. all tail calls will be optimized in this way.
  7526. \index{subject}{frame}
  7527. However, some care is needed with regards to argument passing in tail
  7528. calls. As mentioned above, for arguments beyond the sixth, the
  7529. convention is to use space in the caller's frame for passing
  7530. arguments. But for a tail call we pop the caller's frame and can no
  7531. longer use it. Another alternative is to use space in the callee's
  7532. frame for passing arguments. However, this option is also problematic
  7533. because the caller and callee's frame overlap in memory. As we begin
  7534. to copy the arguments from their sources in the caller's frame, the
  7535. target locations in the callee's frame might overlap with the sources
  7536. for later arguments! We solve this problem by not using the stack for
  7537. passing more than six arguments but instead using the heap, as we
  7538. describe in the Section~\ref{sec:limit-functions-r4}.
  7539. As mentioned above, for a tail call we pop the caller's frame prior to
  7540. making the tail call. The instructions for popping a frame are the
  7541. instructions that we usually place in the conclusion of a
  7542. function. Thus, we also need to place such code immediately before
  7543. each tail call. These instructions include restoring the callee-saved
  7544. registers, so it is good that the argument passing registers are all
  7545. caller-saved registers.
  7546. One last note regarding which instruction to use to make the tail
  7547. call. When the callee is finished, it should not return to the current
  7548. function, but it should return to the function that called the current
  7549. one. Thus, the return address that is already on the stack is the
  7550. right one, and we should not use \key{callq} to make the tail call, as
  7551. that would unnecessarily overwrite the return address. Instead we can
  7552. simply use the \key{jmp} instruction. Like the indirect function call,
  7553. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  7554. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7555. jump target because the preceding conclusion overwrites just about
  7556. everything else.
  7557. \begin{lstlisting}
  7558. jmp *%rax
  7559. \end{lstlisting}
  7560. \section{Shrink \LangFun{}}
  7561. \label{sec:shrink-r4}
  7562. The \code{shrink} pass performs a minor modification to ease the
  7563. later passes. This pass introduces an explicit \code{main} function
  7564. and changes the top \code{ProgramDefsExp} form to
  7565. \code{ProgramDefs} as follows.
  7566. \begin{lstlisting}
  7567. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7568. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7569. \end{lstlisting}
  7570. where $\itm{mainDef}$ is
  7571. \begin{lstlisting}
  7572. (Def 'main '() 'Integer '() |$\Exp'$|)
  7573. \end{lstlisting}
  7574. \section{Reveal Functions and the \LangFunRef{} language}
  7575. \label{sec:reveal-functions-r4}
  7576. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7577. respect: it conflates the use of function names and local
  7578. variables. This is a problem because we need to compile the use of a
  7579. function name differently than the use of a local variable; we need to
  7580. use \code{leaq} to convert the function name (a label in x86) to an
  7581. address in a register. Thus, it is a good idea to create a new pass
  7582. that changes function references from just a symbol $f$ to
  7583. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7584. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7585. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7586. \begin{figure}[tp]
  7587. \centering
  7588. \fbox{
  7589. \begin{minipage}{0.96\textwidth}
  7590. \[
  7591. \begin{array}{lcl}
  7592. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7593. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7594. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7595. \end{array}
  7596. \]
  7597. \end{minipage}
  7598. }
  7599. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7600. (Figure~\ref{fig:Rfun-syntax}).}
  7601. \label{fig:f1-syntax}
  7602. \end{figure}
  7603. %% Distinguishing between calls in tail position and non-tail position
  7604. %% requires the pass to have some notion of context. We recommend using
  7605. %% two mutually recursive functions, one for processing expressions in
  7606. %% tail position and another for the rest.
  7607. Placing this pass after \code{uniquify} will make sure that there are
  7608. no local variables and functions that share the same name. On the
  7609. other hand, \code{reveal-functions} needs to come before the
  7610. \code{explicate-control} pass because that pass helps us compile
  7611. \code{FunRef} forms into assignment statements.
  7612. \section{Limit Functions}
  7613. \label{sec:limit-functions-r4}
  7614. Recall that we wish to limit the number of function parameters to six
  7615. so that we do not need to use the stack for argument passing, which
  7616. makes it easier to implement efficient tail calls. However, because
  7617. the input language \LangFun{} supports arbitrary numbers of function
  7618. arguments, we have some work to do!
  7619. This pass transforms functions and function calls that involve more
  7620. than six arguments to pass the first five arguments as usual, but it
  7621. packs the rest of the arguments into a vector and passes it as the
  7622. sixth argument.
  7623. Each function definition with too many parameters is transformed as
  7624. follows.
  7625. \begin{lstlisting}
  7626. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7627. |$\Rightarrow$|
  7628. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7629. \end{lstlisting}
  7630. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7631. the occurrences of the later parameters with vector references.
  7632. \begin{lstlisting}
  7633. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7634. \end{lstlisting}
  7635. For function calls with too many arguments, the \code{limit-functions}
  7636. pass transforms them in the following way.
  7637. \begin{tabular}{lll}
  7638. \begin{minipage}{0.2\textwidth}
  7639. \begin{lstlisting}
  7640. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7641. \end{lstlisting}
  7642. \end{minipage}
  7643. &
  7644. $\Rightarrow$
  7645. &
  7646. \begin{minipage}{0.4\textwidth}
  7647. \begin{lstlisting}
  7648. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7649. \end{lstlisting}
  7650. \end{minipage}
  7651. \end{tabular}
  7652. \section{Remove Complex Operands}
  7653. \label{sec:rco-r4}
  7654. The primary decisions to make for this pass is whether to classify
  7655. \code{FunRef} and \code{Apply} as either atomic or complex
  7656. expressions. Recall that a simple expression will eventually end up as
  7657. just an immediate argument of an x86 instruction. Function
  7658. application will be translated to a sequence of instructions, so
  7659. \code{Apply} must be classified as complex expression.
  7660. On the other hand, the arguments of \code{Apply} should be
  7661. atomic expressions.
  7662. %
  7663. Regarding \code{FunRef}, as discussed above, the function label needs
  7664. to be converted to an address using the \code{leaq} instruction. Thus,
  7665. even though \code{FunRef} seems rather simple, it needs to be
  7666. classified as a complex expression so that we generate an assignment
  7667. statement with a left-hand side that can serve as the target of the
  7668. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7669. output language \LangFunANF{} of this pass.
  7670. \begin{figure}[tp]
  7671. \centering
  7672. \fbox{
  7673. \begin{minipage}{0.96\textwidth}
  7674. \small
  7675. \[
  7676. \begin{array}{rcl}
  7677. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7678. \mid \VOID{} } \\
  7679. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7680. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7681. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7682. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7683. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7684. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7685. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7686. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7687. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7688. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7689. \end{array}
  7690. \]
  7691. \end{minipage}
  7692. }
  7693. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7694. \label{fig:Rfun-anf-syntax}
  7695. \end{figure}
  7696. \section{Explicate Control and the \LangCFun{} language}
  7697. \label{sec:explicate-control-r4}
  7698. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7699. output of \key{explicate-control}. (The concrete syntax is given in
  7700. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7701. functions for assignment and tail contexts should be updated with
  7702. cases for \code{Apply} and \code{FunRef} and the function for
  7703. predicate context should be updated for \code{Apply} but not
  7704. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7705. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7706. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7707. defining a new auxiliary function for processing function definitions.
  7708. This code is similar to the case for \code{Program} in \LangVec{}. The
  7709. top-level \code{explicate-control} function that handles the
  7710. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7711. all the function definitions.
  7712. \begin{figure}[tp]
  7713. \fbox{
  7714. \begin{minipage}{0.96\textwidth}
  7715. \small
  7716. \[
  7717. \begin{array}{lcl}
  7718. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7719. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7720. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7721. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7722. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7723. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7724. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7725. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7726. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7727. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7728. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7729. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7730. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7731. \mid \GOTO{\itm{label}} } \\
  7732. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7733. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7734. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7735. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7736. \end{array}
  7737. \]
  7738. \end{minipage}
  7739. }
  7740. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7741. \label{fig:c3-syntax}
  7742. \end{figure}
  7743. \section{Select Instructions and the \LangXIndCall{} Language}
  7744. \label{sec:select-r4}
  7745. \index{subject}{instruction selection}
  7746. The output of select instructions is a program in the \LangXIndCall{}
  7747. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7748. \index{subject}{x86}
  7749. \begin{figure}[tp]
  7750. \fbox{
  7751. \begin{minipage}{0.96\textwidth}
  7752. \small
  7753. \[
  7754. \begin{array}{lcl}
  7755. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7756. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7757. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7758. \Instr &::=& \ldots
  7759. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7760. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7761. \Block &::= & \Instr\ldots \\
  7762. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7763. \LangXIndCallM{} &::= & \Def\ldots
  7764. \end{array}
  7765. \]
  7766. \end{minipage}
  7767. }
  7768. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7769. \label{fig:x86-3-concrete}
  7770. \end{figure}
  7771. \begin{figure}[tp]
  7772. \fbox{
  7773. \begin{minipage}{0.96\textwidth}
  7774. \small
  7775. \[
  7776. \begin{array}{lcl}
  7777. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7778. \mid \BYTEREG{\Reg} } \\
  7779. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7780. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7781. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7782. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7783. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7784. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7785. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7786. \end{array}
  7787. \]
  7788. \end{minipage}
  7789. }
  7790. \caption{The abstract syntax of \LangXIndCall{} (extends
  7791. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7792. \label{fig:x86-3}
  7793. \end{figure}
  7794. An assignment of a function reference to a variable becomes a
  7795. load-effective-address instruction as follows: \\
  7796. \begin{tabular}{lcl}
  7797. \begin{minipage}{0.35\textwidth}
  7798. \begin{lstlisting}
  7799. |$\itm{lhs}$| = (fun-ref |$f$|);
  7800. \end{lstlisting}
  7801. \end{minipage}
  7802. &
  7803. $\Rightarrow$\qquad\qquad
  7804. &
  7805. \begin{minipage}{0.3\textwidth}
  7806. \begin{lstlisting}
  7807. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7808. \end{lstlisting}
  7809. \end{minipage}
  7810. \end{tabular} \\
  7811. Regarding function definitions, we need to remove the parameters and
  7812. instead perform parameter passing using the conventions discussed in
  7813. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7814. registers. We recommend turning the parameters into local variables
  7815. and generating instructions at the beginning of the function to move
  7816. from the argument passing registers to these local variables.
  7817. \begin{lstlisting}
  7818. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7819. |$\Rightarrow$|
  7820. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7821. \end{lstlisting}
  7822. The $G'$ control-flow graph is the same as $G$ except that the
  7823. \code{start} block is modified to add the instructions for moving from
  7824. the argument registers to the parameter variables. So the \code{start}
  7825. block of $G$ shown on the left is changed to the code on the right.
  7826. \begin{center}
  7827. \begin{minipage}{0.3\textwidth}
  7828. \begin{lstlisting}
  7829. start:
  7830. |$\itm{instr}_1$|
  7831. |$\vdots$|
  7832. |$\itm{instr}_n$|
  7833. \end{lstlisting}
  7834. \end{minipage}
  7835. $\Rightarrow$
  7836. \begin{minipage}{0.3\textwidth}
  7837. \begin{lstlisting}
  7838. start:
  7839. movq %rdi, |$x_1$|
  7840. movq %rsi, |$x_2$|
  7841. |$\vdots$|
  7842. |$\itm{instr}_1$|
  7843. |$\vdots$|
  7844. |$\itm{instr}_n$|
  7845. \end{lstlisting}
  7846. \end{minipage}
  7847. \end{center}
  7848. By changing the parameters to local variables, we are giving the
  7849. register allocator control over which registers or stack locations to
  7850. use for them. If you implemented the move-biasing challenge
  7851. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7852. assign the parameter variables to the corresponding argument register,
  7853. in which case the \code{patch-instructions} pass will remove the
  7854. \code{movq} instruction. This happens in the example translation in
  7855. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7856. the \code{add} function.
  7857. %
  7858. Also, note that the register allocator will perform liveness analysis
  7859. on this sequence of move instructions and build the interference
  7860. graph. So, for example, $x_1$ will be marked as interfering with
  7861. \code{rsi} and that will prevent the assignment of $x_1$ to
  7862. \code{rsi}, which is good, because that would overwrite the argument
  7863. that needs to move into $x_2$.
  7864. Next, consider the compilation of function calls. In the mirror image
  7865. of handling the parameters of function definitions, the arguments need
  7866. to be moved to the argument passing registers. The function call
  7867. itself is performed with an indirect function call. The return value
  7868. from the function is stored in \code{rax}, so it needs to be moved
  7869. into the \itm{lhs}.
  7870. \begin{lstlisting}
  7871. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7872. |$\Rightarrow$|
  7873. movq |$\itm{arg}_1$|, %rdi
  7874. movq |$\itm{arg}_2$|, %rsi
  7875. |$\vdots$|
  7876. callq *|\itm{fun}|
  7877. movq %rax, |\itm{lhs}|
  7878. \end{lstlisting}
  7879. The \code{IndirectCallq} AST node includes an integer for the arity of
  7880. the function, i.e., the number of parameters. That information is
  7881. useful in the \code{uncover-live} pass for determining which
  7882. argument-passing registers are potentially read during the call.
  7883. For tail calls, the parameter passing is the same as non-tail calls:
  7884. generate instructions to move the arguments into to the argument
  7885. passing registers. After that we need to pop the frame from the
  7886. procedure call stack. However, we do not yet know how big the frame
  7887. is; that gets determined during register allocation. So instead of
  7888. generating those instructions here, we invent a new instruction that
  7889. means ``pop the frame and then do an indirect jump'', which we name
  7890. \code{TailJmp}. The abstract syntax for this instruction includes an
  7891. argument that specifies where to jump and an integer that represents
  7892. the arity of the function being called.
  7893. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7894. using the label \code{start} for the initial block of a program, and
  7895. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7896. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7897. can be compiled to an assignment to \code{rax} followed by a jump to
  7898. \code{conclusion}. With the addition of function definitions, we will
  7899. have a starting block and conclusion for each function, but their
  7900. labels need to be unique. We recommend prepending the function's name
  7901. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7902. labels. (Alternatively, one could \code{gensym} labels for the start
  7903. and conclusion and store them in the $\itm{info}$ field of the
  7904. function definition.)
  7905. \section{Register Allocation}
  7906. \label{sec:register-allocation-r4}
  7907. \subsection{Liveness Analysis}
  7908. \label{sec:liveness-analysis-r4}
  7909. \index{subject}{liveness analysis}
  7910. %% The rest of the passes need only minor modifications to handle the new
  7911. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7912. %% \code{leaq}.
  7913. The \code{IndirectCallq} instruction should be treated like
  7914. \code{Callq} regarding its written locations $W$, in that they should
  7915. include all the caller-saved registers. Recall that the reason for
  7916. that is to force call-live variables to be assigned to callee-saved
  7917. registers or to be spilled to the stack.
  7918. Regarding the set of read locations $R$ the arity field of
  7919. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7920. argument-passing registers should be considered as read by those
  7921. instructions.
  7922. \subsection{Build Interference Graph}
  7923. \label{sec:build-interference-r4}
  7924. With the addition of function definitions, we compute an interference
  7925. graph for each function (not just one for the whole program).
  7926. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7927. spill vector-typed variables that are live during a call to the
  7928. \code{collect}. With the addition of functions to our language, we
  7929. need to revisit this issue. Many functions perform allocation and
  7930. therefore have calls to the collector inside of them. Thus, we should
  7931. not only spill a vector-typed variable when it is live during a call
  7932. to \code{collect}, but we should spill the variable if it is live
  7933. during any function call. Thus, in the \code{build-interference} pass,
  7934. we recommend adding interference edges between call-live vector-typed
  7935. variables and the callee-saved registers (in addition to the usual
  7936. addition of edges between call-live variables and the caller-saved
  7937. registers).
  7938. \subsection{Allocate Registers}
  7939. The primary change to the \code{allocate-registers} pass is adding an
  7940. auxiliary function for handling definitions (the \Def{} non-terminal
  7941. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7942. logic is the same as described in
  7943. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7944. allocation is performed many times, once for each function definition,
  7945. instead of just once for the whole program.
  7946. \section{Patch Instructions}
  7947. In \code{patch-instructions}, you should deal with the x86
  7948. idiosyncrasy that the destination argument of \code{leaq} must be a
  7949. register. Additionally, you should ensure that the argument of
  7950. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7951. code generation more convenient, because we trample many registers
  7952. before the tail call (as explained in the next section).
  7953. \section{Print x86}
  7954. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7955. \code{IndirectCallq} are straightforward: output their concrete
  7956. syntax.
  7957. \begin{lstlisting}
  7958. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7959. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7960. \end{lstlisting}
  7961. The \code{TailJmp} node requires a bit work. A straightforward
  7962. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7963. before the jump we need to pop the current frame. This sequence of
  7964. instructions is the same as the code for the conclusion of a function,
  7965. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7966. Regarding function definitions, you will need to generate a prelude
  7967. and conclusion for each one. This code is similar to the prelude and
  7968. conclusion that you generated for the \code{main} function in
  7969. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7970. should carry out the following steps.
  7971. \begin{enumerate}
  7972. \item Start with \code{.global} and \code{.align} directives followed
  7973. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7974. example.)
  7975. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7976. pointer.
  7977. \item Push to the stack all of the callee-saved registers that were
  7978. used for register allocation.
  7979. \item Move the stack pointer \code{rsp} down by the size of the stack
  7980. frame for this function, which depends on the number of regular
  7981. spills. (Aligned to 16 bytes.)
  7982. \item Move the root stack pointer \code{r15} up by the size of the
  7983. root-stack frame for this function, which depends on the number of
  7984. spilled vectors. \label{root-stack-init}
  7985. \item Initialize to zero all of the entries in the root-stack frame.
  7986. \item Jump to the start block.
  7987. \end{enumerate}
  7988. The prelude of the \code{main} function has one additional task: call
  7989. the \code{initialize} function to set up the garbage collector and
  7990. move the value of the global \code{rootstack\_begin} in
  7991. \code{r15}. This should happen before step \ref{root-stack-init}
  7992. above, which depends on \code{r15}.
  7993. The conclusion of every function should do the following.
  7994. \begin{enumerate}
  7995. \item Move the stack pointer back up by the size of the stack frame
  7996. for this function.
  7997. \item Restore the callee-saved registers by popping them from the
  7998. stack.
  7999. \item Move the root stack pointer back down by the size of the
  8000. root-stack frame for this function.
  8001. \item Restore \code{rbp} by popping it from the stack.
  8002. \item Return to the caller with the \code{retq} instruction.
  8003. \end{enumerate}
  8004. \begin{exercise}\normalfont
  8005. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  8006. Create 5 new programs that use functions, including examples that pass
  8007. functions and return functions from other functions, recursive
  8008. functions, functions that create vectors, and functions that make tail
  8009. calls. Test your compiler on these new programs and all of your
  8010. previously created test programs.
  8011. \end{exercise}
  8012. \begin{figure}[tbp]
  8013. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8014. \node (Rfun) at (0,2) {\large \LangFun{}};
  8015. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  8016. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  8017. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8018. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8019. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  8020. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  8021. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8022. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8023. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8024. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8025. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8026. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8027. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8028. \path[->,bend left=15] (Rfun) edge [above] node
  8029. {\ttfamily\footnotesize shrink} (Rfun-1);
  8030. \path[->,bend left=15] (Rfun-1) edge [above] node
  8031. {\ttfamily\footnotesize uniquify} (Rfun-2);
  8032. \path[->,bend left=15] (Rfun-2) edge [right] node
  8033. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  8034. \path[->,bend left=15] (F1-1) edge [below] node
  8035. {\ttfamily\footnotesize limit-functions} (F1-2);
  8036. \path[->,bend right=15] (F1-2) edge [above] node
  8037. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  8038. \path[->,bend right=15] (F1-3) edge [above] node
  8039. {\ttfamily\footnotesize remove-complex.} (F1-4);
  8040. \path[->,bend left=15] (F1-4) edge [right] node
  8041. {\ttfamily\footnotesize explicate-control} (C3-2);
  8042. \path[->,bend right=15] (C3-2) edge [left] node
  8043. {\ttfamily\footnotesize select-instr.} (x86-2);
  8044. \path[->,bend left=15] (x86-2) edge [left] node
  8045. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8046. \path[->,bend right=15] (x86-2-1) edge [below] node
  8047. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8048. \path[->,bend right=15] (x86-2-2) edge [left] node
  8049. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8050. \path[->,bend left=15] (x86-3) edge [above] node
  8051. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8052. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  8053. \end{tikzpicture}
  8054. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  8055. \label{fig:Rfun-passes}
  8056. \end{figure}
  8057. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  8058. compiling \LangFun{} to x86.
  8059. \section{An Example Translation}
  8060. \label{sec:functions-example}
  8061. Figure~\ref{fig:add-fun} shows an example translation of a simple
  8062. function in \LangFun{} to x86. The figure also includes the results of the
  8063. \code{explicate-control} and \code{select-instructions} passes.
  8064. \begin{figure}[htbp]
  8065. \begin{tabular}{ll}
  8066. \begin{minipage}{0.5\textwidth}
  8067. % s3_2.rkt
  8068. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8069. (define (add [x : Integer] [y : Integer])
  8070. : Integer
  8071. (+ x y))
  8072. (add 40 2)
  8073. \end{lstlisting}
  8074. $\Downarrow$
  8075. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8076. (define (add86 [x87 : Integer]
  8077. [y88 : Integer]) : Integer
  8078. add86start:
  8079. return (+ x87 y88);
  8080. )
  8081. (define (main) : Integer ()
  8082. mainstart:
  8083. tmp89 = (fun-ref add86);
  8084. (tail-call tmp89 40 2)
  8085. )
  8086. \end{lstlisting}
  8087. \end{minipage}
  8088. &
  8089. $\Rightarrow$
  8090. \begin{minipage}{0.5\textwidth}
  8091. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8092. (define (add86) : Integer
  8093. add86start:
  8094. movq %rdi, x87
  8095. movq %rsi, y88
  8096. movq x87, %rax
  8097. addq y88, %rax
  8098. jmp add11389conclusion
  8099. )
  8100. (define (main) : Integer
  8101. mainstart:
  8102. leaq (fun-ref add86), tmp89
  8103. movq $40, %rdi
  8104. movq $2, %rsi
  8105. tail-jmp tmp89
  8106. )
  8107. \end{lstlisting}
  8108. $\Downarrow$
  8109. \end{minipage}
  8110. \end{tabular}
  8111. \begin{tabular}{ll}
  8112. \begin{minipage}{0.3\textwidth}
  8113. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8114. .globl add86
  8115. .align 16
  8116. add86:
  8117. pushq %rbp
  8118. movq %rsp, %rbp
  8119. jmp add86start
  8120. add86start:
  8121. movq %rdi, %rax
  8122. addq %rsi, %rax
  8123. jmp add86conclusion
  8124. add86conclusion:
  8125. popq %rbp
  8126. retq
  8127. \end{lstlisting}
  8128. \end{minipage}
  8129. &
  8130. \begin{minipage}{0.5\textwidth}
  8131. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8132. .globl main
  8133. .align 16
  8134. main:
  8135. pushq %rbp
  8136. movq %rsp, %rbp
  8137. movq $16384, %rdi
  8138. movq $16384, %rsi
  8139. callq initialize
  8140. movq rootstack_begin(%rip), %r15
  8141. jmp mainstart
  8142. mainstart:
  8143. leaq add86(%rip), %rcx
  8144. movq $40, %rdi
  8145. movq $2, %rsi
  8146. movq %rcx, %rax
  8147. popq %rbp
  8148. jmp *%rax
  8149. mainconclusion:
  8150. popq %rbp
  8151. retq
  8152. \end{lstlisting}
  8153. \end{minipage}
  8154. \end{tabular}
  8155. \caption{Example compilation of a simple function to x86.}
  8156. \label{fig:add-fun}
  8157. \end{figure}
  8158. % Challenge idea: inlining! (simple version)
  8159. % Further Reading
  8160. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8161. \chapter{Lexically Scoped Functions}
  8162. \label{ch:Rlam}
  8163. \index{subject}{lambda}
  8164. \index{subject}{lexical scoping}
  8165. This chapter studies lexically scoped functions as they appear in
  8166. functional languages such as Racket. By lexical scoping we mean that a
  8167. function's body may refer to variables whose binding site is outside
  8168. of the function, in an enclosing scope.
  8169. %
  8170. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  8171. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  8172. \key{lambda} form. The body of the \key{lambda}, refers to three
  8173. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  8174. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  8175. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  8176. parameter of function \code{f}. The \key{lambda} is returned from the
  8177. function \code{f}. The main expression of the program includes two
  8178. calls to \code{f} with different arguments for \code{x}, first
  8179. \code{5} then \code{3}. The functions returned from \code{f} are bound
  8180. to variables \code{g} and \code{h}. Even though these two functions
  8181. were created by the same \code{lambda}, they are really different
  8182. functions because they use different values for \code{x}. Applying
  8183. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  8184. \code{15} produces \code{22}. The result of this program is \code{42}.
  8185. \begin{figure}[btp]
  8186. % s4_6.rkt
  8187. \begin{lstlisting}
  8188. (define (f [x : Integer]) : (Integer -> Integer)
  8189. (let ([y 4])
  8190. (lambda: ([z : Integer]) : Integer
  8191. (+ x (+ y z)))))
  8192. (let ([g (f 5)])
  8193. (let ([h (f 3)])
  8194. (+ (g 11) (h 15))))
  8195. \end{lstlisting}
  8196. \caption{Example of a lexically scoped function.}
  8197. \label{fig:lexical-scoping}
  8198. \end{figure}
  8199. The approach that we take for implementing lexically scoped
  8200. functions is to compile them into top-level function definitions,
  8201. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  8202. provide special treatment for variable occurrences such as \code{x}
  8203. and \code{y} in the body of the \code{lambda} of
  8204. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  8205. refer to variables defined outside of it. To identify such variable
  8206. occurrences, we review the standard notion of free variable.
  8207. \begin{definition}
  8208. A variable is \emph{free in expression} $e$ if the variable occurs
  8209. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  8210. variable}
  8211. \end{definition}
  8212. For example, in the expression \code{(+ x (+ y z))} the variables
  8213. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  8214. only \code{x} and \code{y} are free in the following expression
  8215. because \code{z} is bound by the \code{lambda}.
  8216. \begin{lstlisting}
  8217. (lambda: ([z : Integer]) : Integer
  8218. (+ x (+ y z)))
  8219. \end{lstlisting}
  8220. So the free variables of a \code{lambda} are the ones that will need
  8221. special treatment. We need to arrange for some way to transport, at
  8222. runtime, the values of those variables from the point where the
  8223. \code{lambda} was created to the point where the \code{lambda} is
  8224. applied. An efficient solution to the problem, due to
  8225. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  8226. free variables together with the function pointer for the lambda's
  8227. code, an arrangement called a \emph{flat closure} (which we shorten to
  8228. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  8229. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  8230. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  8231. pointers. The function pointer resides at index $0$ and the
  8232. values for the free variables will fill in the rest of the vector.
  8233. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  8234. how closures work. It's a three-step dance. The program first calls
  8235. function \code{f}, which creates a closure for the \code{lambda}. The
  8236. closure is a vector whose first element is a pointer to the top-level
  8237. function that we will generate for the \code{lambda}, the second
  8238. element is the value of \code{x}, which is \code{5}, and the third
  8239. element is \code{4}, the value of \code{y}. The closure does not
  8240. contain an element for \code{z} because \code{z} is not a free
  8241. variable of the \code{lambda}. Creating the closure is step 1 of the
  8242. dance. The closure is returned from \code{f} and bound to \code{g}, as
  8243. shown in Figure~\ref{fig:closures}.
  8244. %
  8245. The second call to \code{f} creates another closure, this time with
  8246. \code{3} in the second slot (for \code{x}). This closure is also
  8247. returned from \code{f} but bound to \code{h}, which is also shown in
  8248. Figure~\ref{fig:closures}.
  8249. \begin{figure}[tbp]
  8250. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  8251. \caption{Example closure representation for the \key{lambda}'s
  8252. in Figure~\ref{fig:lexical-scoping}.}
  8253. \label{fig:closures}
  8254. \end{figure}
  8255. Continuing with the example, consider the application of \code{g} to
  8256. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  8257. obtain the function pointer in the first element of the closure and
  8258. call it, passing in the closure itself and then the regular arguments,
  8259. in this case \code{11}. This technique for applying a closure is step
  8260. 2 of the dance.
  8261. %
  8262. But doesn't this \code{lambda} only take 1 argument, for parameter
  8263. \code{z}? The third and final step of the dance is generating a
  8264. top-level function for a \code{lambda}. We add an additional
  8265. parameter for the closure and we insert a \code{let} at the beginning
  8266. of the function for each free variable, to bind those variables to the
  8267. appropriate elements from the closure parameter.
  8268. %
  8269. This three-step dance is known as \emph{closure conversion}. We
  8270. discuss the details of closure conversion in
  8271. Section~\ref{sec:closure-conversion} and the code generated from the
  8272. example in Section~\ref{sec:example-lambda}. But first we define the
  8273. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  8274. \section{The \LangLam{} Language}
  8275. \label{sec:r5}
  8276. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8277. functions and lexical scoping, is defined in
  8278. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8279. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8280. syntax for function application.
  8281. \begin{figure}[tp]
  8282. \centering
  8283. \fbox{
  8284. \begin{minipage}{0.96\textwidth}
  8285. \small
  8286. \[
  8287. \begin{array}{lcl}
  8288. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  8289. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  8290. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  8291. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8292. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8293. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8294. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8295. \mid (\key{and}\;\Exp\;\Exp)
  8296. \mid (\key{or}\;\Exp\;\Exp)
  8297. \mid (\key{not}\;\Exp) } \\
  8298. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8299. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8300. (\key{vector-ref}\;\Exp\;\Int)} \\
  8301. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8302. \mid (\Exp \; \Exp\ldots) } \\
  8303. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8304. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8305. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8306. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  8307. \end{array}
  8308. \]
  8309. \end{minipage}
  8310. }
  8311. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8312. with \key{lambda}.}
  8313. \label{fig:Rlam-concrete-syntax}
  8314. \end{figure}
  8315. \begin{figure}[tp]
  8316. \centering
  8317. \fbox{
  8318. \begin{minipage}{0.96\textwidth}
  8319. \small
  8320. \[
  8321. \begin{array}{lcl}
  8322. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8323. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8324. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8325. &\mid& \gray{ \BOOL{\itm{bool}}
  8326. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8327. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8328. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8329. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8330. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8331. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8332. \end{array}
  8333. \]
  8334. \end{minipage}
  8335. }
  8336. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8337. \label{fig:Rlam-syntax}
  8338. \end{figure}
  8339. \index{subject}{interpreter}
  8340. \label{sec:interp-Rlambda}
  8341. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8342. \LangLam{}. The case for \key{lambda} saves the current environment
  8343. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8344. the environment from the \key{lambda}, the \code{lam-env}, when
  8345. interpreting the body of the \key{lambda}. The \code{lam-env}
  8346. environment is extended with the mapping of parameters to argument
  8347. values.
  8348. \begin{figure}[tbp]
  8349. \begin{lstlisting}
  8350. (define interp-Rlambda-class
  8351. (class interp-Rfun-class
  8352. (super-new)
  8353. (define/override (interp-op op)
  8354. (match op
  8355. ['procedure-arity
  8356. (lambda (v)
  8357. (match v
  8358. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8359. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8360. [else (super interp-op op)]))
  8361. (define/override ((interp-exp env) e)
  8362. (define recur (interp-exp env))
  8363. (match e
  8364. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8365. `(function ,xs ,body ,env)]
  8366. [else ((super interp-exp env) e)]))
  8367. ))
  8368. (define (interp-Rlambda p)
  8369. (send (new interp-Rlambda-class) interp-program p))
  8370. \end{lstlisting}
  8371. \caption{Interpreter for \LangLam{}.}
  8372. \label{fig:interp-Rlambda}
  8373. \end{figure}
  8374. \label{sec:type-check-r5}
  8375. \index{subject}{type checking}
  8376. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8377. \key{lambda} form. The body of the \key{lambda} is checked in an
  8378. environment that includes the current environment (because it is
  8379. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8380. require the body's type to match the declared return type.
  8381. \begin{figure}[tbp]
  8382. \begin{lstlisting}
  8383. (define (type-check-Rlambda env)
  8384. (lambda (e)
  8385. (match e
  8386. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8387. (define-values (new-body bodyT)
  8388. ((type-check-exp (append (map cons xs Ts) env)) body))
  8389. (define ty `(,@Ts -> ,rT))
  8390. (cond
  8391. [(equal? rT bodyT)
  8392. (values (HasType (Lambda params rT new-body) ty) ty)]
  8393. [else
  8394. (error "mismatch in return type" bodyT rT)])]
  8395. ...
  8396. )))
  8397. \end{lstlisting}
  8398. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8399. \label{fig:type-check-Rlambda}
  8400. \end{figure}
  8401. \section{Reveal Functions and the $F_2$ language}
  8402. \label{sec:reveal-functions-r5}
  8403. To support the \code{procedure-arity} operator we need to communicate
  8404. the arity of a function to the point of closure creation. We can
  8405. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8406. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8407. output of this pass is the language $F_2$, whose syntax is defined in
  8408. Figure~\ref{fig:f2-syntax}.
  8409. \begin{figure}[tp]
  8410. \centering
  8411. \fbox{
  8412. \begin{minipage}{0.96\textwidth}
  8413. \[
  8414. \begin{array}{lcl}
  8415. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8416. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8417. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8418. \end{array}
  8419. \]
  8420. \end{minipage}
  8421. }
  8422. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8423. (Figure~\ref{fig:Rlam-syntax}).}
  8424. \label{fig:f2-syntax}
  8425. \end{figure}
  8426. \section{Closure Conversion}
  8427. \label{sec:closure-conversion}
  8428. \index{subject}{closure conversion}
  8429. The compiling of lexically-scoped functions into top-level function
  8430. definitions is accomplished in the pass \code{convert-to-closures}
  8431. that comes after \code{reveal-functions} and before
  8432. \code{limit-functions}.
  8433. As usual, we implement the pass as a recursive function over the
  8434. AST. All of the action is in the cases for \key{Lambda} and
  8435. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8436. that creates a closure, that is, a vector whose first element is a
  8437. function pointer and the rest of the elements are the free variables
  8438. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8439. using \code{vector} so that we can distinguish closures from vectors
  8440. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8441. the generated code below, the \itm{name} is a unique symbol generated
  8442. to identify the function and the \itm{arity} is the number of
  8443. parameters (the length of \itm{ps}).
  8444. \begin{lstlisting}
  8445. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8446. |$\Rightarrow$|
  8447. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8448. \end{lstlisting}
  8449. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8450. create a top-level function definition for each \key{Lambda}, as
  8451. shown below.\\
  8452. \begin{minipage}{0.8\textwidth}
  8453. \begin{lstlisting}
  8454. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8455. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8456. ...
  8457. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8458. |\itm{body'}|)...))
  8459. \end{lstlisting}
  8460. \end{minipage}\\
  8461. The \code{clos} parameter refers to the closure. Translate the type
  8462. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8463. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8464. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8465. underscore \code{\_} is a dummy type that we use because it is rather
  8466. difficult to give a type to the function in the closure's
  8467. type.\footnote{To give an accurate type to a closure, we would need to
  8468. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8469. The dummy type is considered to be equal to any other type during type
  8470. checking. The sequence of \key{Let} forms bind the free variables to
  8471. their values obtained from the closure.
  8472. Closure conversion turns functions into vectors, so the type
  8473. annotations in the program must also be translated. We recommend
  8474. defining a auxiliary recursive function for this purpose. Function
  8475. types should be translated as follows.
  8476. \begin{lstlisting}
  8477. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8478. |$\Rightarrow$|
  8479. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8480. \end{lstlisting}
  8481. The above type says that the first thing in the vector is a function
  8482. pointer. The first parameter of the function pointer is a vector (a
  8483. closure) and the rest of the parameters are the ones from the original
  8484. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8485. the closure omits the types of the free variables because 1) those
  8486. types are not available in this context and 2) we do not need them in
  8487. the code that is generated for function application.
  8488. We transform function application into code that retrieves the
  8489. function pointer from the closure and then calls the function, passing
  8490. in the closure as the first argument. We bind $e'$ to a temporary
  8491. variable to avoid code duplication.
  8492. \begin{lstlisting}
  8493. (Apply |$e$| |\itm{es}|)
  8494. |$\Rightarrow$|
  8495. (Let |\itm{tmp}| |$e'$|
  8496. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8497. \end{lstlisting}
  8498. There is also the question of what to do with references top-level
  8499. function definitions. To maintain a uniform translation of function
  8500. application, we turn function references into closures.
  8501. \begin{tabular}{lll}
  8502. \begin{minipage}{0.3\textwidth}
  8503. \begin{lstlisting}
  8504. (FunRefArity |$f$| |$n$|)
  8505. \end{lstlisting}
  8506. \end{minipage}
  8507. &
  8508. $\Rightarrow$
  8509. &
  8510. \begin{minipage}{0.5\textwidth}
  8511. \begin{lstlisting}
  8512. (Closure |$n$| (FunRef |$f$|) '())
  8513. \end{lstlisting}
  8514. \end{minipage}
  8515. \end{tabular} \\
  8516. %
  8517. The top-level function definitions need to be updated as well to take
  8518. an extra closure parameter.
  8519. \section{An Example Translation}
  8520. \label{sec:example-lambda}
  8521. Figure~\ref{fig:lexical-functions-example} shows the result of
  8522. \code{reveal-functions} and \code{convert-to-closures} for the example
  8523. program demonstrating lexical scoping that we discussed at the
  8524. beginning of this chapter.
  8525. \begin{figure}[tbp]
  8526. \begin{minipage}{0.8\textwidth}
  8527. % tests/lambda_test_6.rkt
  8528. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8529. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8530. (let ([y8 4])
  8531. (lambda: ([z9 : Integer]) : Integer
  8532. (+ x7 (+ y8 z9)))))
  8533. (define (main) : Integer
  8534. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8535. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8536. (+ (g0 11) (h1 15)))))
  8537. \end{lstlisting}
  8538. $\Rightarrow$
  8539. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8540. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8541. (let ([y8 4])
  8542. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8543. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8544. (let ([x7 (vector-ref fvs3 1)])
  8545. (let ([y8 (vector-ref fvs3 2)])
  8546. (+ x7 (+ y8 z9)))))
  8547. (define (main) : Integer
  8548. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8549. ((vector-ref clos5 0) clos5 5))])
  8550. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8551. ((vector-ref clos6 0) clos6 3))])
  8552. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8553. \end{lstlisting}
  8554. \end{minipage}
  8555. \caption{Example of closure conversion.}
  8556. \label{fig:lexical-functions-example}
  8557. \end{figure}
  8558. \begin{exercise}\normalfont
  8559. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8560. Create 5 new programs that use \key{lambda} functions and make use of
  8561. lexical scoping. Test your compiler on these new programs and all of
  8562. your previously created test programs.
  8563. \end{exercise}
  8564. \section{Expose Allocation}
  8565. \label{sec:expose-allocation-r5}
  8566. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8567. that allocates and initializes a vector, similar to the translation of
  8568. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8569. The only difference is replacing the use of
  8570. \ALLOC{\itm{len}}{\itm{type}} with
  8571. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8572. \section{Explicate Control and \LangCLam{}}
  8573. \label{sec:explicate-r5}
  8574. The output language of \code{explicate-control} is \LangCLam{} whose
  8575. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8576. difference with respect to \LangCFun{} is the addition of the
  8577. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8578. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8579. similar to the handling of other expressions such as primitive
  8580. operators.
  8581. \begin{figure}[tp]
  8582. \fbox{
  8583. \begin{minipage}{0.96\textwidth}
  8584. \small
  8585. \[
  8586. \begin{array}{lcl}
  8587. \Exp &::= & \ldots
  8588. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8589. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8590. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8591. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8592. \mid \GOTO{\itm{label}} } \\
  8593. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8594. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8595. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8596. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8597. \end{array}
  8598. \]
  8599. \end{minipage}
  8600. }
  8601. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8602. \label{fig:c4-syntax}
  8603. \end{figure}
  8604. \section{Select Instructions}
  8605. \label{sec:select-instructions-Rlambda}
  8606. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8607. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8608. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8609. that you should place the \itm{arity} in the tag that is stored at
  8610. position $0$ of the vector. Recall that in
  8611. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8612. was not used. We store the arity in the $5$ bits starting at position
  8613. $58$.
  8614. Compile the \code{procedure-arity} operator into a sequence of
  8615. instructions that access the tag from position $0$ of the vector and
  8616. extract the $5$-bits starting at position $58$ from the tag.
  8617. \begin{figure}[p]
  8618. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8619. \node (Rfun) at (0,2) {\large \LangFun{}};
  8620. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8621. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8622. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8623. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8624. \node (F1-3) at (6,0) {\large $F_1$};
  8625. \node (F1-4) at (3,0) {\large $F_1$};
  8626. \node (F1-5) at (0,0) {\large $F_1$};
  8627. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8628. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8629. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8630. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8631. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8632. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8633. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8634. \path[->,bend left=15] (Rfun) edge [above] node
  8635. {\ttfamily\footnotesize shrink} (Rfun-2);
  8636. \path[->,bend left=15] (Rfun-2) edge [above] node
  8637. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8638. \path[->,bend left=15] (Rfun-3) edge [right] node
  8639. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8640. \path[->,bend left=15] (F1-1) edge [below] node
  8641. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8642. \path[->,bend right=15] (F1-2) edge [above] node
  8643. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8644. \path[->,bend right=15] (F1-3) edge [above] node
  8645. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8646. \path[->,bend right=15] (F1-4) edge [above] node
  8647. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8648. \path[->,bend right=15] (F1-5) edge [right] node
  8649. {\ttfamily\footnotesize explicate-control} (C3-2);
  8650. \path[->,bend left=15] (C3-2) edge [left] node
  8651. {\ttfamily\footnotesize select-instr.} (x86-2);
  8652. \path[->,bend right=15] (x86-2) edge [left] node
  8653. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8654. \path[->,bend right=15] (x86-2-1) edge [below] node
  8655. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8656. \path[->,bend right=15] (x86-2-2) edge [left] node
  8657. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8658. \path[->,bend left=15] (x86-3) edge [above] node
  8659. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8660. \path[->,bend left=15] (x86-4) edge [right] node
  8661. {\ttfamily\footnotesize print-x86} (x86-5);
  8662. \end{tikzpicture}
  8663. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8664. functions.}
  8665. \label{fig:Rlambda-passes}
  8666. \end{figure}
  8667. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8668. for the compilation of \LangLam{}.
  8669. \clearpage
  8670. \section{Challenge: Optimize Closures}
  8671. \label{sec:optimize-closures}
  8672. In this chapter we compiled lexically-scoped functions into a
  8673. relatively efficient representation: flat closures. However, even this
  8674. representation comes with some overhead. For example, consider the
  8675. following program with a function \code{tail-sum} that does not have
  8676. any free variables and where all the uses of \code{tail-sum} are in
  8677. applications where we know that only \code{tail-sum} is being applied
  8678. (and not any other functions).
  8679. \begin{center}
  8680. \begin{minipage}{0.95\textwidth}
  8681. \begin{lstlisting}
  8682. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8683. (if (eq? n 0)
  8684. r
  8685. (tail-sum (- n 1) (+ n r))))
  8686. (+ (tail-sum 5 0) 27)
  8687. \end{lstlisting}
  8688. \end{minipage}
  8689. \end{center}
  8690. As described in this chapter, we uniformly apply closure conversion to
  8691. all functions, obtaining the following output for this program.
  8692. \begin{center}
  8693. \begin{minipage}{0.95\textwidth}
  8694. \begin{lstlisting}
  8695. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8696. (if (eq? n2 0)
  8697. r3
  8698. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8699. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8700. (define (main) : Integer
  8701. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8702. ((vector-ref clos6 0) clos6 5 0)) 27))
  8703. \end{lstlisting}
  8704. \end{minipage}
  8705. \end{center}
  8706. In the previous Chapter, there would be no allocation in the program
  8707. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8708. the above program allocates memory for each \code{closure} and the
  8709. calls to \code{tail-sum} are indirect. These two differences incur
  8710. considerable overhead in a program such as this one, where the
  8711. allocations and indirect calls occur inside a tight loop.
  8712. One might think that this problem is trivial to solve: can't we just
  8713. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8714. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8715. e'_n$)} instead of treating it like a call to a closure? We would
  8716. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8717. %
  8718. However, this problem is not so trivial because a global function may
  8719. ``escape'' and become involved in applications that also involve
  8720. closures. Consider the following example in which the application
  8721. \code{(f 41)} needs to be compiled into a closure application, because
  8722. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8723. function might also get bound to \code{f}.
  8724. \begin{lstlisting}
  8725. (define (add1 [x : Integer]) : Integer
  8726. (+ x 1))
  8727. (let ([y (read)])
  8728. (let ([f (if (eq? (read) 0)
  8729. add1
  8730. (lambda: ([x : Integer]) : Integer (- x y)))])
  8731. (f 41)))
  8732. \end{lstlisting}
  8733. If a global function name is used in any way other than as the
  8734. operator in a direct call, then we say that the function
  8735. \emph{escapes}. If a global function does not escape, then we do not
  8736. need to perform closure conversion on the function.
  8737. \begin{exercise}\normalfont
  8738. Implement an auxiliary function for detecting which global
  8739. functions escape. Using that function, implement an improved version
  8740. of closure conversion that does not apply closure conversion to
  8741. global functions that do not escape but instead compiles them as
  8742. regular functions. Create several new test cases that check whether
  8743. you properly detect whether global functions escape or not.
  8744. \end{exercise}
  8745. So far we have reduced the overhead of calling global functions, but
  8746. it would also be nice to reduce the overhead of calling a
  8747. \code{lambda} when we can determine at compile time which
  8748. \code{lambda} will be called. We refer to such calls as \emph{known
  8749. calls}. Consider the following example in which a \code{lambda} is
  8750. bound to \code{f} and then applied.
  8751. \begin{lstlisting}
  8752. (let ([y (read)])
  8753. (let ([f (lambda: ([x : Integer]) : Integer
  8754. (+ x y))])
  8755. (f 21)))
  8756. \end{lstlisting}
  8757. Closure conversion compiles \code{(f 21)} into an indirect call:
  8758. \begin{lstlisting}
  8759. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8760. (let ([y2 (vector-ref fvs6 1)])
  8761. (+ x3 y2)))
  8762. (define (main) : Integer
  8763. (let ([y2 (read)])
  8764. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8765. ((vector-ref f4 0) f4 21))))
  8766. \end{lstlisting}
  8767. but we can instead compile the application \code{(f 21)} into a direct call
  8768. to \code{lambda5}:
  8769. \begin{lstlisting}
  8770. (define (main) : Integer
  8771. (let ([y2 (read)])
  8772. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8773. ((fun-ref lambda5) f4 21))))
  8774. \end{lstlisting}
  8775. The problem of determining which lambda will be called from a
  8776. particular application is quite challenging in general and the topic
  8777. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8778. following exercise we recommend that you compile an application to a
  8779. direct call when the operator is a variable and the variable is
  8780. \code{let}-bound to a closure. This can be accomplished by maintaining
  8781. an environment mapping \code{let}-bound variables to function names.
  8782. Extend the environment whenever you encounter a closure on the
  8783. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8784. to the name of the global function for the closure. This pass should
  8785. come after closure conversion.
  8786. \begin{exercise}\normalfont
  8787. Implement a compiler pass, named \code{optimize-known-calls}, that
  8788. compiles known calls into direct calls. Verify that your compiler is
  8789. successful in this regard on several example programs.
  8790. \end{exercise}
  8791. These exercises only scratches the surface of optimizing of
  8792. closures. A good next step for the interested reader is to look at the
  8793. work of \citet{Keep:2012ab}.
  8794. \section{Further Reading}
  8795. The notion of lexically scoped anonymous functions predates modern
  8796. computers by about a decade. They were invented by
  8797. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8798. foundation for logic. Anonymous functions were included in the
  8799. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8800. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8801. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8802. compile Scheme programs. However, environments were represented as
  8803. linked lists, so variable lookup was linear in the size of the
  8804. environment. In this chapter we represent environments using flat
  8805. closures, which were invented by
  8806. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8807. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8808. closures, variable lookup is constant time but the time to create a
  8809. closure is proportional to the number of its free variables. Flat
  8810. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8811. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8812. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8813. \chapter{Dynamic Typing}
  8814. \label{ch:Rdyn}
  8815. \index{subject}{dynamic typing}
  8816. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8817. typed language that is a subset of Racket. This is in contrast to the
  8818. previous chapters, which have studied the compilation of Typed
  8819. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8820. expression may produce a value of a different type each time it is
  8821. executed. Consider the following example with a conditional \code{if}
  8822. expression that may return a Boolean or an integer depending on the
  8823. input to the program.
  8824. % part of dynamic_test_25.rkt
  8825. \begin{lstlisting}
  8826. (not (if (eq? (read) 1) #f 0))
  8827. \end{lstlisting}
  8828. Languages that allow expressions to produce different kinds of values
  8829. are called \emph{polymorphic}, a word composed of the Greek roots
  8830. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8831. are several kinds of polymorphism in programming languages, such as
  8832. subtype polymorphism and parametric
  8833. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8834. study in this chapter does not have a special name but it is the kind
  8835. that arises in dynamically typed languages.
  8836. Another characteristic of dynamically typed languages is that
  8837. primitive operations, such as \code{not}, are often defined to operate
  8838. on many different types of values. In fact, in Racket, the \code{not}
  8839. operator produces a result for any kind of value: given \code{\#f} it
  8840. returns \code{\#t} and given anything else it returns \code{\#f}.
  8841. Furthermore, even when primitive operations restrict their inputs to
  8842. values of a certain type, this restriction is enforced at runtime
  8843. instead of during compilation. For example, the following vector
  8844. reference results in a run-time contract violation because the index
  8845. must be in integer, not a Boolean such as \code{\#t}.
  8846. \begin{lstlisting}
  8847. (vector-ref (vector 42) #t)
  8848. \end{lstlisting}
  8849. \begin{figure}[tp]
  8850. \centering
  8851. \fbox{
  8852. \begin{minipage}{0.97\textwidth}
  8853. \[
  8854. \begin{array}{rcl}
  8855. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8856. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8857. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8858. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8859. &\mid& \key{\#t} \mid \key{\#f}
  8860. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8861. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8862. \mid \CUNIOP{\key{not}}{\Exp} \\
  8863. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8864. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8865. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8866. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8867. &\mid& \LP\Exp \; \Exp\ldots\RP
  8868. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8869. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8870. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8871. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8872. \LangDynM{} &::=& \Def\ldots\; \Exp
  8873. \end{array}
  8874. \]
  8875. \end{minipage}
  8876. }
  8877. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8878. \label{fig:r7-concrete-syntax}
  8879. \end{figure}
  8880. \begin{figure}[tp]
  8881. \centering
  8882. \fbox{
  8883. \begin{minipage}{0.96\textwidth}
  8884. \small
  8885. \[
  8886. \begin{array}{lcl}
  8887. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8888. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8889. &\mid& \BOOL{\itm{bool}}
  8890. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8891. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8892. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8893. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8894. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8895. \end{array}
  8896. \]
  8897. \end{minipage}
  8898. }
  8899. \caption{The abstract syntax of \LangDyn{}.}
  8900. \label{fig:r7-syntax}
  8901. \end{figure}
  8902. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8903. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8904. \ref{fig:r7-syntax}.
  8905. %
  8906. There is no type checker for \LangDyn{} because it is not a statically
  8907. typed language (it's dynamically typed!).
  8908. The definitional interpreter for \LangDyn{} is presented in
  8909. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8910. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8911. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8912. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8913. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  8914. value} that combines an underlying value with a tag that identifies
  8915. what kind of value it is. We define the following struct
  8916. to represented tagged values.
  8917. \begin{lstlisting}
  8918. (struct Tagged (value tag) #:transparent)
  8919. \end{lstlisting}
  8920. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8921. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8922. but don't always capture all the information that a type does. For
  8923. example, a vector of type \code{(Vector Any Any)} is tagged with
  8924. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8925. is tagged with \code{Procedure}.
  8926. Next consider the match case for \code{vector-ref}. The
  8927. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8928. is used to ensure that the first argument is a vector and the second
  8929. is an integer. If they are not, a \code{trapped-error} is raised.
  8930. Recall from Section~\ref{sec:interp_Rint} that when a definition
  8931. interpreter raises a \code{trapped-error} error, the compiled code
  8932. must also signal an error by exiting with return code \code{255}. A
  8933. \code{trapped-error} is also raised if the index is not less than
  8934. length of the vector.
  8935. \begin{figure}[tbp]
  8936. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8937. (define ((interp-Rdyn-exp env) ast)
  8938. (define recur (interp-Rdyn-exp env))
  8939. (match ast
  8940. [(Var x) (lookup x env)]
  8941. [(Int n) (Tagged n 'Integer)]
  8942. [(Bool b) (Tagged b 'Boolean)]
  8943. [(Lambda xs rt body)
  8944. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8945. [(Prim 'vector es)
  8946. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8947. [(Prim 'vector-ref (list e1 e2))
  8948. (define vec (recur e1)) (define i (recur e2))
  8949. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8950. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8951. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8952. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8953. [(Prim 'vector-set! (list e1 e2 e3))
  8954. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8955. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8956. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8957. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8958. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8959. (Tagged (void) 'Void)]
  8960. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8961. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8962. [(Prim 'or (list e1 e2))
  8963. (define v1 (recur e1))
  8964. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8965. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8966. [(Prim op (list e1))
  8967. #:when (set-member? type-predicates op)
  8968. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8969. [(Prim op es)
  8970. (define args (map recur es))
  8971. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8972. (unless (for/or ([expected-tags (op-tags op)])
  8973. (equal? expected-tags tags))
  8974. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8975. (tag-value
  8976. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8977. [(If q t f)
  8978. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8979. [(Apply f es)
  8980. (define new-f (recur f)) (define args (map recur es))
  8981. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8982. (match f-val
  8983. [`(function ,xs ,body ,lam-env)
  8984. (unless (eq? (length xs) (length args))
  8985. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8986. (define new-env (append (map cons xs args) lam-env))
  8987. ((interp-Rdyn-exp new-env) body)]
  8988. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8989. \end{lstlisting}
  8990. \caption{Interpreter for the \LangDyn{} language.}
  8991. \label{fig:interp-Rdyn}
  8992. \end{figure}
  8993. \begin{figure}[tbp]
  8994. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8995. (define (interp-op op)
  8996. (match op
  8997. ['+ fx+]
  8998. ['- fx-]
  8999. ['read read-fixnum]
  9000. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  9001. ['< (lambda (v1 v2)
  9002. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  9003. ['<= (lambda (v1 v2)
  9004. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  9005. ['> (lambda (v1 v2)
  9006. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  9007. ['>= (lambda (v1 v2)
  9008. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  9009. ['boolean? boolean?]
  9010. ['integer? fixnum?]
  9011. ['void? void?]
  9012. ['vector? vector?]
  9013. ['vector-length vector-length]
  9014. ['procedure? (match-lambda
  9015. [`(functions ,xs ,body ,env) #t] [else #f])]
  9016. [else (error 'interp-op "unknown operator" op)]))
  9017. (define (op-tags op)
  9018. (match op
  9019. ['+ '((Integer Integer))]
  9020. ['- '((Integer Integer) (Integer))]
  9021. ['read '(())]
  9022. ['not '((Boolean))]
  9023. ['< '((Integer Integer))]
  9024. ['<= '((Integer Integer))]
  9025. ['> '((Integer Integer))]
  9026. ['>= '((Integer Integer))]
  9027. ['vector-length '((Vector))]))
  9028. (define type-predicates
  9029. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9030. (define (tag-value v)
  9031. (cond [(boolean? v) (Tagged v 'Boolean)]
  9032. [(fixnum? v) (Tagged v 'Integer)]
  9033. [(procedure? v) (Tagged v 'Procedure)]
  9034. [(vector? v) (Tagged v 'Vector)]
  9035. [(void? v) (Tagged v 'Void)]
  9036. [else (error 'tag-value "unidentified value ~a" v)]))
  9037. (define (check-tag val expected ast)
  9038. (define tag (Tagged-tag val))
  9039. (unless (eq? tag expected)
  9040. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  9041. \end{lstlisting}
  9042. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  9043. \label{fig:interp-Rdyn-aux}
  9044. \end{figure}
  9045. \clearpage
  9046. \section{Representation of Tagged Values}
  9047. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  9048. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  9049. values at the bit level. Because almost every operation in \LangDyn{}
  9050. involves manipulating tagged values, the representation must be
  9051. efficient. Recall that all of our values are 64 bits. We shall steal
  9052. the 3 right-most bits to encode the tag. We use $001$ to identify
  9053. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  9054. and $101$ for the void value. We define the following auxiliary
  9055. function for mapping types to tag codes.
  9056. \begin{align*}
  9057. \itm{tagof}(\key{Integer}) &= 001 \\
  9058. \itm{tagof}(\key{Boolean}) &= 100 \\
  9059. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  9060. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  9061. \itm{tagof}(\key{Void}) &= 101
  9062. \end{align*}
  9063. This stealing of 3 bits comes at some price: our integers are reduced
  9064. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  9065. affect vectors and procedures because those values are addresses, and
  9066. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  9067. they are always $000$. Thus, we do not lose information by overwriting
  9068. the rightmost 3 bits with the tag and we can simply zero-out the tag
  9069. to recover the original address.
  9070. To make tagged values into first-class entities, we can give them a
  9071. type, called \code{Any}, and define operations such as \code{Inject}
  9072. and \code{Project} for creating and using them, yielding the \LangAny{}
  9073. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  9074. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  9075. in greater detail.
  9076. \section{The \LangAny{} Language}
  9077. \label{sec:Rany-lang}
  9078. \begin{figure}[tp]
  9079. \centering
  9080. \fbox{
  9081. \begin{minipage}{0.96\textwidth}
  9082. \small
  9083. \[
  9084. \begin{array}{lcl}
  9085. \Type &::= & \ldots \mid \key{Any} \\
  9086. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  9087. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  9088. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  9089. \mid \code{procedure?} \mid \code{void?} \\
  9090. \Exp &::=& \ldots
  9091. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  9092. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  9093. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9094. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9095. \end{array}
  9096. \]
  9097. \end{minipage}
  9098. }
  9099. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  9100. \label{fig:Rany-syntax}
  9101. \end{figure}
  9102. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  9103. (The concrete syntax of \LangAny{} is in the Appendix,
  9104. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  9105. converts the value produced by expression $e$ of type $T$ into a
  9106. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  9107. produced by expression $e$ into a value of type $T$ or else halts the
  9108. program if the type tag is not equivalent to $T$.
  9109. %
  9110. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  9111. restricted to a flat type $\FType$, which simplifies the
  9112. implementation and corresponds with what is needed for compiling \LangDyn{}.
  9113. The \code{any-vector} operators adapt the vector operations so that
  9114. they can be applied to a value of type \code{Any}. They also
  9115. generalize the vector operations in that the index is not restricted
  9116. to be a literal integer in the grammar but is allowed to be any
  9117. expression.
  9118. The type predicates such as \key{boolean?} expect their argument to
  9119. produce a tagged value; they return \key{\#t} if the tag corresponds
  9120. to the predicate and they return \key{\#f} otherwise.
  9121. The type checker for \LangAny{} is shown in
  9122. Figures~\ref{fig:type-check-Rany-part-1} and
  9123. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  9124. Figure~\ref{fig:type-check-Rany-aux}.
  9125. %
  9126. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  9127. auxiliary functions \code{apply-inject} and \code{apply-project} are
  9128. in Figure~\ref{fig:apply-project}.
  9129. \begin{figure}[btp]
  9130. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9131. (define type-check-Rany-class
  9132. (class type-check-Rlambda-class
  9133. (super-new)
  9134. (inherit check-type-equal?)
  9135. (define/override (type-check-exp env)
  9136. (lambda (e)
  9137. (define recur (type-check-exp env))
  9138. (match e
  9139. [(Inject e1 ty)
  9140. (unless (flat-ty? ty)
  9141. (error 'type-check "may only inject from flat type, not ~a" ty))
  9142. (define-values (new-e1 e-ty) (recur e1))
  9143. (check-type-equal? e-ty ty e)
  9144. (values (Inject new-e1 ty) 'Any)]
  9145. [(Project e1 ty)
  9146. (unless (flat-ty? ty)
  9147. (error 'type-check "may only project to flat type, not ~a" ty))
  9148. (define-values (new-e1 e-ty) (recur e1))
  9149. (check-type-equal? e-ty 'Any e)
  9150. (values (Project new-e1 ty) ty)]
  9151. [(Prim 'any-vector-length (list e1))
  9152. (define-values (e1^ t1) (recur e1))
  9153. (check-type-equal? t1 'Any e)
  9154. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  9155. [(Prim 'any-vector-ref (list e1 e2))
  9156. (define-values (e1^ t1) (recur e1))
  9157. (define-values (e2^ t2) (recur e2))
  9158. (check-type-equal? t1 'Any e)
  9159. (check-type-equal? t2 'Integer e)
  9160. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  9161. [(Prim 'any-vector-set! (list e1 e2 e3))
  9162. (define-values (e1^ t1) (recur e1))
  9163. (define-values (e2^ t2) (recur e2))
  9164. (define-values (e3^ t3) (recur e3))
  9165. (check-type-equal? t1 'Any e)
  9166. (check-type-equal? t2 'Integer e)
  9167. (check-type-equal? t3 'Any e)
  9168. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  9169. \end{lstlisting}
  9170. \caption{Type checker for the \LangAny{} language, part 1.}
  9171. \label{fig:type-check-Rany-part-1}
  9172. \end{figure}
  9173. \begin{figure}[btp]
  9174. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9175. [(ValueOf e ty)
  9176. (define-values (new-e e-ty) (recur e))
  9177. (values (ValueOf new-e ty) ty)]
  9178. [(Prim pred (list e1))
  9179. #:when (set-member? (type-predicates) pred)
  9180. (define-values (new-e1 e-ty) (recur e1))
  9181. (check-type-equal? e-ty 'Any e)
  9182. (values (Prim pred (list new-e1)) 'Boolean)]
  9183. [(If cnd thn els)
  9184. (define-values (cnd^ Tc) (recur cnd))
  9185. (define-values (thn^ Tt) (recur thn))
  9186. (define-values (els^ Te) (recur els))
  9187. (check-type-equal? Tc 'Boolean cnd)
  9188. (check-type-equal? Tt Te e)
  9189. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  9190. [(Exit) (values (Exit) '_)]
  9191. [(Prim 'eq? (list arg1 arg2))
  9192. (define-values (e1 t1) (recur arg1))
  9193. (define-values (e2 t2) (recur arg2))
  9194. (match* (t1 t2)
  9195. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9196. [(other wise) (check-type-equal? t1 t2 e)])
  9197. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9198. [else ((super type-check-exp env) e)])))
  9199. ))
  9200. \end{lstlisting}
  9201. \caption{Type checker for the \LangAny{} language, part 2.}
  9202. \label{fig:type-check-Rany-part-2}
  9203. \end{figure}
  9204. \begin{figure}[tbp]
  9205. \begin{lstlisting}
  9206. (define/override (operator-types)
  9207. (append
  9208. '((integer? . ((Any) . Boolean))
  9209. (vector? . ((Any) . Boolean))
  9210. (procedure? . ((Any) . Boolean))
  9211. (void? . ((Any) . Boolean))
  9212. (tag-of-any . ((Any) . Integer))
  9213. (make-any . ((_ Integer) . Any))
  9214. )
  9215. (super operator-types)))
  9216. (define/public (type-predicates)
  9217. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9218. (define/public (combine-types t1 t2)
  9219. (match (list t1 t2)
  9220. [(list '_ t2) t2]
  9221. [(list t1 '_) t1]
  9222. [(list `(Vector ,ts1 ...)
  9223. `(Vector ,ts2 ...))
  9224. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  9225. (combine-types t1 t2)))]
  9226. [(list `(,ts1 ... -> ,rt1)
  9227. `(,ts2 ... -> ,rt2))
  9228. `(,@(for/list ([t1 ts1] [t2 ts2])
  9229. (combine-types t1 t2))
  9230. -> ,(combine-types rt1 rt2))]
  9231. [else t1]))
  9232. (define/public (flat-ty? ty)
  9233. (match ty
  9234. [(or `Integer `Boolean '_ `Void) #t]
  9235. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  9236. [`(,ts ... -> ,rt)
  9237. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  9238. [else #f]))
  9239. \end{lstlisting}
  9240. \caption{Auxiliary methods for type checking \LangAny{}.}
  9241. \label{fig:type-check-Rany-aux}
  9242. \end{figure}
  9243. \begin{figure}[btp]
  9244. \begin{lstlisting}
  9245. (define interp-Rany-class
  9246. (class interp-Rlambda-class
  9247. (super-new)
  9248. (define/override (interp-op op)
  9249. (match op
  9250. ['boolean? (match-lambda
  9251. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  9252. [else #f])]
  9253. ['integer? (match-lambda
  9254. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  9255. [else #f])]
  9256. ['vector? (match-lambda
  9257. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  9258. [else #f])]
  9259. ['procedure? (match-lambda
  9260. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  9261. [else #f])]
  9262. ['eq? (match-lambda*
  9263. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  9264. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  9265. [ls (apply (super interp-op op) ls)])]
  9266. ['any-vector-ref (lambda (v i)
  9267. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  9268. ['any-vector-set! (lambda (v i a)
  9269. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  9270. ['any-vector-length (lambda (v)
  9271. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  9272. [else (super interp-op op)]))
  9273. (define/override ((interp-exp env) e)
  9274. (define recur (interp-exp env))
  9275. (match e
  9276. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9277. [(Project e ty2) (apply-project (recur e) ty2)]
  9278. [else ((super interp-exp env) e)]))
  9279. ))
  9280. (define (interp-Rany p)
  9281. (send (new interp-Rany-class) interp-program p))
  9282. \end{lstlisting}
  9283. \caption{Interpreter for \LangAny{}.}
  9284. \label{fig:interp-Rany}
  9285. \end{figure}
  9286. \begin{figure}[tbp]
  9287. \begin{lstlisting}
  9288. (define/public (apply-inject v tg) (Tagged v tg))
  9289. (define/public (apply-project v ty2)
  9290. (define tag2 (any-tag ty2))
  9291. (match v
  9292. [(Tagged v1 tag1)
  9293. (cond
  9294. [(eq? tag1 tag2)
  9295. (match ty2
  9296. [`(Vector ,ts ...)
  9297. (define l1 ((interp-op 'vector-length) v1))
  9298. (cond
  9299. [(eq? l1 (length ts)) v1]
  9300. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9301. l1 (length ts))])]
  9302. [`(,ts ... -> ,rt)
  9303. (match v1
  9304. [`(function ,xs ,body ,env)
  9305. (cond [(eq? (length xs) (length ts)) v1]
  9306. [else
  9307. (error 'apply-project "arity mismatch ~a != ~a"
  9308. (length xs) (length ts))])]
  9309. [else (error 'apply-project "expected function not ~a" v1)])]
  9310. [else v1])]
  9311. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9312. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9313. \end{lstlisting}
  9314. \caption{Auxiliary functions for injection and projection.}
  9315. \label{fig:apply-project}
  9316. \end{figure}
  9317. \clearpage
  9318. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9319. \label{sec:compile-r7}
  9320. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9321. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9322. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9323. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9324. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9325. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9326. the Boolean \code{\#t}, which must be injected to produce an
  9327. expression of type \key{Any}.
  9328. %
  9329. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9330. addition, is representative of compilation for many primitive
  9331. operations: the arguments have type \key{Any} and must be projected to
  9332. \key{Integer} before the addition can be performed.
  9333. The compilation of \key{lambda} (third row of
  9334. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9335. produce type annotations: we simply use \key{Any}.
  9336. %
  9337. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9338. has to account for some differences in behavior between \LangDyn{} and
  9339. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9340. kind of values can be used in various places. For example, the
  9341. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9342. the arguments need not be of the same type (in that case the
  9343. result is \code{\#f}).
  9344. \begin{figure}[btp]
  9345. \centering
  9346. \begin{tabular}{|lll|} \hline
  9347. \begin{minipage}{0.27\textwidth}
  9348. \begin{lstlisting}
  9349. #t
  9350. \end{lstlisting}
  9351. \end{minipage}
  9352. &
  9353. $\Rightarrow$
  9354. &
  9355. \begin{minipage}{0.65\textwidth}
  9356. \begin{lstlisting}
  9357. (inject #t Boolean)
  9358. \end{lstlisting}
  9359. \end{minipage}
  9360. \\[2ex]\hline
  9361. \begin{minipage}{0.27\textwidth}
  9362. \begin{lstlisting}
  9363. (+ |$e_1$| |$e_2$|)
  9364. \end{lstlisting}
  9365. \end{minipage}
  9366. &
  9367. $\Rightarrow$
  9368. &
  9369. \begin{minipage}{0.65\textwidth}
  9370. \begin{lstlisting}
  9371. (inject
  9372. (+ (project |$e'_1$| Integer)
  9373. (project |$e'_2$| Integer))
  9374. Integer)
  9375. \end{lstlisting}
  9376. \end{minipage}
  9377. \\[2ex]\hline
  9378. \begin{minipage}{0.27\textwidth}
  9379. \begin{lstlisting}
  9380. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9381. \end{lstlisting}
  9382. \end{minipage}
  9383. &
  9384. $\Rightarrow$
  9385. &
  9386. \begin{minipage}{0.65\textwidth}
  9387. \begin{lstlisting}
  9388. (inject
  9389. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9390. (Any|$\ldots$|Any -> Any))
  9391. \end{lstlisting}
  9392. \end{minipage}
  9393. \\[2ex]\hline
  9394. \begin{minipage}{0.27\textwidth}
  9395. \begin{lstlisting}
  9396. (|$e_0$| |$e_1 \ldots e_n$|)
  9397. \end{lstlisting}
  9398. \end{minipage}
  9399. &
  9400. $\Rightarrow$
  9401. &
  9402. \begin{minipage}{0.65\textwidth}
  9403. \begin{lstlisting}
  9404. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9405. \end{lstlisting}
  9406. \end{minipage}
  9407. \\[2ex]\hline
  9408. \begin{minipage}{0.27\textwidth}
  9409. \begin{lstlisting}
  9410. (vector-ref |$e_1$| |$e_2$|)
  9411. \end{lstlisting}
  9412. \end{minipage}
  9413. &
  9414. $\Rightarrow$
  9415. &
  9416. \begin{minipage}{0.65\textwidth}
  9417. \begin{lstlisting}
  9418. (any-vector-ref |$e_1'$| |$e_2'$|)
  9419. \end{lstlisting}
  9420. \end{minipage}
  9421. \\[2ex]\hline
  9422. \begin{minipage}{0.27\textwidth}
  9423. \begin{lstlisting}
  9424. (if |$e_1$| |$e_2$| |$e_3$|)
  9425. \end{lstlisting}
  9426. \end{minipage}
  9427. &
  9428. $\Rightarrow$
  9429. &
  9430. \begin{minipage}{0.65\textwidth}
  9431. \begin{lstlisting}
  9432. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9433. \end{lstlisting}
  9434. \end{minipage}
  9435. \\[2ex]\hline
  9436. \begin{minipage}{0.27\textwidth}
  9437. \begin{lstlisting}
  9438. (eq? |$e_1$| |$e_2$|)
  9439. \end{lstlisting}
  9440. \end{minipage}
  9441. &
  9442. $\Rightarrow$
  9443. &
  9444. \begin{minipage}{0.65\textwidth}
  9445. \begin{lstlisting}
  9446. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9447. \end{lstlisting}
  9448. \end{minipage}
  9449. \\[2ex]\hline
  9450. \begin{minipage}{0.27\textwidth}
  9451. \begin{lstlisting}
  9452. (not |$e_1$|)
  9453. \end{lstlisting}
  9454. \end{minipage}
  9455. &
  9456. $\Rightarrow$
  9457. &
  9458. \begin{minipage}{0.65\textwidth}
  9459. \begin{lstlisting}
  9460. (if (eq? |$e'_1$| (inject #f Boolean))
  9461. (inject #t Boolean) (inject #f Boolean))
  9462. \end{lstlisting}
  9463. \end{minipage}
  9464. \\[2ex]\hline
  9465. \end{tabular}
  9466. \caption{Cast Insertion}
  9467. \label{fig:compile-r7-Rany}
  9468. \end{figure}
  9469. \section{Reveal Casts}
  9470. \label{sec:reveal-casts-Rany}
  9471. % TODO: define R'_6
  9472. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9473. into an \code{if} expression that checks whether the value's tag
  9474. matches the target type; if it does, the value is converted to a value
  9475. of the target type by removing the tag; if it does not, the program
  9476. exits. To perform these actions we need a new primitive operation,
  9477. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9478. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9479. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9480. underlying value from a tagged value. The \code{ValueOf} form
  9481. includes the type for the underlying value which is used by the type
  9482. checker. Finally, the \code{Exit} form ends the execution of the
  9483. program.
  9484. If the target type of the projection is \code{Boolean} or
  9485. \code{Integer}, then \code{Project} can be translated as follows.
  9486. \begin{center}
  9487. \begin{minipage}{1.0\textwidth}
  9488. \begin{lstlisting}
  9489. (Project |$e$| |$\FType$|)
  9490. |$\Rightarrow$|
  9491. (Let |$\itm{tmp}$| |$e'$|
  9492. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9493. (Int |$\itm{tagof}(\FType)$|)))
  9494. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9495. (Exit)))
  9496. \end{lstlisting}
  9497. \end{minipage}
  9498. \end{center}
  9499. If the target type of the projection is a vector or function type,
  9500. then there is a bit more work to do. For vectors, check that the
  9501. length of the vector type matches the length of the vector (using the
  9502. \code{vector-length} primitive). For functions, check that the number
  9503. of parameters in the function type matches the function's arity (using
  9504. \code{procedure-arity}).
  9505. Regarding \code{inject}, we recommend compiling it to a slightly
  9506. lower-level primitive operation named \code{make-any}. This operation
  9507. takes a tag instead of a type.
  9508. \begin{center}
  9509. \begin{minipage}{1.0\textwidth}
  9510. \begin{lstlisting}
  9511. (Inject |$e$| |$\FType$|)
  9512. |$\Rightarrow$|
  9513. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9514. \end{lstlisting}
  9515. \end{minipage}
  9516. \end{center}
  9517. The type predicates (\code{boolean?}, etc.) can be translated into
  9518. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9519. translation of \code{Project}.
  9520. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9521. combine the projection action with the vector operation. Also, the
  9522. read and write operations allow arbitrary expressions for the index so
  9523. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9524. cannot guarantee that the index is within bounds. Thus, we insert code
  9525. to perform bounds checking at runtime. The translation for
  9526. \code{any-vector-ref} is as follows and the other two operations are
  9527. translated in a similar way.
  9528. \begin{lstlisting}
  9529. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9530. |$\Rightarrow$|
  9531. (Let |$v$| |$e'_1$|
  9532. (Let |$i$| |$e'_2$|
  9533. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9534. (If (Prim '< (list (Var |$i$|)
  9535. (Prim 'any-vector-length (list (Var |$v$|)))))
  9536. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9537. (Exit))))
  9538. \end{lstlisting}
  9539. \section{Remove Complex Operands}
  9540. \label{sec:rco-Rany}
  9541. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9542. The subexpression of \code{ValueOf} must be atomic.
  9543. \section{Explicate Control and \LangCAny{}}
  9544. \label{sec:explicate-Rany}
  9545. The output of \code{explicate-control} is the \LangCAny{} language whose
  9546. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9547. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9548. expression becomes a $\Tail$. Also, note that the index argument of
  9549. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9550. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9551. \begin{figure}[tp]
  9552. \fbox{
  9553. \begin{minipage}{0.96\textwidth}
  9554. \small
  9555. \[
  9556. \begin{array}{lcl}
  9557. \Exp &::= & \ldots
  9558. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9559. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9560. &\mid& \VALUEOF{\Exp}{\FType} \\
  9561. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9562. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9563. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9564. \mid \GOTO{\itm{label}} } \\
  9565. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9566. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9567. \mid \LP\key{Exit}\RP \\
  9568. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9569. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9570. \end{array}
  9571. \]
  9572. \end{minipage}
  9573. }
  9574. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9575. \label{fig:c5-syntax}
  9576. \end{figure}
  9577. \section{Select Instructions}
  9578. \label{sec:select-Rany}
  9579. In the \code{select-instructions} pass we translate the primitive
  9580. operations on the \code{Any} type to x86 instructions that involve
  9581. manipulating the 3 tag bits of the tagged value.
  9582. \paragraph{Make-any}
  9583. We recommend compiling the \key{make-any} primitive as follows if the
  9584. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9585. shifts the destination to the left by the number of bits specified its
  9586. source argument (in this case $3$, the length of the tag) and it
  9587. preserves the sign of the integer. We use the \key{orq} instruction to
  9588. combine the tag and the value to form the tagged value. \\
  9589. \begin{lstlisting}
  9590. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9591. |$\Rightarrow$|
  9592. movq |$e'$|, |\itm{lhs'}|
  9593. salq $3, |\itm{lhs'}|
  9594. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9595. \end{lstlisting}
  9596. The instruction selection for vectors and procedures is different
  9597. because their is no need to shift them to the left. The rightmost 3
  9598. bits are already zeros as described at the beginning of this
  9599. chapter. So we just combine the value and the tag using \key{orq}. \\
  9600. \begin{lstlisting}
  9601. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9602. |$\Rightarrow$|
  9603. movq |$e'$|, |\itm{lhs'}|
  9604. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9605. \end{lstlisting}
  9606. \paragraph{Tag-of-any}
  9607. Recall that the \code{tag-of-any} operation extracts the type tag from
  9608. a value of type \code{Any}. The type tag is the bottom three bits, so
  9609. we obtain the tag by taking the bitwise-and of the value with $111$
  9610. ($7$ in decimal).
  9611. \begin{lstlisting}
  9612. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9613. |$\Rightarrow$|
  9614. movq |$e'$|, |\itm{lhs'}|
  9615. andq $7, |\itm{lhs'}|
  9616. \end{lstlisting}
  9617. \paragraph{ValueOf}
  9618. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9619. depending on whether the type $T$ is a pointer (vector or procedure)
  9620. or not (Integer or Boolean). The following shows the instruction
  9621. selection for Integer and Boolean. We produce an untagged value by
  9622. shifting it to the right by 3 bits.
  9623. \begin{lstlisting}
  9624. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9625. |$\Rightarrow$|
  9626. movq |$e'$|, |\itm{lhs'}|
  9627. sarq $3, |\itm{lhs'}|
  9628. \end{lstlisting}
  9629. %
  9630. In the case for vectors and procedures, there is no need to
  9631. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9632. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9633. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9634. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9635. then apply \code{andq} with the tagged value to get the desired
  9636. result. \\
  9637. \begin{lstlisting}
  9638. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9639. |$\Rightarrow$|
  9640. movq $|$-8$|, |\itm{lhs'}|
  9641. andq |$e'$|, |\itm{lhs'}|
  9642. \end{lstlisting}
  9643. %% \paragraph{Type Predicates} We leave it to the reader to
  9644. %% devise a sequence of instructions to implement the type predicates
  9645. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9646. \paragraph{Any-vector-length}
  9647. \begin{lstlisting}
  9648. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9649. |$\Longrightarrow$|
  9650. movq |$\neg 111$|, %r11
  9651. andq |$a_1'$|, %r11
  9652. movq 0(%r11), %r11
  9653. andq $126, %r11
  9654. sarq $1, %r11
  9655. movq %r11, |$\itm{lhs'}$|
  9656. \end{lstlisting}
  9657. \paragraph{Any-vector-ref}
  9658. The index may be an arbitrary atom so instead of computing the offset
  9659. at compile time, instructions need to be generated to compute the
  9660. offset at runtime as follows. Note the use of the new instruction
  9661. \code{imulq}.
  9662. \begin{center}
  9663. \begin{minipage}{0.96\textwidth}
  9664. \begin{lstlisting}
  9665. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9666. |$\Longrightarrow$|
  9667. movq |$\neg 111$|, %r11
  9668. andq |$a_1'$|, %r11
  9669. movq |$a_2'$|, %rax
  9670. addq $1, %rax
  9671. imulq $8, %rax
  9672. addq %rax, %r11
  9673. movq 0(%r11) |$\itm{lhs'}$|
  9674. \end{lstlisting}
  9675. \end{minipage}
  9676. \end{center}
  9677. \paragraph{Any-vector-set!}
  9678. The code generation for \code{any-vector-set!} is similar to the other
  9679. \code{any-vector} operations.
  9680. \section{Register Allocation for \LangAny{}}
  9681. \label{sec:register-allocation-Rany}
  9682. \index{subject}{register allocation}
  9683. There is an interesting interaction between tagged values and garbage
  9684. collection that has an impact on register allocation. A variable of
  9685. type \code{Any} might refer to a vector and therefore it might be a
  9686. root that needs to be inspected and copied during garbage
  9687. collection. Thus, we need to treat variables of type \code{Any} in a
  9688. similar way to variables of type \code{Vector} for purposes of
  9689. register allocation. In particular,
  9690. \begin{itemize}
  9691. \item If a variable of type \code{Any} is live during a function call,
  9692. then it must be spilled. This can be accomplished by changing
  9693. \code{build-interference} to mark all variables of type \code{Any}
  9694. that are live after a \code{callq} as interfering with all the
  9695. registers.
  9696. \item If a variable of type \code{Any} is spilled, it must be spilled
  9697. to the root stack instead of the normal procedure call stack.
  9698. \end{itemize}
  9699. Another concern regarding the root stack is that the garbage collector
  9700. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9701. tagged value that points to a tuple, and (3) a tagged value that is
  9702. not a tuple. We enable this differentiation by choosing not to use the
  9703. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9704. reserved for identifying plain old pointers to tuples. That way, if
  9705. one of the first three bits is set, then we have a tagged value and
  9706. inspecting the tag can differentiation between vectors ($010$) and the
  9707. other kinds of values.
  9708. \begin{exercise}\normalfont
  9709. Expand your compiler to handle \LangAny{} as discussed in the last few
  9710. sections. Create 5 new programs that use the \code{Any} type and the
  9711. new operations (\code{inject}, \code{project}, \code{boolean?},
  9712. etc.). Test your compiler on these new programs and all of your
  9713. previously created test programs.
  9714. \end{exercise}
  9715. \begin{exercise}\normalfont
  9716. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9717. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9718. by removing type annotations. Add 5 more tests programs that
  9719. specifically rely on the language being dynamically typed. That is,
  9720. they should not be legal programs in a statically typed language, but
  9721. nevertheless, they should be valid \LangDyn{} programs that run to
  9722. completion without error.
  9723. \end{exercise}
  9724. \begin{figure}[p]
  9725. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9726. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9727. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9728. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9729. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9730. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9731. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9732. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9733. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9734. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9735. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9736. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9737. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9738. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9739. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9740. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9741. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9742. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9743. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9744. \path[->,bend left=15] (Rfun) edge [above] node
  9745. {\ttfamily\footnotesize shrink} (Rfun-2);
  9746. \path[->,bend left=15] (Rfun-2) edge [above] node
  9747. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9748. \path[->,bend left=15] (Rfun-3) edge [above] node
  9749. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9750. \path[->,bend right=15] (Rfun-4) edge [left] node
  9751. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9752. \path[->,bend left=15] (Rfun-5) edge [above] node
  9753. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9754. \path[->,bend left=15] (Rfun-6) edge [left] node
  9755. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9756. \path[->,bend left=15] (Rfun-7) edge [below] node
  9757. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9758. \path[->,bend right=15] (F1-2) edge [above] node
  9759. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9760. \path[->,bend right=15] (F1-3) edge [above] node
  9761. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9762. \path[->,bend right=15] (F1-4) edge [above] node
  9763. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9764. \path[->,bend right=15] (F1-5) edge [right] node
  9765. {\ttfamily\footnotesize explicate-control} (C3-2);
  9766. \path[->,bend left=15] (C3-2) edge [left] node
  9767. {\ttfamily\footnotesize select-instr.} (x86-2);
  9768. \path[->,bend right=15] (x86-2) edge [left] node
  9769. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9770. \path[->,bend right=15] (x86-2-1) edge [below] node
  9771. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9772. \path[->,bend right=15] (x86-2-2) edge [left] node
  9773. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9774. \path[->,bend left=15] (x86-3) edge [above] node
  9775. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9776. \path[->,bend left=15] (x86-4) edge [right] node
  9777. {\ttfamily\footnotesize print-x86} (x86-5);
  9778. \end{tikzpicture}
  9779. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9780. \label{fig:Rdyn-passes}
  9781. \end{figure}
  9782. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9783. for the compilation of \LangDyn{}.
  9784. % Further Reading
  9785. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9786. \chapter{Loops and Assignment}
  9787. \label{ch:Rwhile}
  9788. % TODO: define R'_8
  9789. % TODO: multi-graph
  9790. In this chapter we study two features that are the hallmarks of
  9791. imperative programming languages: loops and assignments to local
  9792. variables. The following example demonstrates these new features by
  9793. computing the sum of the first five positive integers.
  9794. % similar to loop_test_1.rkt
  9795. \begin{lstlisting}
  9796. (let ([sum 0])
  9797. (let ([i 5])
  9798. (begin
  9799. (while (> i 0)
  9800. (begin
  9801. (set! sum (+ sum i))
  9802. (set! i (- i 1))))
  9803. sum)))
  9804. \end{lstlisting}
  9805. The \code{while} loop consists of a condition and a body.
  9806. %
  9807. The \code{set!} consists of a variable and a right-hand-side expression.
  9808. %
  9809. The primary purpose of both the \code{while} loop and \code{set!} is
  9810. to cause side effects, so it is convenient to also include in a
  9811. language feature for sequencing side effects: the \code{begin}
  9812. expression. It consists of one or more subexpressions that are
  9813. evaluated left-to-right.
  9814. \section{The \LangLoop{} Language}
  9815. \begin{figure}[tp]
  9816. \centering
  9817. \fbox{
  9818. \begin{minipage}{0.96\textwidth}
  9819. \small
  9820. \[
  9821. \begin{array}{lcl}
  9822. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9823. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9824. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9825. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9826. \mid (\key{and}\;\Exp\;\Exp)
  9827. \mid (\key{or}\;\Exp\;\Exp)
  9828. \mid (\key{not}\;\Exp) } \\
  9829. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9830. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9831. (\key{vector-ref}\;\Exp\;\Int)} \\
  9832. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9833. \mid (\Exp \; \Exp\ldots) } \\
  9834. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9835. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9836. &\mid& \CSETBANG{\Var}{\Exp}
  9837. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9838. \mid \CWHILE{\Exp}{\Exp} \\
  9839. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9840. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  9841. \end{array}
  9842. \]
  9843. \end{minipage}
  9844. }
  9845. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9846. \label{fig:Rwhile-concrete-syntax}
  9847. \end{figure}
  9848. \begin{figure}[tp]
  9849. \centering
  9850. \fbox{
  9851. \begin{minipage}{0.96\textwidth}
  9852. \small
  9853. \[
  9854. \begin{array}{lcl}
  9855. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9856. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9857. &\mid& \gray{ \BOOL{\itm{bool}}
  9858. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9859. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9860. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9861. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9862. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9863. \mid \WHILE{\Exp}{\Exp} \\
  9864. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9865. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9866. \end{array}
  9867. \]
  9868. \end{minipage}
  9869. }
  9870. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9871. \label{fig:Rwhile-syntax}
  9872. \end{figure}
  9873. The concrete syntax of \LangLoop{} is defined in
  9874. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9875. in Figure~\ref{fig:Rwhile-syntax}.
  9876. %
  9877. The definitional interpreter for \LangLoop{} is shown in
  9878. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9879. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9880. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9881. support assignment to variables and to make their lifetimes indefinite
  9882. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9883. box the value that is bound to each variable (in \code{Let}) and
  9884. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9885. the value.
  9886. %
  9887. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9888. variable in the environment to obtain a boxed value and then we change
  9889. it using \code{set-box!} to the result of evaluating the right-hand
  9890. side. The result value of a \code{SetBang} is \code{void}.
  9891. %
  9892. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9893. if the result is true, 2) evaluate the body.
  9894. The result value of a \code{while} loop is also \code{void}.
  9895. %
  9896. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9897. subexpressions \itm{es} for their effects and then evaluates
  9898. and returns the result from \itm{body}.
  9899. \begin{figure}[tbp]
  9900. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9901. (define interp-Rwhile-class
  9902. (class interp-Rany-class
  9903. (super-new)
  9904. (define/override ((interp-exp env) e)
  9905. (define recur (interp-exp env))
  9906. (match e
  9907. [(SetBang x rhs)
  9908. (set-box! (lookup x env) (recur rhs))]
  9909. [(WhileLoop cnd body)
  9910. (define (loop)
  9911. (cond [(recur cnd) (recur body) (loop)]
  9912. [else (void)]))
  9913. (loop)]
  9914. [(Begin es body)
  9915. (for ([e es]) (recur e))
  9916. (recur body)]
  9917. [else ((super interp-exp env) e)]))
  9918. ))
  9919. (define (interp-Rwhile p)
  9920. (send (new interp-Rwhile-class) interp-program p))
  9921. \end{lstlisting}
  9922. \caption{Interpreter for \LangLoop{}.}
  9923. \label{fig:interp-Rwhile}
  9924. \end{figure}
  9925. The type checker for \LangLoop{} is define in
  9926. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9927. variable and the right-hand-side must agree. The result type is
  9928. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9929. \code{Boolean}. The result type is also \code{Void}. For
  9930. \code{Begin}, the result type is the type of its last subexpression.
  9931. \begin{figure}[tbp]
  9932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9933. (define type-check-Rwhile-class
  9934. (class type-check-Rany-class
  9935. (super-new)
  9936. (inherit check-type-equal?)
  9937. (define/override (type-check-exp env)
  9938. (lambda (e)
  9939. (define recur (type-check-exp env))
  9940. (match e
  9941. [(SetBang x rhs)
  9942. (define-values (rhs^ rhsT) (recur rhs))
  9943. (define varT (dict-ref env x))
  9944. (check-type-equal? rhsT varT e)
  9945. (values (SetBang x rhs^) 'Void)]
  9946. [(WhileLoop cnd body)
  9947. (define-values (cnd^ Tc) (recur cnd))
  9948. (check-type-equal? Tc 'Boolean e)
  9949. (define-values (body^ Tbody) ((type-check-exp env) body))
  9950. (values (WhileLoop cnd^ body^) 'Void)]
  9951. [(Begin es body)
  9952. (define-values (es^ ts)
  9953. (for/lists (l1 l2) ([e es]) (recur e)))
  9954. (define-values (body^ Tbody) (recur body))
  9955. (values (Begin es^ body^) Tbody)]
  9956. [else ((super type-check-exp env) e)])))
  9957. ))
  9958. (define (type-check-Rwhile p)
  9959. (send (new type-check-Rwhile-class) type-check-program p))
  9960. \end{lstlisting}
  9961. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9962. and \code{Begin} in \LangLoop{}.}
  9963. \label{fig:type-check-Rwhile}
  9964. \end{figure}
  9965. At first glance, the translation of these language features to x86
  9966. seems straightforward because the \LangCFun{} intermediate language already
  9967. supports all of the ingredients that we need: assignment, \code{goto},
  9968. conditional branching, and sequencing. However, there are two
  9969. complications that arise which we discuss in the next two
  9970. sections. After that we introduce one new compiler pass and the
  9971. changes necessary to the existing passes.
  9972. \section{Assignment and Lexically Scoped Functions}
  9973. \label{sec:assignment-scoping}
  9974. The addition of assignment raises a problem with our approach to
  9975. implementing lexically-scoped functions. Consider the following
  9976. example in which function \code{f} has a free variable \code{x} that
  9977. is changed after \code{f} is created but before the call to \code{f}.
  9978. % loop_test_11.rkt
  9979. \begin{lstlisting}
  9980. (let ([x 0])
  9981. (let ([y 0])
  9982. (let ([z 20])
  9983. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9984. (begin
  9985. (set! x 10)
  9986. (set! y 12)
  9987. (f y))))))
  9988. \end{lstlisting}
  9989. The correct output for this example is \code{42} because the call to
  9990. \code{f} is required to use the current value of \code{x} (which is
  9991. \code{10}). Unfortunately, the closure conversion pass
  9992. (Section~\ref{sec:closure-conversion}) generates code for the
  9993. \code{lambda} that copies the old value of \code{x} into a
  9994. closure. Thus, if we naively add support for assignment to our current
  9995. compiler, the output of this program would be \code{32}.
  9996. A first attempt at solving this problem would be to save a pointer to
  9997. \code{x} in the closure and change the occurrences of \code{x} inside
  9998. the lambda to dereference the pointer. Of course, this would require
  9999. assigning \code{x} to the stack and not to a register. However, the
  10000. problem goes a bit deeper. Consider the following example in which we
  10001. create a counter abstraction by creating a pair of functions that
  10002. share the free variable \code{x}.
  10003. % similar to loop_test_10.rkt
  10004. \begin{lstlisting}
  10005. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  10006. (vector
  10007. (lambda: () : Integer x)
  10008. (lambda: () : Void (set! x (+ 1 x)))))
  10009. (let ([counter (f 0)])
  10010. (let ([get (vector-ref counter 0)])
  10011. (let ([inc (vector-ref counter 1)])
  10012. (begin
  10013. (inc)
  10014. (get)))))
  10015. \end{lstlisting}
  10016. In this example, the lifetime of \code{x} extends beyond the lifetime
  10017. of the call to \code{f}. Thus, if we were to store \code{x} on the
  10018. stack frame for the call to \code{f}, it would be gone by the time we
  10019. call \code{inc} and \code{get}, leaving us with dangling pointers for
  10020. \code{x}. This example demonstrates that when a variable occurs free
  10021. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  10022. value of the variable needs to live on the heap. The verb ``box'' is
  10023. often used for allocating a single value on the heap, producing a
  10024. pointer, and ``unbox'' for dereferencing the pointer.
  10025. We recommend solving these problems by ``boxing'' the local variables
  10026. that are in the intersection of 1) variables that appear on the
  10027. left-hand-side of a \code{set!} and 2) variables that occur free
  10028. inside a \code{lambda}. We shall introduce a new pass named
  10029. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  10030. perform this translation. But before diving into the compiler passes,
  10031. we one more problem to discuss.
  10032. \section{Cyclic Control Flow and Dataflow Analysis}
  10033. \label{sec:dataflow-analysis}
  10034. Up until this point the control-flow graphs generated in
  10035. \code{explicate-control} were guaranteed to be acyclic. However, each
  10036. \code{while} loop introduces a cycle in the control-flow graph.
  10037. But does that matter?
  10038. %
  10039. Indeed it does. Recall that for register allocation, the compiler
  10040. performs liveness analysis to determine which variables can share the
  10041. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  10042. the control-flow graph in reverse topological order, but topological
  10043. order is only well-defined for acyclic graphs.
  10044. Let us return to the example of computing the sum of the first five
  10045. positive integers. Here is the program after instruction selection but
  10046. before register allocation.
  10047. \begin{center}
  10048. \begin{minipage}{0.45\textwidth}
  10049. \begin{lstlisting}
  10050. (define (main) : Integer
  10051. mainstart:
  10052. movq $0, sum1
  10053. movq $5, i2
  10054. jmp block5
  10055. block5:
  10056. movq i2, tmp3
  10057. cmpq tmp3, $0
  10058. jl block7
  10059. jmp block8
  10060. \end{lstlisting}
  10061. \end{minipage}
  10062. \begin{minipage}{0.45\textwidth}
  10063. \begin{lstlisting}
  10064. block7:
  10065. addq i2, sum1
  10066. movq $1, tmp4
  10067. negq tmp4
  10068. addq tmp4, i2
  10069. jmp block5
  10070. block8:
  10071. movq $27, %rax
  10072. addq sum1, %rax
  10073. jmp mainconclusion
  10074. )
  10075. \end{lstlisting}
  10076. \end{minipage}
  10077. \end{center}
  10078. Recall that liveness analysis works backwards, starting at the end
  10079. of each function. For this example we could start with \code{block8}
  10080. because we know what is live at the beginning of the conclusion,
  10081. just \code{rax} and \code{rsp}. So the live-before set
  10082. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  10083. %
  10084. Next we might try to analyze \code{block5} or \code{block7}, but
  10085. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10086. we are stuck.
  10087. The way out of this impasse comes from the realization that one can
  10088. perform liveness analysis starting with an empty live-after set to
  10089. compute an under-approximation of the live-before set. By
  10090. \emph{under-approximation}, we mean that the set only contains
  10091. variables that are really live, but it may be missing some. Next, the
  10092. under-approximations for each block can be improved by 1) updating the
  10093. live-after set for each block using the approximate live-before sets
  10094. from the other blocks and 2) perform liveness analysis again on each
  10095. block. In fact, by iterating this process, the under-approximations
  10096. eventually become the correct solutions!
  10097. %
  10098. This approach of iteratively analyzing a control-flow graph is
  10099. applicable to many static analysis problems and goes by the name
  10100. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10101. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  10102. Washington.
  10103. Let us apply this approach to the above example. We use the empty set
  10104. for the initial live-before set for each block. Let $m_0$ be the
  10105. following mapping from label names to sets of locations (variables and
  10106. registers).
  10107. \begin{center}
  10108. \begin{lstlisting}
  10109. mainstart: {}
  10110. block5: {}
  10111. block7: {}
  10112. block8: {}
  10113. \end{lstlisting}
  10114. \end{center}
  10115. Using the above live-before approximations, we determine the
  10116. live-after for each block and then apply liveness analysis to each
  10117. block. This produces our next approximation $m_1$ of the live-before
  10118. sets.
  10119. \begin{center}
  10120. \begin{lstlisting}
  10121. mainstart: {}
  10122. block5: {i2}
  10123. block7: {i2, sum1}
  10124. block8: {rsp, sum1}
  10125. \end{lstlisting}
  10126. \end{center}
  10127. For the second round, the live-after for \code{mainstart} is the
  10128. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  10129. liveness analysis for \code{mainstart} computes the empty set. The
  10130. live-after for \code{block5} is the union of the live-before sets for
  10131. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  10132. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  10133. sum1\}}. The live-after for \code{block7} is the live-before for
  10134. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  10135. So the liveness analysis for \code{block7} remains \code{\{i2,
  10136. sum1\}}. Together these yield the following approximation $m_2$ of
  10137. the live-before sets.
  10138. \begin{center}
  10139. \begin{lstlisting}
  10140. mainstart: {}
  10141. block5: {i2, rsp, sum1}
  10142. block7: {i2, sum1}
  10143. block8: {rsp, sum1}
  10144. \end{lstlisting}
  10145. \end{center}
  10146. In the preceding iteration, only \code{block5} changed, so we can
  10147. limit our attention to \code{mainstart} and \code{block7}, the two
  10148. blocks that jump to \code{block5}. As a result, the live-before sets
  10149. for \code{mainstart} and \code{block7} are updated to include
  10150. \code{rsp}, yielding the following approximation $m_3$.
  10151. \begin{center}
  10152. \begin{lstlisting}
  10153. mainstart: {rsp}
  10154. block5: {i2, rsp, sum1}
  10155. block7: {i2, rsp, sum1}
  10156. block8: {rsp, sum1}
  10157. \end{lstlisting}
  10158. \end{center}
  10159. Because \code{block7} changed, we analyze \code{block5} once more, but
  10160. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  10161. our approximations have converged, so $m_3$ is the solution.
  10162. This iteration process is guaranteed to converge to a solution by the
  10163. Kleene Fixed-Point Theorem, a general theorem about functions on
  10164. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10165. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10166. elements, a least element $\bot$ (pronounced bottom), and a join
  10167. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10168. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  10169. working with join semi-lattices.} When two elements are ordered $m_i
  10170. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  10171. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  10172. approximation than $m_i$. The bottom element $\bot$ represents the
  10173. complete lack of information, i.e., the worst approximation. The join
  10174. operator takes two lattice elements and combines their information,
  10175. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  10176. bound}
  10177. A dataflow analysis typically involves two lattices: one lattice to
  10178. represent abstract states and another lattice that aggregates the
  10179. abstract states of all the blocks in the control-flow graph. For
  10180. liveness analysis, an abstract state is a set of locations. We form
  10181. the lattice $L$ by taking its elements to be sets of locations, the
  10182. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10183. set, and the join operator to be set union.
  10184. %
  10185. We form a second lattice $M$ by taking its elements to be mappings
  10186. from the block labels to sets of locations (elements of $L$). We
  10187. order the mappings point-wise, using the ordering of $L$. So given any
  10188. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10189. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10190. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10191. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  10192. We can think of one iteration of liveness analysis as being a function
  10193. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  10194. mapping.
  10195. \[
  10196. f(m_i) = m_{i+1}
  10197. \]
  10198. Next let us think for a moment about what a final solution $m_s$
  10199. should look like. If we perform liveness analysis using the solution
  10200. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10201. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10202. \[
  10203. f(m_s) = m_s
  10204. \]
  10205. Furthermore, the solution should only include locations that are
  10206. forced to be there by performing liveness analysis on the program, so
  10207. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10208. The Kleene Fixed-Point Theorem states that if a function $f$ is
  10209. monotone (better inputs produce better outputs), then the least fixed
  10210. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10211. chain} obtained by starting at $\bot$ and iterating $f$ as
  10212. follows.\index{subject}{Kleene Fixed-Point Theorem}
  10213. \[
  10214. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10215. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10216. \]
  10217. When a lattice contains only finitely-long ascending chains, then
  10218. every Kleene chain tops out at some fixed point after a number of
  10219. iterations of $f$. So that fixed point is also a least upper
  10220. bound of the chain.
  10221. \[
  10222. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10223. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10224. \]
  10225. The liveness analysis is indeed a monotone function and the lattice
  10226. $M$ only has finitely-long ascending chains because there are only a
  10227. finite number of variables and blocks in the program. Thus we are
  10228. guaranteed that iteratively applying liveness analysis to all blocks
  10229. in the program will eventually produce the least fixed point solution.
  10230. Next let us consider dataflow analysis in general and discuss the
  10231. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  10232. %
  10233. The algorithm has four parameters: the control-flow graph \code{G}, a
  10234. function \code{transfer} that applies the analysis to one block, the
  10235. \code{bottom} and \code{join} operator for the lattice of abstract
  10236. states. The algorithm begins by creating the bottom mapping,
  10237. represented by a hash table. It then pushes all of the nodes in the
  10238. control-flow graph onto the work list (a queue). The algorithm repeats
  10239. the \code{while} loop as long as there are items in the work list. In
  10240. each iteration, a node is popped from the work list and processed. The
  10241. \code{input} for the node is computed by taking the join of the
  10242. abstract states of all the predecessor nodes. The \code{transfer}
  10243. function is then applied to obtain the \code{output} abstract
  10244. state. If the output differs from the previous state for this block,
  10245. the mapping for this block is updated and its successor nodes are
  10246. pushed onto the work list.
  10247. \begin{figure}[tb]
  10248. \begin{lstlisting}
  10249. (define (analyze-dataflow G transfer bottom join)
  10250. (define mapping (make-hash))
  10251. (for ([v (in-vertices G)])
  10252. (dict-set! mapping v bottom))
  10253. (define worklist (make-queue))
  10254. (for ([v (in-vertices G)])
  10255. (enqueue! worklist v))
  10256. (define trans-G (transpose G))
  10257. (while (not (queue-empty? worklist))
  10258. (define node (dequeue! worklist))
  10259. (define input (for/fold ([state bottom])
  10260. ([pred (in-neighbors trans-G node)])
  10261. (join state (dict-ref mapping pred))))
  10262. (define output (transfer node input))
  10263. (cond [(not (equal? output (dict-ref mapping node)))
  10264. (dict-set! mapping node output)
  10265. (for ([v (in-neighbors G node)])
  10266. (enqueue! worklist v))]))
  10267. mapping)
  10268. \end{lstlisting}
  10269. \caption{Generic work list algorithm for dataflow analysis}
  10270. \label{fig:generic-dataflow}
  10271. \end{figure}
  10272. Having discussed the two complications that arise from adding support
  10273. for assignment and loops, we turn to discussing the one new compiler
  10274. pass and the significant changes to existing passes.
  10275. \section{Convert Assignments}
  10276. \label{sec:convert-assignments}
  10277. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10278. the combination of assignments and lexically-scoped functions requires
  10279. that we box those variables that are both assigned-to and that appear
  10280. free inside a \code{lambda}. The purpose of the
  10281. \code{convert-assignments} pass is to carry out that transformation.
  10282. We recommend placing this pass after \code{uniquify} but before
  10283. \code{reveal-functions}.
  10284. Consider again the first example from
  10285. Section~\ref{sec:assignment-scoping}:
  10286. \begin{lstlisting}
  10287. (let ([x 0])
  10288. (let ([y 0])
  10289. (let ([z 20])
  10290. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10291. (begin
  10292. (set! x 10)
  10293. (set! y 12)
  10294. (f y))))))
  10295. \end{lstlisting}
  10296. The variables \code{x} and \code{y} are assigned-to. The variables
  10297. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10298. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10299. The boxing of \code{x} consists of three transformations: initialize
  10300. \code{x} with a vector, replace reads from \code{x} with
  10301. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10302. \code{vector-set!}. The output of \code{convert-assignments} for this
  10303. example is as follows.
  10304. \begin{lstlisting}
  10305. (define (main) : Integer
  10306. (let ([x0 (vector 0)])
  10307. (let ([y1 0])
  10308. (let ([z2 20])
  10309. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10310. (+ a3 (+ (vector-ref x0 0) z2)))])
  10311. (begin
  10312. (vector-set! x0 0 10)
  10313. (set! y1 12)
  10314. (f4 y1)))))))
  10315. \end{lstlisting}
  10316. \paragraph{Assigned \& Free}
  10317. We recommend defining an auxiliary function named
  10318. \code{assigned\&free} that takes an expression and simultaneously
  10319. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10320. that occur free within lambda's, and 3) a new version of the
  10321. expression that records which bound variables occurred in the
  10322. intersection of $A$ and $F$. You can use the struct
  10323. \code{AssignedFree} to do this. Consider the case for
  10324. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10325. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10326. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10327. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10328. \begin{lstlisting}
  10329. (Let |$x$| |$rhs$| |$body$|)
  10330. |$\Rightarrow$|
  10331. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10332. \end{lstlisting}
  10333. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10334. The set of assigned variables for this \code{Let} is
  10335. $A_r \cup (A_b - \{x\})$
  10336. and the set of variables free in lambda's is
  10337. $F_r \cup (F_b - \{x\})$.
  10338. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10339. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10340. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10341. and $F_r$.
  10342. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10343. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10344. recursively processing \itm{body}. Wrap each of parameter that occurs
  10345. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10346. Let $P$ be the set of parameter names in \itm{params}. The result is
  10347. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10348. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10349. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10350. \paragraph{Convert Assignments}
  10351. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10352. functions for expressions and definitions. The function for
  10353. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10354. set of assigned-and-free variables (obtained from the result of
  10355. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10356. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10357. \code{vector-ref}.
  10358. \begin{lstlisting}
  10359. (Var |$x$|)
  10360. |$\Rightarrow$|
  10361. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10362. \end{lstlisting}
  10363. %
  10364. In the case for $\LET{\LP\code{AssignedFree}\,
  10365. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10366. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10367. \itm{body'} but with $x$ added to the set of assigned-and-free
  10368. variables. Translate the let-expression as follows to bind $x$ to a
  10369. boxed value.
  10370. \begin{lstlisting}
  10371. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10372. |$\Rightarrow$|
  10373. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10374. \end{lstlisting}
  10375. %
  10376. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10377. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10378. variables, translate the \code{set!} into a \code{vector-set!}
  10379. as follows.
  10380. \begin{lstlisting}
  10381. (SetBang |$x$| |$\itm{rhs}$|)
  10382. |$\Rightarrow$|
  10383. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10384. \end{lstlisting}
  10385. %
  10386. The case for \code{Lambda} is non-trivial, but it is similar to the
  10387. case for function definitions, which we discuss next.
  10388. The auxiliary function for definitions, \code{cnvt-assign-def},
  10389. applies assignment conversion to function definitions.
  10390. We translate a function definition as follows.
  10391. \begin{lstlisting}
  10392. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10393. |$\Rightarrow$|
  10394. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10395. \end{lstlisting}
  10396. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10397. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10398. \code{assigned\&free} on $\itm{body_1}$.
  10399. Let $P$ be the parameter names in \itm{params}.
  10400. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10401. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10402. as the set of assigned-and-free variables.
  10403. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10404. in a sequence of let-expressions that box the parameters
  10405. that are in $A_b \cap F_b$.
  10406. %
  10407. Regarding \itm{params'}, change the names of the parameters that are
  10408. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10409. variables can retain the original names). Recall the second example in
  10410. Section~\ref{sec:assignment-scoping} involving a counter
  10411. abstraction. The following is the output of assignment version for
  10412. function \code{f}.
  10413. \begin{lstlisting}
  10414. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10415. (vector
  10416. (lambda: () : Integer x1)
  10417. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10418. |$\Rightarrow$|
  10419. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10420. (let ([x1 (vector param_x1)])
  10421. (vector (lambda: () : Integer (vector-ref x1 0))
  10422. (lambda: () : Void
  10423. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10424. \end{lstlisting}
  10425. \section{Remove Complex Operands}
  10426. \label{sec:rco-loop}
  10427. The three new language forms, \code{while}, \code{set!}, and
  10428. \code{begin} are all complex expressions and their subexpressions are
  10429. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10430. output language \LangFunANF{} of this pass.
  10431. \begin{figure}[tp]
  10432. \centering
  10433. \fbox{
  10434. \begin{minipage}{0.96\textwidth}
  10435. \small
  10436. \[
  10437. \begin{array}{rcl}
  10438. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10439. \mid \VOID{} } \\
  10440. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10441. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10442. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10443. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10444. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10445. \end{array}
  10446. \]
  10447. \end{minipage}
  10448. }
  10449. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10450. \label{fig:Rwhile-anf-syntax}
  10451. \end{figure}
  10452. As usual, when a complex expression appears in a grammar position that
  10453. needs to be atomic, such as the argument of a primitive operator, we
  10454. must introduce a temporary variable and bind it to the complex
  10455. expression. This approach applies, unchanged, to handle the new
  10456. language forms. For example, in the following code there are two
  10457. \code{begin} expressions appearing as arguments to \code{+}. The
  10458. output of \code{rco-exp} is shown below, in which the \code{begin}
  10459. expressions have been bound to temporary variables. Recall that
  10460. \code{let} expressions in \LangLoopANF{} are allowed to have
  10461. arbitrary expressions in their right-hand-side expression, so it is
  10462. fine to place \code{begin} there.
  10463. \begin{lstlisting}
  10464. (let ([x0 10])
  10465. (let ([y1 0])
  10466. (+ (+ (begin (set! y1 (read)) x0)
  10467. (begin (set! x0 (read)) y1))
  10468. x0)))
  10469. |$\Rightarrow$|
  10470. (let ([x0 10])
  10471. (let ([y1 0])
  10472. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10473. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10474. (let ([tmp4 (+ tmp2 tmp3)])
  10475. (+ tmp4 x0))))))
  10476. \end{lstlisting}
  10477. \section{Explicate Control and \LangCLoop{}}
  10478. \label{sec:explicate-loop}
  10479. Recall that in the \code{explicate-control} pass we define one helper
  10480. function for each kind of position in the program. For the \LangVar{}
  10481. language of integers and variables we needed kinds of positions:
  10482. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10483. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10484. yet another kind of position: effect position. Except for the last
  10485. subexpression, the subexpressions inside a \code{begin} are evaluated
  10486. only for their effect. Their result values are discarded. We can
  10487. generate better code by taking this fact into account.
  10488. The output language of \code{explicate-control} is \LangCLoop{}
  10489. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10490. \LangCLam{}. The only syntactic difference is that \code{Call},
  10491. \code{vector-set!}, and \code{read} may also appear as statements.
  10492. The most significant difference between \LangCLam{} and \LangCLoop{}
  10493. is that the control-flow graphs of the later may contain cycles.
  10494. \begin{figure}[tp]
  10495. \fbox{
  10496. \begin{minipage}{0.96\textwidth}
  10497. \small
  10498. \[
  10499. \begin{array}{lcl}
  10500. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10501. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10502. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10503. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10504. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10505. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10506. \end{array}
  10507. \]
  10508. \end{minipage}
  10509. }
  10510. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10511. \label{fig:c7-syntax}
  10512. \end{figure}
  10513. The new auxiliary function \code{explicate-effect} takes an expression
  10514. (in an effect position) and a promise of a continuation block. The
  10515. function returns a promise for a $\Tail$ that includes the generated
  10516. code for the input expression followed by the continuation block. If
  10517. the expression is obviously pure, that is, never causes side effects,
  10518. then the expression can be removed, so the result is just the
  10519. continuation block.
  10520. %
  10521. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10522. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10523. the loop. Recursively process the \itm{body} (in effect position)
  10524. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10525. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10526. \itm{body'} as the then-branch and the continuation block as the
  10527. else-branch. The result should be added to the control-flow graph with
  10528. the label \itm{loop}. The result for the whole \code{while} loop is a
  10529. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10530. added to the control-flow graph if the loop is indeed used, which can
  10531. be accomplished using \code{delay}.
  10532. The auxiliary functions for tail, assignment, and predicate positions
  10533. need to be updated. The three new language forms, \code{while},
  10534. \code{set!}, and \code{begin}, can appear in assignment and tail
  10535. positions. Only \code{begin} may appear in predicate positions; the
  10536. other two have result type \code{Void}.
  10537. \section{Select Instructions}
  10538. \label{sec:select-instructions-loop}
  10539. Only three small additions are needed in the
  10540. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10541. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10542. stand-alone statements instead of only appearing on the right-hand
  10543. side of an assignment statement. The code generation is nearly
  10544. identical; just leave off the instruction for moving the result into
  10545. the left-hand side.
  10546. \section{Register Allocation}
  10547. \label{sec:register-allocation-loop}
  10548. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10549. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10550. which complicates the liveness analysis needed for register
  10551. allocation.
  10552. \subsection{Liveness Analysis}
  10553. \label{sec:liveness-analysis-r8}
  10554. We recommend using the generic \code{analyze-dataflow} function that
  10555. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10556. perform liveness analysis, replacing the code in
  10557. \code{uncover-live-CFG} that processed the basic blocks in topological
  10558. order (Section~\ref{sec:liveness-analysis-Rif}).
  10559. The \code{analyze-dataflow} function has four parameters.
  10560. \begin{enumerate}
  10561. \item The first parameter \code{G} should be a directed graph from the
  10562. \code{racket/graph} package (see the sidebar in
  10563. Section~\ref{sec:build-interference}) that represents the
  10564. control-flow graph.
  10565. \item The second parameter \code{transfer} is a function that applies
  10566. liveness analysis to a basic block. It takes two parameters: the
  10567. label for the block to analyze and the live-after set for that
  10568. block. The transfer function should return the live-before set for
  10569. the block. Also, as a side-effect, it should update the block's
  10570. $\itm{info}$ with the liveness information for each instruction. To
  10571. implement the \code{transfer} function, you should be able to reuse
  10572. the code you already have for analyzing basic blocks.
  10573. \item The third and fourth parameters of \code{analyze-dataflow} are
  10574. \code{bottom} and \code{join} for the lattice of abstract states,
  10575. i.e. sets of locations. The bottom of the lattice is the empty set
  10576. \code{(set)} and the join operator is \code{set-union}.
  10577. \end{enumerate}
  10578. \begin{figure}[p]
  10579. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10580. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10581. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10582. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10583. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10584. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10585. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10586. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10587. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10588. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10589. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10590. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10591. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10592. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10593. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10594. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10595. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10596. %% \path[->,bend left=15] (Rfun) edge [above] node
  10597. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10598. \path[->,bend left=15] (Rfun) edge [above] node
  10599. {\ttfamily\footnotesize shrink} (Rfun-2);
  10600. \path[->,bend left=15] (Rfun-2) edge [above] node
  10601. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10602. \path[->,bend left=15] (Rfun-3) edge [above] node
  10603. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10604. \path[->,bend left=15] (Rfun-4) edge [right] node
  10605. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10606. \path[->,bend left=15] (F1-1) edge [below] node
  10607. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10608. \path[->,bend right=15] (F1-2) edge [above] node
  10609. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10610. \path[->,bend right=15] (F1-3) edge [above] node
  10611. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10612. \path[->,bend right=15] (F1-4) edge [above] node
  10613. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10614. \path[->,bend right=15] (F1-5) edge [right] node
  10615. {\ttfamily\footnotesize explicate-control} (C3-2);
  10616. \path[->,bend left=15] (C3-2) edge [left] node
  10617. {\ttfamily\footnotesize select-instr.} (x86-2);
  10618. \path[->,bend right=15] (x86-2) edge [left] node
  10619. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10620. \path[->,bend right=15] (x86-2-1) edge [below] node
  10621. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10622. \path[->,bend right=15] (x86-2-2) edge [left] node
  10623. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10624. \path[->,bend left=15] (x86-3) edge [above] node
  10625. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10626. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10627. \end{tikzpicture}
  10628. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10629. \label{fig:Rwhile-passes}
  10630. \end{figure}
  10631. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10632. for the compilation of \LangLoop{}.
  10633. \section{Challenge: Arrays}
  10634. \label{sec:arrays}
  10635. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10636. elements whose length is determined at compile-time and where each
  10637. element of a tuple may have a different type (they are
  10638. heterogeous). This challenge is also about sequences, but this time
  10639. the length is determined at run-time and all the elements have the same
  10640. type (they are homogeneous). We use the term ``array'' for this later
  10641. kind of sequence.
  10642. The Racket language does not distinguish between tuples and arrays,
  10643. they are both represented by vectors. However, Typed Racket
  10644. distinguishes between tuples and arrays: the \code{Vector} type is for
  10645. tuples and the \code{Vectorof} type is for arrays.
  10646. %
  10647. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10648. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10649. and the \code{make-vector} primitive operator for creating an array,
  10650. whose arguments are the length of the array and an initial value for
  10651. all the elements in the array. The \code{vector-length},
  10652. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10653. for tuples become overloaded for use with arrays.
  10654. %
  10655. We also include integer multiplication in \LangArray{}, as it is
  10656. useful in many examples involving arrays such as computing the
  10657. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10658. \begin{figure}[tp]
  10659. \centering
  10660. \fbox{
  10661. \begin{minipage}{0.96\textwidth}
  10662. \small
  10663. \[
  10664. \begin{array}{lcl}
  10665. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10666. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10667. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10668. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10669. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10670. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10671. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10672. \mid \LP\key{not}\;\Exp\RP } \\
  10673. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10674. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10675. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10676. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10677. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10678. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10679. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10680. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10681. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10682. \mid \CWHILE{\Exp}{\Exp} } \\
  10683. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10684. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10685. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10686. \end{array}
  10687. \]
  10688. \end{minipage}
  10689. }
  10690. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10691. \label{fig:Rvecof-concrete-syntax}
  10692. \end{figure}
  10693. \begin{figure}[tp]
  10694. \begin{lstlisting}
  10695. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10696. [n : Integer]) : Integer
  10697. (let ([i 0])
  10698. (let ([prod 0])
  10699. (begin
  10700. (while (< i n)
  10701. (begin
  10702. (set! prod (+ prod (* (vector-ref A i)
  10703. (vector-ref B i))))
  10704. (set! i (+ i 1))
  10705. ))
  10706. prod))))
  10707. (let ([A (make-vector 2 2)])
  10708. (let ([B (make-vector 2 3)])
  10709. (+ (inner-product A B 2)
  10710. 30)))
  10711. \end{lstlisting}
  10712. \caption{Example program that computes the inner-product.}
  10713. \label{fig:inner-product}
  10714. \end{figure}
  10715. The type checker for \LangArray{} is define in
  10716. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10717. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10718. of the intializing expression. The length expression is required to
  10719. have type \code{Integer}. The type checking of the operators
  10720. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10721. updated to handle the situation where the vector has type
  10722. \code{Vectorof}. In these cases we translate the operators to their
  10723. \code{vectorof} form so that later passes can easily distinguish
  10724. between operations on tuples versus arrays. We override the
  10725. \code{operator-types} method to provide the type signature for
  10726. multiplication: it takes two integers and returns an integer. To
  10727. support injection and projection of arrays to the \code{Any} type
  10728. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10729. predicate.
  10730. \begin{figure}[tbp]
  10731. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10732. (define type-check-Rvecof-class
  10733. (class type-check-Rwhile-class
  10734. (super-new)
  10735. (inherit check-type-equal?)
  10736. (define/override (flat-ty? ty)
  10737. (match ty
  10738. ['(Vectorof Any) #t]
  10739. [else (super flat-ty? ty)]))
  10740. (define/override (operator-types)
  10741. (append '((* . ((Integer Integer) . Integer)))
  10742. (super operator-types)))
  10743. (define/override (type-check-exp env)
  10744. (lambda (e)
  10745. (define recur (type-check-exp env))
  10746. (match e
  10747. [(Prim 'make-vector (list e1 e2))
  10748. (define-values (e1^ t1) (recur e1))
  10749. (define-values (e2^ elt-type) (recur e2))
  10750. (define vec-type `(Vectorof ,elt-type))
  10751. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10752. vec-type)]
  10753. [(Prim 'vector-ref (list e1 e2))
  10754. (define-values (e1^ t1) (recur e1))
  10755. (define-values (e2^ t2) (recur e2))
  10756. (match* (t1 t2)
  10757. [(`(Vectorof ,elt-type) 'Integer)
  10758. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10759. [(other wise) ((super type-check-exp env) e)])]
  10760. [(Prim 'vector-set! (list e1 e2 e3) )
  10761. (define-values (e-vec t-vec) (recur e1))
  10762. (define-values (e2^ t2) (recur e2))
  10763. (define-values (e-arg^ t-arg) (recur e3))
  10764. (match t-vec
  10765. [`(Vectorof ,elt-type)
  10766. (check-type-equal? elt-type t-arg e)
  10767. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10768. [else ((super type-check-exp env) e)])]
  10769. [(Prim 'vector-length (list e1))
  10770. (define-values (e1^ t1) (recur e1))
  10771. (match t1
  10772. [`(Vectorof ,t)
  10773. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10774. [else ((super type-check-exp env) e)])]
  10775. [else ((super type-check-exp env) e)])))
  10776. ))
  10777. (define (type-check-Rvecof p)
  10778. (send (new type-check-Rvecof-class) type-check-program p))
  10779. \end{lstlisting}
  10780. \caption{Type checker for the \LangArray{} language.}
  10781. \label{fig:type-check-Rvecof}
  10782. \end{figure}
  10783. The interpreter for \LangArray{} is defined in
  10784. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10785. implemented with Racket's \code{make-vector} function and
  10786. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10787. integers.
  10788. \begin{figure}[tbp]
  10789. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10790. (define interp-Rvecof-class
  10791. (class interp-Rwhile-class
  10792. (super-new)
  10793. (define/override (interp-op op)
  10794. (verbose "Rvecof/interp-op" op)
  10795. (match op
  10796. ['make-vector make-vector]
  10797. ['* fx*]
  10798. [else (super interp-op op)]))
  10799. ))
  10800. (define (interp-Rvecof p)
  10801. (send (new interp-Rvecof-class) interp-program p))
  10802. \end{lstlisting}
  10803. \caption{Interpreter for \LangArray{}.}
  10804. \label{fig:interp-Rvecof}
  10805. \end{figure}
  10806. \subsection{Data Representation}
  10807. \label{sec:array-rep}
  10808. Just like tuples, we store arrays on the heap which means that the
  10809. garbage collector will need to inspect arrays. An immediate thought is
  10810. to use the same representation for arrays that we use for tuples.
  10811. However, we limit tuples to a length of $50$ so that their length and
  10812. pointer mask can fit into the 64-bit tag at the beginning of each
  10813. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10814. millions of elements, so we need more bits to store the length.
  10815. However, because arrays are homogeneous, we only need $1$ bit for the
  10816. pointer mask instead of one bit per array elements. Finally, the
  10817. garbage collector will need to be able to distinguish between tuples
  10818. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10819. arrive at the following layout for the 64-bit tag at the beginning of
  10820. an array:
  10821. \begin{itemize}
  10822. \item The right-most bit is the forwarding bit, just like in a tuple.
  10823. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10824. it is not.
  10825. \item The next bit to the left is the pointer mask. A $0$ indicates
  10826. that none of the elements are pointers to the heap and a $1$
  10827. indicates that all of the elements are pointers.
  10828. \item The next $61$ bits store the length of the array.
  10829. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10830. array ($1$).
  10831. \end{itemize}
  10832. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10833. differentiate the kinds of values that have been injected into the
  10834. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10835. to indicate that the value is an array.
  10836. In the following subsections we provide hints regarding how to update
  10837. the passes to handle arrays.
  10838. \subsection{Reveal Casts}
  10839. The array-access operators \code{vectorof-ref} and
  10840. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10841. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10842. that the type checker cannot tell whether the index will be in bounds,
  10843. so the bounds check must be performed at run time. Recall that the
  10844. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10845. an \code{If} arround a vector reference for update to check whether
  10846. the index is less than the length. You should do the same for
  10847. \code{vectorof-ref} and \code{vectorof-set!} .
  10848. In addition, the handling of the \code{any-vector} operators in
  10849. \code{reveal-casts} needs to be updated to account for arrays that are
  10850. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10851. generated code should test whether the tag is for tuples (\code{010})
  10852. or arrays (\code{110}) and then dispatch to either
  10853. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10854. we add a case in \code{select-instructions} to generate the
  10855. appropriate instructions for accessing the array length from the
  10856. header of an array.
  10857. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10858. the generated code needs to check that the index is less than the
  10859. vector length, so like the code for \code{any-vector-length}, check
  10860. the tag to determine whether to use \code{any-vector-length} or
  10861. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10862. is complete, the generated code can use \code{any-vector-ref} and
  10863. \code{any-vector-set!} for both tuples and arrays because the
  10864. instructions used for those operators do not look at the tag at the
  10865. front of the tuple or array.
  10866. \subsection{Expose Allocation}
  10867. This pass should translate the \code{make-vector} operator into
  10868. lower-level operations. In particular, the new AST node
  10869. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10870. length specified by the $\Exp$, but does not initialize the elements
  10871. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10872. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10873. element type for the array. Regarding the initialization of the array,
  10874. we recommend generated a \code{while} loop that uses
  10875. \code{vector-set!} to put the initializing value into every element of
  10876. the array.
  10877. \subsection{Remove Complex Operands}
  10878. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10879. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10880. complex and its subexpression must be atomic.
  10881. \subsection{Explicate Control}
  10882. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10883. \code{explicate-assign}.
  10884. \subsection{Select Instructions}
  10885. Generate instructions for \code{AllocateArray} similar to those for
  10886. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10887. that the tag at the front of the array should instead use the
  10888. representation discussed in Section~\ref{sec:array-rep}.
  10889. Regarding \code{vectorof-length}, extract the length from the tag
  10890. according to the representation discussed in
  10891. Section~\ref{sec:array-rep}.
  10892. The instructions generated for \code{vectorof-ref} differ from those
  10893. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10894. that the index is not a constant so the offset must be computed at
  10895. runtime, similar to the instructions generated for
  10896. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10897. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10898. appear in an assignment and as a stand-alone statement, so make sure
  10899. to handle both situations in this pass.
  10900. Finally, the instructions for \code{any-vectorof-length} should be
  10901. similar to those for \code{vectorof-length}, except that one must
  10902. first project the array by writing zeroes into the $3$-bit tag
  10903. \begin{exercise}\normalfont
  10904. Implement a compiler for the \LangArray{} language by extending your
  10905. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10906. programs, including the one in Figure~\ref{fig:inner-product} and also
  10907. a program that multiplies two matrices. Note that matrices are
  10908. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10909. arrays by laying out each row in the array, one after the next.
  10910. \end{exercise}
  10911. % Further Reading: dataflow analysis
  10912. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10913. \chapter{Gradual Typing}
  10914. \label{ch:Rgrad}
  10915. \index{subject}{gradual typing}
  10916. This chapter studies a language, \LangGrad{}, in which the programmer
  10917. can choose between static and dynamic type checking in different parts
  10918. of a program, thereby mixing the statically typed \LangLoop{} language
  10919. with the dynamically typed \LangDyn{}. There are several approaches to
  10920. mixing static and dynamic typing, including multi-language
  10921. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10922. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10923. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  10924. programmer controls the amount of static versus dynamic checking by
  10925. adding or removing type annotations on parameters and
  10926. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10927. %
  10928. The concrete syntax of \LangGrad{} is defined in
  10929. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10930. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10931. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10932. non-terminals that make type annotations optional. The return types
  10933. are not optional in the abstract syntax; the parser fills in
  10934. \code{Any} when the return type is not specified in the concrete
  10935. syntax.
  10936. \begin{figure}[tp]
  10937. \centering
  10938. \fbox{
  10939. \begin{minipage}{0.96\textwidth}
  10940. \small
  10941. \[
  10942. \begin{array}{lcl}
  10943. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10944. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10945. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10946. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10947. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10948. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10949. \mid (\key{and}\;\Exp\;\Exp)
  10950. \mid (\key{or}\;\Exp\;\Exp)
  10951. \mid (\key{not}\;\Exp) } \\
  10952. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10953. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10954. (\key{vector-ref}\;\Exp\;\Int)} \\
  10955. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10956. \mid (\Exp \; \Exp\ldots) } \\
  10957. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10958. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10959. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10960. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10961. \mid \CWHILE{\Exp}{\Exp} } \\
  10962. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10963. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  10964. \end{array}
  10965. \]
  10966. \end{minipage}
  10967. }
  10968. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10969. \label{fig:Rgrad-concrete-syntax}
  10970. \end{figure}
  10971. \begin{figure}[tp]
  10972. \centering
  10973. \fbox{
  10974. \begin{minipage}{0.96\textwidth}
  10975. \small
  10976. \[
  10977. \begin{array}{lcl}
  10978. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10979. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10980. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10981. &\mid& \gray{ \BOOL{\itm{bool}}
  10982. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10983. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10984. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10985. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10986. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10987. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10988. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10989. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10990. \end{array}
  10991. \]
  10992. \end{minipage}
  10993. }
  10994. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10995. \label{fig:Rgrad-syntax}
  10996. \end{figure}
  10997. Both the type checker and the interpreter for \LangGrad{} require some
  10998. interesting changes to enable gradual typing, which we discuss in the
  10999. next two sections in the context of the \code{map-vec} example from
  11000. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  11001. revised the \code{map-vec} example, omitting the type annotations from
  11002. the \code{add1} function.
  11003. \begin{figure}[btp]
  11004. % gradual_test_9.rkt
  11005. \begin{lstlisting}
  11006. (define (map-vec [f : (Integer -> Integer)]
  11007. [v : (Vector Integer Integer)])
  11008. : (Vector Integer Integer)
  11009. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11010. (define (add1 x) (+ x 1))
  11011. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11012. \end{lstlisting}
  11013. \caption{A partially-typed version of the \code{map-vec} example.}
  11014. \label{fig:gradual-map-vec}
  11015. \end{figure}
  11016. \section{Type Checking \LangGrad{} and \LangCast{}}
  11017. \label{sec:gradual-type-check}
  11018. The type checker for \LangGrad{} uses the \code{Any} type for missing
  11019. parameter and return types. For example, the \code{x} parameter of
  11020. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  11021. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  11022. consider the \code{+} operator inside \code{add1}. It expects both
  11023. arguments to have type \code{Integer}, but its first argument \code{x}
  11024. has type \code{Any}. In a gradually typed language, such differences
  11025. are allowed so long as the types are \emph{consistent}, that is, they
  11026. are equal except in places where there is an \code{Any} type. The type
  11027. \code{Any} is consistent with every other type.
  11028. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  11029. \begin{figure}[tbp]
  11030. \begin{lstlisting}
  11031. (define/public (consistent? t1 t2)
  11032. (match* (t1 t2)
  11033. [('Integer 'Integer) #t]
  11034. [('Boolean 'Boolean) #t]
  11035. [('Void 'Void) #t]
  11036. [('Any t2) #t]
  11037. [(t1 'Any) #t]
  11038. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11039. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  11040. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11041. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  11042. (consistent? rt1 rt2))]
  11043. [(other wise) #f]))
  11044. \end{lstlisting}
  11045. \caption{The consistency predicate on types.}
  11046. \label{fig:consistent}
  11047. \end{figure}
  11048. Returning to the \code{map-vec} example of
  11049. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  11050. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  11051. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  11052. because the two types are consistent. In particular, \code{->} is
  11053. equal to \code{->} and because \code{Any} is consistent with
  11054. \code{Integer}.
  11055. Next consider a program with an error, such as applying the
  11056. \code{map-vec} to a function that sometimes returns a Boolean, as
  11057. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  11058. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  11059. consistent with the type of parameter \code{f} of \code{map-vec}, that
  11060. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  11061. Integer)}. One might say that a gradual type checker is optimistic
  11062. in that it accepts programs that might execute without a runtime type
  11063. error.
  11064. %
  11065. Unfortunately, running this program with input \code{1} triggers an
  11066. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  11067. performs checking at runtime to ensure the integrity of the static
  11068. types, such as the \code{(Integer -> Integer)} annotation on parameter
  11069. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  11070. new \code{Cast} form that is inserted by the type checker. Thus, the
  11071. output of the type checker is a program in the \LangCast{} language, which
  11072. adds \code{Cast} to \LangLoop{}, as shown in
  11073. Figure~\ref{fig:Rgrad-prime-syntax}.
  11074. \begin{figure}[tp]
  11075. \centering
  11076. \fbox{
  11077. \begin{minipage}{0.96\textwidth}
  11078. \small
  11079. \[
  11080. \begin{array}{lcl}
  11081. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  11082. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11083. \end{array}
  11084. \]
  11085. \end{minipage}
  11086. }
  11087. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11088. \label{fig:Rgrad-prime-syntax}
  11089. \end{figure}
  11090. \begin{figure}[tbp]
  11091. \begin{lstlisting}
  11092. (define (map-vec [f : (Integer -> Integer)]
  11093. [v : (Vector Integer Integer)])
  11094. : (Vector Integer Integer)
  11095. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11096. (define (add1 x) (+ x 1))
  11097. (define (true) #t)
  11098. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  11099. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  11100. \end{lstlisting}
  11101. \caption{A variant of the \code{map-vec} example with an error.}
  11102. \label{fig:map-vec-maybe-add1}
  11103. \end{figure}
  11104. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  11105. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  11106. inserted every time the type checker sees two types that are
  11107. consistent but not equal. In the \code{add1} function, \code{x} is
  11108. cast to \code{Integer} and the result of the \code{+} is cast to
  11109. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  11110. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  11111. \begin{figure}[btp]
  11112. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11113. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  11114. : (Vector Integer Integer)
  11115. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11116. (define (add1 [x : Any]) : Any
  11117. (cast (+ (cast x Any Integer) 1) Integer Any))
  11118. (define (true) : Any (cast #t Boolean Any))
  11119. (define (maybe-add1 [x : Any]) : Any
  11120. (if (eq? 0 (read)) (add1 x) (true)))
  11121. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  11122. (vector 0 41)) 0)
  11123. \end{lstlisting}
  11124. \caption{Output of type checking \code{map-vec}
  11125. and \code{maybe-add1}.}
  11126. \label{fig:map-vec-cast}
  11127. \end{figure}
  11128. The type checker for \LangGrad{} is defined in
  11129. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  11130. and \ref{fig:type-check-Rgradual-3}.
  11131. \begin{figure}[tbp]
  11132. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11133. (define type-check-gradual-class
  11134. (class type-check-Rwhile-class
  11135. (super-new)
  11136. (inherit operator-types type-predicates)
  11137. (define/override (type-check-exp env)
  11138. (lambda (e)
  11139. (define recur (type-check-exp env))
  11140. (match e
  11141. [(Prim 'vector-length (list e1))
  11142. (define-values (e1^ t) (recur e1))
  11143. (match t
  11144. [`(Vector ,ts ...)
  11145. (values (Prim 'vector-length (list e1^)) 'Integer)]
  11146. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  11147. [(Prim 'vector-ref (list e1 e2))
  11148. (define-values (e1^ t1) (recur e1))
  11149. (define-values (e2^ t2) (recur e2))
  11150. (check-consistent? t2 'Integer e)
  11151. (match t1
  11152. [`(Vector ,ts ...)
  11153. (match e2^
  11154. [(Int i)
  11155. (unless (and (0 . <= . i) (i . < . (length ts)))
  11156. (error 'type-check "invalid index ~a in ~a" i e))
  11157. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11158. [else (define e1^^ (make-cast e1^ t1 'Any))
  11159. (define e2^^ (make-cast e2^ t2 'Integer))
  11160. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  11161. ['Any
  11162. (define e2^^ (make-cast e2^ t2 'Integer))
  11163. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  11164. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11165. [(Prim 'vector-set! (list e1 e2 e3) )
  11166. (define-values (e1^ t1) (recur e1))
  11167. (define-values (e2^ t2) (recur e2))
  11168. (define-values (e3^ t3) (recur e3))
  11169. (check-consistent? t2 'Integer e)
  11170. (match t1
  11171. [`(Vector ,ts ...)
  11172. (match e2^
  11173. [(Int i)
  11174. (unless (and (0 . <= . i) (i . < . (length ts)))
  11175. (error 'type-check "invalid index ~a in ~a" i e))
  11176. (check-consistent? (list-ref ts i) t3 e)
  11177. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  11178. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  11179. [else
  11180. (define e1^^ (make-cast e1^ t1 'Any))
  11181. (define e2^^ (make-cast e2^ t2 'Integer))
  11182. (define e3^^ (make-cast e3^ t3 'Any))
  11183. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  11184. ['Any
  11185. (define e2^^ (make-cast e2^ t2 'Integer))
  11186. (define e3^^ (make-cast e3^ t3 'Any))
  11187. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  11188. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11189. \end{lstlisting}
  11190. \caption{Type checker for the \LangGrad{} language, part 1.}
  11191. \label{fig:type-check-Rgradual-1}
  11192. \end{figure}
  11193. \begin{figure}[tbp]
  11194. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11195. [(Prim 'eq? (list e1 e2))
  11196. (define-values (e1^ t1) (recur e1))
  11197. (define-values (e2^ t2) (recur e2))
  11198. (check-consistent? t1 t2 e)
  11199. (define T (meet t1 t2))
  11200. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  11201. 'Boolean)]
  11202. [(Prim 'not (list e1))
  11203. (define-values (e1^ t1) (recur e1))
  11204. (match t1
  11205. ['Any
  11206. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  11207. (Bool #t) (Bool #f)))]
  11208. [else
  11209. (define-values (t-ret new-es^)
  11210. (type-check-op 'not (list t1) (list e1^) e))
  11211. (values (Prim 'not new-es^) t-ret)])]
  11212. [(Prim 'and (list e1 e2))
  11213. (recur (If e1 e2 (Bool #f)))]
  11214. [(Prim 'or (list e1 e2))
  11215. (define tmp (gensym 'tmp))
  11216. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  11217. [(Prim op es)
  11218. #:when (not (set-member? explicit-prim-ops op))
  11219. (define-values (new-es ts)
  11220. (for/lists (exprs types) ([e es])
  11221. (recur e)))
  11222. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  11223. (values (Prim op new-es^) t-ret)]
  11224. [(If e1 e2 e3)
  11225. (define-values (e1^ T1) (recur e1))
  11226. (define-values (e2^ T2) (recur e2))
  11227. (define-values (e3^ T3) (recur e3))
  11228. (check-consistent? T2 T3 e)
  11229. (match T1
  11230. ['Boolean
  11231. (define Tif (join T2 T3))
  11232. (values (If e1^ (make-cast e2^ T2 Tif)
  11233. (make-cast e3^ T3 Tif)) Tif)]
  11234. ['Any
  11235. (define Tif (meet T2 T3))
  11236. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  11237. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  11238. Tif)]
  11239. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  11240. [(HasType e1 T)
  11241. (define-values (e1^ T1) (recur e1))
  11242. (check-consistent? T1 T)
  11243. (values (make-cast e1^ T1 T) T)]
  11244. [(SetBang x e1)
  11245. (define-values (e1^ T1) (recur e1))
  11246. (define varT (dict-ref env x))
  11247. (check-consistent? T1 varT e)
  11248. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  11249. [(WhileLoop e1 e2)
  11250. (define-values (e1^ T1) (recur e1))
  11251. (check-consistent? T1 'Boolean e)
  11252. (define-values (e2^ T2) ((type-check-exp env) e2))
  11253. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  11254. \end{lstlisting}
  11255. \caption{Type checker for the \LangGrad{} language, part 2.}
  11256. \label{fig:type-check-Rgradual-2}
  11257. \end{figure}
  11258. \begin{figure}[tbp]
  11259. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11260. [(Apply e1 e2s)
  11261. (define-values (e1^ T1) (recur e1))
  11262. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  11263. (match T1
  11264. [`(,T1ps ... -> ,T1rt)
  11265. (for ([T2 T2s] [Tp T1ps])
  11266. (check-consistent? T2 Tp e))
  11267. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  11268. (make-cast e2 src tgt)))
  11269. (values (Apply e1^ e2s^^) T1rt)]
  11270. [`Any
  11271. (define e1^^ (make-cast e1^ 'Any
  11272. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  11273. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  11274. (make-cast e2 src 'Any)))
  11275. (values (Apply e1^^ e2s^^) 'Any)]
  11276. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11277. [(Lambda params Tr e1)
  11278. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11279. (match p
  11280. [`[,x : ,T] (values x T)]
  11281. [(? symbol? x) (values x 'Any)])))
  11282. (define-values (e1^ T1)
  11283. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11284. (check-consistent? Tr T1 e)
  11285. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11286. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11287. [else ((super type-check-exp env) e)]
  11288. )))
  11289. \end{lstlisting}
  11290. \caption{Type checker for the \LangGrad{} language, part 3.}
  11291. \label{fig:type-check-Rgradual-3}
  11292. \end{figure}
  11293. \begin{figure}[tbp]
  11294. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11295. (define/public (join t1 t2)
  11296. (match* (t1 t2)
  11297. [('Integer 'Integer) 'Integer]
  11298. [('Boolean 'Boolean) 'Boolean]
  11299. [('Void 'Void) 'Void]
  11300. [('Any t2) t2]
  11301. [(t1 'Any) t1]
  11302. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11303. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11304. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11305. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11306. -> ,(join rt1 rt2))]))
  11307. (define/public (meet t1 t2)
  11308. (match* (t1 t2)
  11309. [('Integer 'Integer) 'Integer]
  11310. [('Boolean 'Boolean) 'Boolean]
  11311. [('Void 'Void) 'Void]
  11312. [('Any t2) 'Any]
  11313. [(t1 'Any) 'Any]
  11314. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11315. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11316. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11317. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11318. -> ,(meet rt1 rt2))]))
  11319. (define/public (make-cast e src tgt)
  11320. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11321. (define/public (check-consistent? t1 t2 e)
  11322. (unless (consistent? t1 t2)
  11323. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11324. (define/override (type-check-op op arg-types args e)
  11325. (match (dict-ref (operator-types) op)
  11326. [`(,param-types . ,return-type)
  11327. (for ([at arg-types] [pt param-types])
  11328. (check-consistent? at pt e))
  11329. (values return-type
  11330. (for/list ([e args] [s arg-types] [t param-types])
  11331. (make-cast e s t)))]
  11332. [else (error 'type-check-op "unrecognized ~a" op)]))
  11333. (define explicit-prim-ops
  11334. (set-union
  11335. (type-predicates)
  11336. (set 'procedure-arity 'eq?
  11337. 'vector 'vector-length 'vector-ref 'vector-set!
  11338. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11339. (define/override (fun-def-type d)
  11340. (match d
  11341. [(Def f params rt info body)
  11342. (define ps
  11343. (for/list ([p params])
  11344. (match p
  11345. [`[,x : ,T] T]
  11346. [(? symbol?) 'Any]
  11347. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11348. `(,@ps -> ,rt)]
  11349. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11350. \end{lstlisting}
  11351. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11352. \label{fig:type-check-Rgradual-aux}
  11353. \end{figure}
  11354. \clearpage
  11355. \section{Interpreting \LangCast{}}
  11356. \label{sec:interp-casts}
  11357. The runtime behavior of first-order casts is straightforward, that is,
  11358. casts involving simple types such as \code{Integer} and
  11359. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11360. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11361. puts the integer into a tagged value
  11362. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11363. \code{Integer} is accomplished with the \code{Project} operator, that
  11364. is, by checking the value's tag and either retrieving the underlying
  11365. integer or signaling an error if it the tag is not the one for
  11366. integers (Figure~\ref{fig:apply-project}).
  11367. %
  11368. Things get more interesting for higher-order casts, that is, casts
  11369. involving function or vector types.
  11370. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11371. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11372. this cast at runtime, we can't know in general whether the function
  11373. will always return an integer.\footnote{Predicting the return value of
  11374. a function is equivalent to the halting problem, which is
  11375. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11376. of the cast until the function is applied. This is accomplished by
  11377. wrapping \code{maybe-add1} in a new function that casts its parameter
  11378. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11379. casts the return value from \code{Any} to \code{Integer}.
  11380. Turning our attention to casts involving vector types, we consider the
  11381. example in Figure~\ref{fig:map-vec-bang} that defines a
  11382. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11383. type \code{(Vector Any Any)} and that updates \code{v} in place
  11384. instead of returning a new vector. So we name this function
  11385. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11386. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11387. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11388. cast between vector types would be a build a new vector whose elements
  11389. are the result of casting each of the original elements to the
  11390. appropriate target type. However, this approach is only valid for
  11391. immutable vectors; and our vectors are mutable. In the example of
  11392. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11393. the updates inside of \code{map-vec!} would happen to the new vector
  11394. and not the original one.
  11395. \begin{figure}[tbp]
  11396. % gradual_test_11.rkt
  11397. \begin{lstlisting}
  11398. (define (map-vec! [f : (Any -> Any)]
  11399. [v : (Vector Any Any)]) : Void
  11400. (begin
  11401. (vector-set! v 0 (f (vector-ref v 0)))
  11402. (vector-set! v 1 (f (vector-ref v 1)))))
  11403. (define (add1 x) (+ x 1))
  11404. (let ([v (vector 0 41)])
  11405. (begin (map-vec! add1 v) (vector-ref v 1)))
  11406. \end{lstlisting}
  11407. \caption{An example involving casts on vectors.}
  11408. \label{fig:map-vec-bang}
  11409. \end{figure}
  11410. Instead the interpreter needs to create a new kind of value, a
  11411. \emph{vector proxy}, that intercepts every vector operation. On a
  11412. read, the proxy reads from the underlying vector and then applies a
  11413. cast to the resulting value. On a write, the proxy casts the argument
  11414. value and then performs the write to the underlying vector. For the
  11415. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11416. \code{0} from \code{Integer} to \code{Any}. For the first
  11417. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11418. to \code{Integer}.
  11419. The final category of cast that we need to consider are casts between
  11420. the \code{Any} type and either a function or a vector
  11421. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11422. in which parameter \code{v} does not have a type annotation, so it is
  11423. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11424. type \code{(Vector Integer Integer)} so the type checker inserts a
  11425. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11426. thought is to use \code{Inject}, but that doesn't work because
  11427. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11428. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11429. to \code{Any}.
  11430. \begin{figure}[tbp]
  11431. \begin{lstlisting}
  11432. (define (map-vec! [f : (Any -> Any)] v) : Void
  11433. (begin
  11434. (vector-set! v 0 (f (vector-ref v 0)))
  11435. (vector-set! v 1 (f (vector-ref v 1)))))
  11436. (define (add1 x) (+ x 1))
  11437. (let ([v (vector 0 41)])
  11438. (begin (map-vec! add1 v) (vector-ref v 1)))
  11439. \end{lstlisting}
  11440. \caption{Casting a vector to \code{Any}.}
  11441. \label{fig:map-vec-any}
  11442. \end{figure}
  11443. The \LangCast{} interpreter uses an auxiliary function named
  11444. \code{apply-cast} to cast a value from a source type to a target type,
  11445. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11446. of the kinds of casts that we've discussed in this section.
  11447. \begin{figure}[tbp]
  11448. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11449. (define/public (apply-cast v s t)
  11450. (match* (s t)
  11451. [(t1 t2) #:when (equal? t1 t2) v]
  11452. [('Any t2)
  11453. (match t2
  11454. [`(,ts ... -> ,rt)
  11455. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11456. (define v^ (apply-project v any->any))
  11457. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11458. [`(Vector ,ts ...)
  11459. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11460. (define v^ (apply-project v vec-any))
  11461. (apply-cast v^ vec-any `(Vector ,@ts))]
  11462. [else (apply-project v t2)])]
  11463. [(t1 'Any)
  11464. (match t1
  11465. [`(,ts ... -> ,rt)
  11466. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11467. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11468. (apply-inject v^ (any-tag any->any))]
  11469. [`(Vector ,ts ...)
  11470. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11471. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11472. (apply-inject v^ (any-tag vec-any))]
  11473. [else (apply-inject v (any-tag t1))])]
  11474. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11475. (define x (gensym 'x))
  11476. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11477. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11478. (define cast-writes
  11479. (for/list ([t1 ts1] [t2 ts2])
  11480. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11481. `(vector-proxy ,(vector v (apply vector cast-reads)
  11482. (apply vector cast-writes)))]
  11483. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11484. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11485. `(function ,xs ,(Cast
  11486. (Apply (Value v)
  11487. (for/list ([x xs][t1 ts1][t2 ts2])
  11488. (Cast (Var x) t2 t1)))
  11489. rt1 rt2) ())]
  11490. ))
  11491. \end{lstlisting}
  11492. \caption{The \code{apply-cast} auxiliary method.}
  11493. \label{fig:apply-cast}
  11494. \end{figure}
  11495. The interpreter for \LangCast{} is defined in
  11496. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11497. dispatching to \code{apply-cast}. To handle the addition of vector
  11498. proxies, we update the vector primitives in \code{interp-op} using the
  11499. functions in Figure~\ref{fig:guarded-vector}.
  11500. \begin{figure}[tbp]
  11501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11502. (define interp-Rcast-class
  11503. (class interp-Rwhile-class
  11504. (super-new)
  11505. (inherit apply-fun apply-inject apply-project)
  11506. (define/override (interp-op op)
  11507. (match op
  11508. ['vector-length guarded-vector-length]
  11509. ['vector-ref guarded-vector-ref]
  11510. ['vector-set! guarded-vector-set!]
  11511. ['any-vector-ref (lambda (v i)
  11512. (match v [`(tagged ,v^ ,tg)
  11513. (guarded-vector-ref v^ i)]))]
  11514. ['any-vector-set! (lambda (v i a)
  11515. (match v [`(tagged ,v^ ,tg)
  11516. (guarded-vector-set! v^ i a)]))]
  11517. ['any-vector-length (lambda (v)
  11518. (match v [`(tagged ,v^ ,tg)
  11519. (guarded-vector-length v^)]))]
  11520. [else (super interp-op op)]
  11521. ))
  11522. (define/override ((interp-exp env) e)
  11523. (define (recur e) ((interp-exp env) e))
  11524. (match e
  11525. [(Value v) v]
  11526. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11527. [else ((super interp-exp env) e)]))
  11528. ))
  11529. (define (interp-Rcast p)
  11530. (send (new interp-Rcast-class) interp-program p))
  11531. \end{lstlisting}
  11532. \caption{The interpreter for \LangCast{}.}
  11533. \label{fig:interp-Rcast}
  11534. \end{figure}
  11535. \begin{figure}[tbp]
  11536. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11537. (define (guarded-vector-ref vec i)
  11538. (match vec
  11539. [`(vector-proxy ,proxy)
  11540. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11541. (define rd (vector-ref (vector-ref proxy 1) i))
  11542. (apply-fun rd (list val) 'guarded-vector-ref)]
  11543. [else (vector-ref vec i)]))
  11544. (define (guarded-vector-set! vec i arg)
  11545. (match vec
  11546. [`(vector-proxy ,proxy)
  11547. (define wr (vector-ref (vector-ref proxy 2) i))
  11548. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11549. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11550. [else (vector-set! vec i arg)]))
  11551. (define (guarded-vector-length vec)
  11552. (match vec
  11553. [`(vector-proxy ,proxy)
  11554. (guarded-vector-length (vector-ref proxy 0))]
  11555. [else (vector-length vec)]))
  11556. \end{lstlisting}
  11557. \caption{The guarded-vector auxiliary functions.}
  11558. \label{fig:guarded-vector}
  11559. \end{figure}
  11560. \section{Lower Casts}
  11561. \label{sec:lower-casts}
  11562. The next step in the journey towards x86 is the \code{lower-casts}
  11563. pass that translates the casts in \LangCast{} to the lower-level
  11564. \code{Inject} and \code{Project} operators and a new operator for
  11565. creating vector proxies, extending the \LangLoop{} language to create
  11566. \LangProxy{}. We recommend creating an auxiliary function named
  11567. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11568. and a target type, and translates it to expression in \LangProxy{} that has
  11569. the same behavior as casting the expression from the source to the
  11570. target type in the interpreter.
  11571. The \code{lower-cast} function can follow a code structure similar to
  11572. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11573. the interpreter for \LangCast{} because it must handle the same cases as
  11574. \code{apply-cast} and it needs to mimic the behavior of
  11575. \code{apply-cast}. The most interesting cases are those concerning the
  11576. casts between two vector types and between two function types.
  11577. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11578. type to another vector type is accomplished by creating a proxy that
  11579. intercepts the operations on the underlying vector. Here we make the
  11580. creation of the proxy explicit with the \code{vector-proxy} primitive
  11581. operation. It takes three arguments, the first is an expression for
  11582. the vector, the second is a vector of functions for casting an element
  11583. that is being read from the vector, and the third is a vector of
  11584. functions for casting an element that is being written to the vector.
  11585. You can create the functions using \code{Lambda}. Also, as we shall
  11586. see in the next section, we need to differentiate these vectors from
  11587. the user-created ones, so we recommend using a new primitive operator
  11588. named \code{raw-vector} instead of \code{vector} to create these
  11589. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11590. the output of \code{lower-casts} on the example in
  11591. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11592. integers to a vector of \code{Any}.
  11593. \begin{figure}[tbp]
  11594. \begin{lstlisting}
  11595. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11596. (begin
  11597. (vector-set! v 0 (f (vector-ref v 0)))
  11598. (vector-set! v 1 (f (vector-ref v 1)))))
  11599. (define (add1 [x : Any]) : Any
  11600. (inject (+ (project x Integer) 1) Integer))
  11601. (let ([v (vector 0 41)])
  11602. (begin
  11603. (map-vec! add1 (vector-proxy v
  11604. (raw-vector (lambda: ([x9 : Integer]) : Any
  11605. (inject x9 Integer))
  11606. (lambda: ([x9 : Integer]) : Any
  11607. (inject x9 Integer)))
  11608. (raw-vector (lambda: ([x9 : Any]) : Integer
  11609. (project x9 Integer))
  11610. (lambda: ([x9 : Any]) : Integer
  11611. (project x9 Integer)))))
  11612. (vector-ref v 1)))
  11613. \end{lstlisting}
  11614. \caption{Output of \code{lower-casts} on the example in
  11615. Figure~\ref{fig:map-vec-bang}.}
  11616. \label{fig:map-vec-bang-lower-cast}
  11617. \end{figure}
  11618. A cast from one function type to another function type is accomplished
  11619. by generating a \code{Lambda} whose parameter and return types match
  11620. the target function type. The body of the \code{Lambda} should cast
  11621. the parameters from the target type to the source type (yes,
  11622. backwards! functions are contravariant\index{subject}{contravariant} in the
  11623. parameters), then call the underlying function, and finally cast the
  11624. result from the source return type to the target return type.
  11625. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11626. \code{lower-casts} pass on the \code{map-vec} example in
  11627. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11628. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11629. \begin{figure}[tbp]
  11630. \begin{lstlisting}
  11631. (define (map-vec [f : (Integer -> Integer)]
  11632. [v : (Vector Integer Integer)])
  11633. : (Vector Integer Integer)
  11634. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11635. (define (add1 [x : Any]) : Any
  11636. (inject (+ (project x Integer) 1) Integer))
  11637. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11638. (project (add1 (inject x9 Integer)) Integer))
  11639. (vector 0 41)) 1)
  11640. \end{lstlisting}
  11641. \caption{Output of \code{lower-casts} on the example in
  11642. Figure~\ref{fig:gradual-map-vec}.}
  11643. \label{fig:map-vec-lower-cast}
  11644. \end{figure}
  11645. \section{Differentiate Proxies}
  11646. \label{sec:differentiate-proxies}
  11647. So far the job of differentiating vectors and vector proxies has been
  11648. the job of the interpreter. For example, the interpreter for \LangCast{}
  11649. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11650. function in Figure~\ref{fig:guarded-vector}. In the
  11651. \code{differentiate-proxies} pass we shift this responsibility to the
  11652. generated code.
  11653. We begin by designing the output language $R^p_8$. In
  11654. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11655. proxies. In $R^p_8$ we return the \code{Vector} type to
  11656. its original meaning, as the type of real vectors, and we introduce a
  11657. new type, \code{PVector}, whose values can be either real vectors or
  11658. vector proxies. This new type comes with a suite of new primitive
  11659. operations for creating and using values of type \code{PVector}. We
  11660. don't need to introduce a new type to represent vector proxies. A
  11661. proxy is represented by a vector containing three things: 1) the
  11662. underlying vector, 2) a vector of functions for casting elements that
  11663. are read from the vector, and 3) a vector of functions for casting
  11664. values to be written to the vector. So we define the following
  11665. abbreviation for the type of a vector proxy:
  11666. \[
  11667. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11668. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11669. \to (\key{PVector}~ T' \ldots)
  11670. \]
  11671. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11672. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11673. %
  11674. Next we describe each of the new primitive operations.
  11675. \begin{description}
  11676. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11677. (\key{PVector} $T \ldots$)]\ \\
  11678. %
  11679. This operation brands a vector as a value of the \code{PVector} type.
  11680. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11681. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11682. %
  11683. This operation brands a vector proxy as value of the \code{PVector} type.
  11684. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11685. \code{Boolean}] \ \\
  11686. %
  11687. returns true if the value is a vector proxy and false if it is a
  11688. real vector.
  11689. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11690. (\key{Vector} $T \ldots$)]\ \\
  11691. %
  11692. Assuming that the input is a vector (and not a proxy), this
  11693. operation returns the vector.
  11694. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11695. $\to$ \code{Boolean}]\ \\
  11696. %
  11697. Given a vector proxy, this operation returns the length of the
  11698. underlying vector.
  11699. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11700. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11701. %
  11702. Given a vector proxy, this operation returns the $i$th element of
  11703. the underlying vector.
  11704. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11705. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11706. proxy, this operation writes a value to the $i$th element of the
  11707. underlying vector.
  11708. \end{description}
  11709. Now to discuss the translation that differentiates vectors from
  11710. proxies. First, every type annotation in the program must be
  11711. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11712. Next, we must insert uses of \code{PVector} operations in the
  11713. appropriate places. For example, we wrap every vector creation with an
  11714. \code{inject-vector}.
  11715. \begin{lstlisting}
  11716. (vector |$e_1 \ldots e_n$|)
  11717. |$\Rightarrow$|
  11718. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11719. \end{lstlisting}
  11720. The \code{raw-vector} operator that we introduced in the previous
  11721. section does not get injected.
  11722. \begin{lstlisting}
  11723. (raw-vector |$e_1 \ldots e_n$|)
  11724. |$\Rightarrow$|
  11725. (vector |$e'_1 \ldots e'_n$|)
  11726. \end{lstlisting}
  11727. The \code{vector-proxy} primitive translates as follows.
  11728. \begin{lstlisting}
  11729. (vector-proxy |$e_1~e_2~e_3$|)
  11730. |$\Rightarrow$|
  11731. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11732. \end{lstlisting}
  11733. We translate the vector operations into conditional expressions that
  11734. check whether the value is a proxy and then dispatch to either the
  11735. appropriate proxy vector operation or the regular vector operation.
  11736. For example, the following is the translation for \code{vector-ref}.
  11737. \begin{lstlisting}
  11738. (vector-ref |$e_1$| |$i$|)
  11739. |$\Rightarrow$|
  11740. (let ([|$v~e_1$|])
  11741. (if (proxy? |$v$|)
  11742. (proxy-vector-ref |$v$| |$i$|)
  11743. (vector-ref (project-vector |$v$|) |$i$|)
  11744. \end{lstlisting}
  11745. Note in the case of a real vector, we must apply \code{project-vector}
  11746. before the \code{vector-ref}.
  11747. \section{Reveal Casts}
  11748. \label{sec:reveal-casts-gradual}
  11749. Recall that the \code{reveal-casts} pass
  11750. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11751. \code{Inject} and \code{Project} into lower-level operations. In
  11752. particular, \code{Project} turns into a conditional expression that
  11753. inspects the tag and retrieves the underlying value. Here we need to
  11754. augment the translation of \code{Project} to handle the situation when
  11755. the target type is \code{PVector}. Instead of using
  11756. \code{vector-length} we need to use \code{proxy-vector-length}.
  11757. \begin{lstlisting}
  11758. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11759. |$\Rightarrow$|
  11760. (let |$\itm{tmp}$| |$e'$|
  11761. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11762. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11763. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11764. (exit)))
  11765. \end{lstlisting}
  11766. \section{Closure Conversion}
  11767. \label{sec:closure-conversion-gradual}
  11768. The closure conversion pass only requires one minor adjustment. The
  11769. auxiliary function that translates type annotations needs to be
  11770. updated to handle the \code{PVector} type.
  11771. \section{Explicate Control}
  11772. \label{sec:explicate-control-gradual}
  11773. Update the \code{explicate-control} pass to handle the new primitive
  11774. operations on the \code{PVector} type.
  11775. \section{Select Instructions}
  11776. \label{sec:select-instructions-gradual}
  11777. Recall that the \code{select-instructions} pass is responsible for
  11778. lowering the primitive operations into x86 instructions. So we need
  11779. to translate the new \code{PVector} operations to x86. To do so, the
  11780. first question we need to answer is how will we differentiate the two
  11781. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11782. We need just one bit to accomplish this, and use the bit in position
  11783. $57$ of the 64-bit tag at the front of every vector (see
  11784. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11785. for \code{inject-vector} we leave it that way.
  11786. \begin{lstlisting}
  11787. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11788. |$\Rightarrow$|
  11789. movq |$e'_1$|, |$\itm{lhs'}$|
  11790. \end{lstlisting}
  11791. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11792. \begin{lstlisting}
  11793. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11794. |$\Rightarrow$|
  11795. movq |$e'_1$|, %r11
  11796. movq |$(1 << 57)$|, %rax
  11797. orq 0(%r11), %rax
  11798. movq %rax, 0(%r11)
  11799. movq %r11, |$\itm{lhs'}$|
  11800. \end{lstlisting}
  11801. The \code{proxy?} operation consumes the information so carefully
  11802. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11803. isolates the $57$th bit to tell whether the value is a real vector or
  11804. a proxy.
  11805. \begin{lstlisting}
  11806. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11807. |$\Rightarrow$|
  11808. movq |$e_1'$|, %r11
  11809. movq 0(%r11), %rax
  11810. sarq $57, %rax
  11811. andq $1, %rax
  11812. movq %rax, |$\itm{lhs'}$|
  11813. \end{lstlisting}
  11814. The \code{project-vector} operation is straightforward to translate,
  11815. so we leave it up to the reader.
  11816. Regarding the \code{proxy-vector} operations, the runtime provides
  11817. procedures that implement them (they are recursive functions!) so
  11818. here we simply need to translate these vector operations into the
  11819. appropriate function call. For example, here is the translation for
  11820. \code{proxy-vector-ref}.
  11821. \begin{lstlisting}
  11822. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11823. |$\Rightarrow$|
  11824. movq |$e_1'$|, %rdi
  11825. movq |$e_2'$|, %rsi
  11826. callq proxy_vector_ref
  11827. movq %rax, |$\itm{lhs'}$|
  11828. \end{lstlisting}
  11829. We have another batch of vector operations to deal with, those for the
  11830. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11831. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11832. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11833. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11834. Section~\ref{sec:select-Rany} we selected instructions for these
  11835. operations based on the idea that the underlying value was a real
  11836. vector. But in the current setting, the underlying value is of type
  11837. \code{PVector}. So \code{any-vector-ref} can be translates to
  11838. pseudo-x86 as follows. We begin by projecting the underlying value out
  11839. of the tagged value and then call the \code{proxy\_vector\_ref}
  11840. procedure in the runtime.
  11841. \begin{lstlisting}
  11842. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11843. movq |$\neg 111$|, %rdi
  11844. andq |$e_1'$|, %rdi
  11845. movq |$e_2'$|, %rsi
  11846. callq proxy_vector_ref
  11847. movq %rax, |$\itm{lhs'}$|
  11848. \end{lstlisting}
  11849. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11850. be translated in a similar way.
  11851. \begin{exercise}\normalfont
  11852. Implement a compiler for the gradually-typed \LangGrad{} language by
  11853. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11854. partially-typed test programs. In addition to testing with these
  11855. new programs, also test your compiler on all the tests for \LangLoop{}
  11856. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11857. on the \LangDyn{} programs but you can adapt them by inserting
  11858. a cast to the \code{Any} type around each subexpression
  11859. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11860. you can induce one by wrapping the subexpression \code{e}
  11861. with a call to an un-annotated identity function, like this:
  11862. \code{((lambda (x) x) e)}.
  11863. \end{exercise}
  11864. \begin{figure}[p]
  11865. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11866. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11867. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11868. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11869. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11870. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11871. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11872. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11873. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11874. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11875. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11876. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11877. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11878. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11879. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11880. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11881. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11882. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11883. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11884. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11885. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11886. \path[->,bend right=15] (Rgradual) edge [above] node
  11887. {\ttfamily\footnotesize type-check} (Rgradualp);
  11888. \path[->,bend right=15] (Rgradualp) edge [above] node
  11889. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11890. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11891. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11892. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11893. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11894. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11895. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11896. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11897. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11898. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11899. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11900. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11901. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11902. \path[->,bend left=15] (F1-1) edge [below] node
  11903. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11904. \path[->,bend right=15] (F1-2) edge [above] node
  11905. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11906. \path[->,bend right=15] (F1-3) edge [above] node
  11907. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11908. \path[->,bend right=15] (F1-4) edge [above] node
  11909. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11910. \path[->,bend right=15] (F1-5) edge [right] node
  11911. {\ttfamily\footnotesize explicate-control} (C3-2);
  11912. \path[->,bend left=15] (C3-2) edge [left] node
  11913. {\ttfamily\footnotesize select-instr.} (x86-2);
  11914. \path[->,bend right=15] (x86-2) edge [left] node
  11915. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11916. \path[->,bend right=15] (x86-2-1) edge [below] node
  11917. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11918. \path[->,bend right=15] (x86-2-2) edge [left] node
  11919. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11920. \path[->,bend left=15] (x86-3) edge [above] node
  11921. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11922. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11923. \end{tikzpicture}
  11924. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11925. \label{fig:Rgradual-passes}
  11926. \end{figure}
  11927. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11928. for the compilation of \LangGrad{}.
  11929. \section{Further Reading}
  11930. This chapter just scratches the surface of gradual typing. The basic
  11931. approach described here is missing two key ingredients that one would
  11932. want in a implementation of gradual typing: blame
  11933. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11934. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11935. problem addressed by blame tracking is that when a cast on a
  11936. higher-order value fails, it often does so at a point in the program
  11937. that is far removed from the original cast. Blame tracking is a
  11938. technique for propagating extra information through casts and proxies
  11939. so that when a cast fails, the error message can point back to the
  11940. original location of the cast in the source program.
  11941. The problem addressed by space-efficient casts also relates to
  11942. higher-order casts. It turns out that in partially typed programs, a
  11943. function or vector can flow through very-many casts at runtime. With
  11944. the approach described in this chapter, each cast adds another
  11945. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11946. considerable space, but it also makes the function calls and vector
  11947. operations slow. For example, a partially-typed version of quicksort
  11948. could, in the worst case, build a chain of proxies of length $O(n)$
  11949. around the vector, changing the overall time complexity of the
  11950. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11951. solution to this problem by representing casts using the coercion
  11952. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11953. long chains of proxies by compressing them into a concise normal
  11954. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11955. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11956. the Grift compiler.
  11957. \begin{center}
  11958. \url{https://github.com/Gradual-Typing/Grift}
  11959. \end{center}
  11960. There are also interesting interactions between gradual typing and
  11961. other language features, such as parametetric polymorphism,
  11962. information-flow types, and type inference, to name a few. We
  11963. recommend the reader to the online gradual typing bibliography:
  11964. \begin{center}
  11965. \url{http://samth.github.io/gradual-typing-bib/}
  11966. \end{center}
  11967. % TODO: challenge problem:
  11968. % type analysis and type specialization?
  11969. % coercions?
  11970. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11971. \chapter{Parametric Polymorphism}
  11972. \label{ch:Rpoly}
  11973. \index{subject}{parametric polymorphism}
  11974. \index{subject}{generics}
  11975. This chapter studies the compilation of parametric
  11976. polymorphism\index{subject}{parametric polymorphism}
  11977. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  11978. Racket. Parametric polymorphism enables improved code reuse by
  11979. parameterizing functions and data structures with respect to the types
  11980. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11981. revisits the \code{map-vec} example but this time gives it a more
  11982. fitting type. This \code{map-vec} function is parameterized with
  11983. respect to the element type of the vector. The type of \code{map-vec}
  11984. is the following polymorphic type as specified by the \code{All} and
  11985. the type parameter \code{a}.
  11986. \begin{lstlisting}
  11987. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11988. \end{lstlisting}
  11989. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11990. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11991. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11992. \code{a}, but we could have just as well applied \code{map-vec} to a
  11993. vector of Booleans (and a function on Booleans).
  11994. \begin{figure}[tbp]
  11995. % poly_test_2.rkt
  11996. \begin{lstlisting}
  11997. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11998. (define (map-vec f v)
  11999. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12000. (define (add1 [x : Integer]) : Integer (+ x 1))
  12001. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12002. \end{lstlisting}
  12003. \caption{The \code{map-vec} example using parametric polymorphism.}
  12004. \label{fig:map-vec-poly}
  12005. \end{figure}
  12006. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  12007. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  12008. syntax. We add a second form for function definitions in which a type
  12009. declaration comes before the \code{define}. In the abstract syntax,
  12010. the return type in the \code{Def} is \code{Any}, but that should be
  12011. ignored in favor of the return type in the type declaration. (The
  12012. \code{Any} comes from using the same parser as in
  12013. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  12014. enables the use of an \code{All} type for a function, thereby making
  12015. it polymorphic. The grammar for types is extended to include
  12016. polymorphic types and type variables.
  12017. \begin{figure}[tp]
  12018. \centering
  12019. \fbox{
  12020. \begin{minipage}{0.96\textwidth}
  12021. \small
  12022. \[
  12023. \begin{array}{lcl}
  12024. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12025. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  12026. &\mid& \LP\key{:}~\Var~\Type\RP \\
  12027. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  12028. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  12029. \end{array}
  12030. \]
  12031. \end{minipage}
  12032. }
  12033. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  12034. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12035. \label{fig:Rpoly-concrete-syntax}
  12036. \end{figure}
  12037. \begin{figure}[tp]
  12038. \centering
  12039. \fbox{
  12040. \begin{minipage}{0.96\textwidth}
  12041. \small
  12042. \[
  12043. \begin{array}{lcl}
  12044. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12045. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12046. &\mid& \DECL{\Var}{\Type} \\
  12047. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  12048. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12049. \end{array}
  12050. \]
  12051. \end{minipage}
  12052. }
  12053. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  12054. (Figure~\ref{fig:Rwhile-syntax}).}
  12055. \label{fig:Rpoly-syntax}
  12056. \end{figure}
  12057. By including polymorphic types in the $\Type$ non-terminal we choose
  12058. to make them first-class which has interesting repercussions on the
  12059. compiler. Many languages with polymorphism, such as
  12060. C++~\citep{stroustrup88:_param_types} and Standard
  12061. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  12062. it is useful to see an example of first-class polymorphism. In
  12063. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  12064. whose parameter is a polymorphic function. The occurrence of a
  12065. polymorphic type underneath a function type is enabled by the normal
  12066. recursive structure of the grammar for $\Type$ and the categorization
  12067. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  12068. applies the polymorphic function to a Boolean and to an integer.
  12069. \begin{figure}[tbp]
  12070. \begin{lstlisting}
  12071. (: apply-twice ((All (b) (b -> b)) -> Integer))
  12072. (define (apply-twice f)
  12073. (if (f #t) (f 42) (f 777)))
  12074. (: id (All (a) (a -> a)))
  12075. (define (id x) x)
  12076. (apply-twice id)
  12077. \end{lstlisting}
  12078. \caption{An example illustrating first-class polymorphism.}
  12079. \label{fig:apply-twice}
  12080. \end{figure}
  12081. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  12082. three new responsibilities (compared to \LangLoop{}). The type checking of
  12083. function application is extended to handle the case where the operator
  12084. expression is a polymorphic function. In that case the type arguments
  12085. are deduced by matching the type of the parameters with the types of
  12086. the arguments.
  12087. %
  12088. The \code{match-types} auxiliary function carries out this deduction
  12089. by recursively descending through a parameter type \code{pt} and the
  12090. corresponding argument type \code{at}, making sure that they are equal
  12091. except when there is a type parameter on the left (in the parameter
  12092. type). If it's the first time that the type parameter has been
  12093. encountered, then the algorithm deduces an association of the type
  12094. parameter to the corresponding type on the right (in the argument
  12095. type). If it's not the first time that the type parameter has been
  12096. encountered, the algorithm looks up its deduced type and makes sure
  12097. that it is equal to the type on the right.
  12098. %
  12099. Once the type arguments are deduced, the operator expression is
  12100. wrapped in an \code{Inst} AST node (for instantiate) that records the
  12101. type of the operator, but more importantly, records the deduced type
  12102. arguments. The return type of the application is the return type of
  12103. the polymorphic function, but with the type parameters replaced by the
  12104. deduced type arguments, using the \code{subst-type} function.
  12105. The second responsibility of the type checker is extending the
  12106. function \code{type-equal?} to handle the \code{All} type. This is
  12107. not quite a simple as equal on other types, such as function and
  12108. vector types, because two polymorphic types can be syntactically
  12109. different even though they are equivalent types. For example,
  12110. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  12111. Two polymorphic types should be considered equal if they differ only
  12112. in the choice of the names of the type parameters. The
  12113. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  12114. renames the type parameters of the first type to match the type
  12115. parameters of the second type.
  12116. The third responsibility of the type checker is making sure that only
  12117. defined type variables appear in type annotations. The
  12118. \code{check-well-formed} function defined in
  12119. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  12120. sure that each type variable has been defined.
  12121. The output language of the type checker is \LangInst{}, defined in
  12122. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  12123. declaration and polymorphic function into a single definition, using
  12124. the \code{Poly} form, to make polymorphic functions more convenient to
  12125. process in next pass of the compiler.
  12126. \begin{figure}[tp]
  12127. \centering
  12128. \fbox{
  12129. \begin{minipage}{0.96\textwidth}
  12130. \small
  12131. \[
  12132. \begin{array}{lcl}
  12133. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12134. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  12135. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12136. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  12137. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12138. \end{array}
  12139. \]
  12140. \end{minipage}
  12141. }
  12142. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  12143. (Figure~\ref{fig:Rwhile-syntax}).}
  12144. \label{fig:Rpoly-prime-syntax}
  12145. \end{figure}
  12146. The output of the type checker on the polymorphic \code{map-vec}
  12147. example is listed in Figure~\ref{fig:map-vec-type-check}.
  12148. \begin{figure}[tbp]
  12149. % poly_test_2.rkt
  12150. \begin{lstlisting}
  12151. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  12152. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  12153. (define (add1 [x : Integer]) : Integer (+ x 1))
  12154. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12155. (Integer))
  12156. add1 (vector 0 41)) 1)
  12157. \end{lstlisting}
  12158. \caption{Output of the type checker on the \code{map-vec} example.}
  12159. \label{fig:map-vec-type-check}
  12160. \end{figure}
  12161. \begin{figure}[tbp]
  12162. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12163. (define type-check-poly-class
  12164. (class type-check-Rwhile-class
  12165. (super-new)
  12166. (inherit check-type-equal?)
  12167. (define/override (type-check-apply env e1 es)
  12168. (define-values (e^ ty) ((type-check-exp env) e1))
  12169. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  12170. ((type-check-exp env) e)))
  12171. (match ty
  12172. [`(,ty^* ... -> ,rt)
  12173. (for ([arg-ty ty*] [param-ty ty^*])
  12174. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  12175. (values e^ es^ rt)]
  12176. [`(All ,xs (,tys ... -> ,rt))
  12177. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12178. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  12179. (match-types env^^ param-ty arg-ty)))
  12180. (define targs
  12181. (for/list ([x xs])
  12182. (match (dict-ref env^^ x (lambda () #f))
  12183. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  12184. x (Apply e1 es))]
  12185. [ty ty])))
  12186. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  12187. [else (error 'type-check "expected a function, not ~a" ty)]))
  12188. (define/override ((type-check-exp env) e)
  12189. (match e
  12190. [(Lambda `([,xs : ,Ts] ...) rT body)
  12191. (for ([T Ts]) ((check-well-formed env) T))
  12192. ((check-well-formed env) rT)
  12193. ((super type-check-exp env) e)]
  12194. [(HasType e1 ty)
  12195. ((check-well-formed env) ty)
  12196. ((super type-check-exp env) e)]
  12197. [else ((super type-check-exp env) e)]))
  12198. (define/override ((type-check-def env) d)
  12199. (verbose 'type-check "poly/def" d)
  12200. (match d
  12201. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  12202. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  12203. (for ([p ps]) ((check-well-formed ts-env) p))
  12204. ((check-well-formed ts-env) rt)
  12205. (define new-env (append ts-env (map cons xs ps) env))
  12206. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12207. (check-type-equal? ty^ rt body)
  12208. (Generic ts (Def f p:t* rt info body^))]
  12209. [else ((super type-check-def env) d)]))
  12210. (define/override (type-check-program p)
  12211. (match p
  12212. [(Program info body)
  12213. (type-check-program (ProgramDefsExp info '() body))]
  12214. [(ProgramDefsExp info ds body)
  12215. (define ds^ (combine-decls-defs ds))
  12216. (define new-env (for/list ([d ds^])
  12217. (cons (def-name d) (fun-def-type d))))
  12218. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  12219. (define-values (body^ ty) ((type-check-exp new-env) body))
  12220. (check-type-equal? ty 'Integer body)
  12221. (ProgramDefsExp info ds^^ body^)]))
  12222. ))
  12223. \end{lstlisting}
  12224. \caption{Type checker for the \LangPoly{} language.}
  12225. \label{fig:type-check-Rvar0}
  12226. \end{figure}
  12227. \begin{figure}[tbp]
  12228. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12229. (define/override (type-equal? t1 t2)
  12230. (match* (t1 t2)
  12231. [(`(All ,xs ,T1) `(All ,ys ,T2))
  12232. (define env (map cons xs ys))
  12233. (type-equal? (subst-type env T1) T2)]
  12234. [(other wise)
  12235. (super type-equal? t1 t2)]))
  12236. (define/public (match-types env pt at)
  12237. (match* (pt at)
  12238. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  12239. [('Void 'Void) env] [('Any 'Any) env]
  12240. [(`(Vector ,pts ...) `(Vector ,ats ...))
  12241. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  12242. (match-types env^ pt1 at1))]
  12243. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  12244. (define env^ (match-types env prt art))
  12245. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  12246. (match-types env^^ pt1 at1))]
  12247. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  12248. (define env^ (append (map cons pxs axs) env))
  12249. (match-types env^ pt1 at1)]
  12250. [((? symbol? x) at)
  12251. (match (dict-ref env x (lambda () #f))
  12252. [#f (error 'type-check "undefined type variable ~a" x)]
  12253. ['Type (cons (cons x at) env)]
  12254. [t^ (check-type-equal? at t^ 'matching) env])]
  12255. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  12256. (define/public (subst-type env pt)
  12257. (match pt
  12258. ['Integer 'Integer] ['Boolean 'Boolean]
  12259. ['Void 'Void] ['Any 'Any]
  12260. [`(Vector ,ts ...)
  12261. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  12262. [`(,ts ... -> ,rt)
  12263. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  12264. [`(All ,xs ,t)
  12265. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  12266. [(? symbol? x) (dict-ref env x)]
  12267. [else (error 'type-check "expected a type not ~a" pt)]))
  12268. (define/public (combine-decls-defs ds)
  12269. (match ds
  12270. ['() '()]
  12271. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  12272. (unless (equal? name f)
  12273. (error 'type-check "name mismatch, ~a != ~a" name f))
  12274. (match type
  12275. [`(All ,xs (,ps ... -> ,rt))
  12276. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12277. (cons (Generic xs (Def name params^ rt info body))
  12278. (combine-decls-defs ds^))]
  12279. [`(,ps ... -> ,rt)
  12280. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12281. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12282. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12283. [`(,(Def f params rt info body) . ,ds^)
  12284. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12285. \end{lstlisting}
  12286. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12287. \label{fig:type-check-Rvar0-aux}
  12288. \end{figure}
  12289. \begin{figure}[tbp]
  12290. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12291. (define/public ((check-well-formed env) ty)
  12292. (match ty
  12293. ['Integer (void)]
  12294. ['Boolean (void)]
  12295. ['Void (void)]
  12296. [(? symbol? a)
  12297. (match (dict-ref env a (lambda () #f))
  12298. ['Type (void)]
  12299. [else (error 'type-check "undefined type variable ~a" a)])]
  12300. [`(Vector ,ts ...)
  12301. (for ([t ts]) ((check-well-formed env) t))]
  12302. [`(,ts ... -> ,t)
  12303. (for ([t ts]) ((check-well-formed env) t))
  12304. ((check-well-formed env) t)]
  12305. [`(All ,xs ,t)
  12306. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12307. ((check-well-formed env^) t)]
  12308. [else (error 'type-check "unrecognized type ~a" ty)]))
  12309. \end{lstlisting}
  12310. \caption{Well-formed types.}
  12311. \label{fig:well-formed-types}
  12312. \end{figure}
  12313. % TODO: interpreter for R'_10
  12314. \section{Compiling Polymorphism}
  12315. \label{sec:compiling-poly}
  12316. Broadly speaking, there are four approaches to compiling parametric
  12317. polymorphism, which we describe below.
  12318. \begin{description}
  12319. \item[Monomorphization] generates a different version of a polymorphic
  12320. function for each set of type arguments that it is used with,
  12321. producing type-specialized code. This approach results in the most
  12322. efficient code but requires whole-program compilation (no separate
  12323. compilation) and increases code size. For our current purposes
  12324. monomorphization is a non-starter because, with first-class
  12325. polymorphism, it is sometimes not possible to determine which
  12326. generic functions are used with which type arguments during
  12327. compilation. (It can be done at runtime, with just-in-time
  12328. compilation.) This approach is used to compile C++
  12329. templates~\citep{stroustrup88:_param_types} and polymorphic
  12330. functions in NESL~\citep{Blelloch:1993aa} and
  12331. ML~\citep{Weeks:2006aa}.
  12332. \item[Uniform representation] generates one version of each
  12333. polymorphic function but requires all values have a common ``boxed''
  12334. format, such as the tagged values of type \code{Any} in
  12335. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12336. similarly to code in a dynamically typed language (like \LangDyn{}),
  12337. in which primitive operators require their arguments to be projected
  12338. from \code{Any} and their results are injected into \code{Any}. (In
  12339. object-oriented languages, the projection is accomplished via
  12340. virtual method dispatch.) The uniform representation approach is
  12341. compatible with separate compilation and with first-class
  12342. polymorphism. However, it produces the least-efficient code because
  12343. it introduces overhead in the entire program, including
  12344. non-polymorphic code. This approach is used in implementations of
  12345. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12346. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12347. Java~\citep{Bracha:1998fk}.
  12348. \item[Mixed representation] generates one version of each polymorphic
  12349. function, using a boxed representation for type
  12350. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12351. and conversions are performed at the boundaries between monomorphic
  12352. and polymorphic (e.g. when a polymorphic function is instantiated
  12353. and called). This approach is compatible with separate compilation
  12354. and first-class polymorphism and maintains the efficiency of
  12355. monomorphic code. The tradeoff is increased overhead at the boundary
  12356. between monomorphic and polymorphic code. This approach is used in
  12357. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12358. Java 5 with the addition of autoboxing.
  12359. \item[Type passing] uses the unboxed representation in both
  12360. monomorphic and polymorphic code. Each polymorphic function is
  12361. compiled to a single function with extra parameters that describe
  12362. the type arguments. The type information is used by the generated
  12363. code to know how to access the unboxed values at runtime. This
  12364. approach is used in implementation of the Napier88
  12365. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12366. passing is compatible with separate compilation and first-class
  12367. polymorphism and maintains the efficiency for monomorphic
  12368. code. There is runtime overhead in polymorphic code from dispatching
  12369. on type information.
  12370. \end{description}
  12371. In this chapter we use the mixed representation approach, partly
  12372. because of its favorable attributes, and partly because it is
  12373. straightforward to implement using the tools that we have already
  12374. built to support gradual typing. To compile polymorphic functions, we
  12375. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12376. \LangCast{}.
  12377. \section{Erase Types}
  12378. \label{sec:erase-types}
  12379. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12380. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12381. shows the output of the \code{erase-types} pass on the polymorphic
  12382. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12383. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12384. \code{All} types are removed from the type of \code{map-vec}.
  12385. \begin{figure}[tbp]
  12386. \begin{lstlisting}
  12387. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12388. : (Vector Any Any)
  12389. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12390. (define (add1 [x : Integer]) : Integer (+ x 1))
  12391. (vector-ref ((cast map-vec
  12392. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12393. ((Integer -> Integer) (Vector Integer Integer)
  12394. -> (Vector Integer Integer)))
  12395. add1 (vector 0 41)) 1)
  12396. \end{lstlisting}
  12397. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12398. \label{fig:map-vec-erase}
  12399. \end{figure}
  12400. This process of type erasure creates a challenge at points of
  12401. instantiation. For example, consider the instantiation of
  12402. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12403. The type of \code{map-vec} is
  12404. \begin{lstlisting}
  12405. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12406. \end{lstlisting}
  12407. and it is instantiated to
  12408. \begin{lstlisting}
  12409. ((Integer -> Integer) (Vector Integer Integer)
  12410. -> (Vector Integer Integer))
  12411. \end{lstlisting}
  12412. After erasure, the type of \code{map-vec} is
  12413. \begin{lstlisting}
  12414. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12415. \end{lstlisting}
  12416. but we need to convert it to the instantiated type. This is easy to
  12417. do in the target language \LangCast{} with a single \code{cast}. In
  12418. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12419. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12420. the instantiated type. The source and target type of a cast must be
  12421. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12422. because both the source and target are obtained from the same
  12423. polymorphic type of \code{map-vec}, replacing the type parameters with
  12424. \code{Any} in the former and with the deduced type arguments in the
  12425. later. (Recall that the \code{Any} type is consistent with any type.)
  12426. To implement the \code{erase-types} pass, we recommend defining a
  12427. recursive auxiliary function named \code{erase-type} that applies the
  12428. following two transformations. It replaces type variables with
  12429. \code{Any}
  12430. \begin{lstlisting}
  12431. |$x$|
  12432. |$\Rightarrow$|
  12433. Any
  12434. \end{lstlisting}
  12435. and it removes the polymorphic \code{All} types.
  12436. \begin{lstlisting}
  12437. (All |$xs$| |$T_1$|)
  12438. |$\Rightarrow$|
  12439. |$T'_1$|
  12440. \end{lstlisting}
  12441. Apply the \code{erase-type} function to all of the type annotations in
  12442. the program.
  12443. Regarding the translation of expressions, the case for \code{Inst} is
  12444. the interesting one. We translate it into a \code{Cast}, as shown
  12445. below. The type of the subexpression $e$ is the polymorphic type
  12446. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12447. $T$, the type $T'$. The target type $T''$ is the result of
  12448. substituting the arguments types $ts$ for the type parameters $xs$ in
  12449. $T$ followed by doing type erasure.
  12450. \begin{lstlisting}
  12451. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12452. |$\Rightarrow$|
  12453. (Cast |$e'$| |$T'$| |$T''$|)
  12454. \end{lstlisting}
  12455. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12456. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12457. Finally, each polymorphic function is translated to a regular
  12458. functions in which type erasure has been applied to all the type
  12459. annotations and the body.
  12460. \begin{lstlisting}
  12461. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12462. |$\Rightarrow$|
  12463. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12464. \end{lstlisting}
  12465. \begin{exercise}\normalfont
  12466. Implement a compiler for the polymorphic language \LangPoly{} by
  12467. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12468. programs that use polymorphic functions. Some of them should make
  12469. use of first-class polymorphism.
  12470. \end{exercise}
  12471. \begin{figure}[p]
  12472. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12473. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12474. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12475. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12476. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12477. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12478. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12479. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12480. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12481. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12482. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12483. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12484. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12485. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12486. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12487. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12488. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12489. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12490. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12491. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12492. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12493. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12494. \path[->,bend right=15] (Rpoly) edge [above] node
  12495. {\ttfamily\footnotesize type-check} (Rpolyp);
  12496. \path[->,bend right=15] (Rpolyp) edge [above] node
  12497. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12498. \path[->,bend right=15] (Rgradualp) edge [above] node
  12499. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12500. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12501. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12502. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12503. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12504. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12505. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12506. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12507. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12508. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12509. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12510. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12511. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12512. \path[->,bend left=15] (F1-1) edge [below] node
  12513. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12514. \path[->,bend right=15] (F1-2) edge [above] node
  12515. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12516. \path[->,bend right=15] (F1-3) edge [above] node
  12517. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12518. \path[->,bend right=15] (F1-4) edge [above] node
  12519. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12520. \path[->,bend right=15] (F1-5) edge [right] node
  12521. {\ttfamily\footnotesize explicate-control} (C3-2);
  12522. \path[->,bend left=15] (C3-2) edge [left] node
  12523. {\ttfamily\footnotesize select-instr.} (x86-2);
  12524. \path[->,bend right=15] (x86-2) edge [left] node
  12525. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12526. \path[->,bend right=15] (x86-2-1) edge [below] node
  12527. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12528. \path[->,bend right=15] (x86-2-2) edge [left] node
  12529. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12530. \path[->,bend left=15] (x86-3) edge [above] node
  12531. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12532. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12533. \end{tikzpicture}
  12534. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12535. \label{fig:Rpoly-passes}
  12536. \end{figure}
  12537. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12538. for the compilation of \LangPoly{}.
  12539. % TODO: challenge problem: specialization of instantiations
  12540. % Further Reading
  12541. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12542. \clearpage
  12543. \appendix
  12544. \chapter{Appendix}
  12545. \section{Interpreters}
  12546. \label{appendix:interp}
  12547. \index{subject}{interpreter}
  12548. We provide interpreters for each of the source languages \LangInt{},
  12549. \LangVar{}, $\ldots$ in the files \code{interp\_Rint.rkt},
  12550. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12551. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12552. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12553. and x86 are in the \key{interp.rkt} file.
  12554. \section{Utility Functions}
  12555. \label{appendix:utilities}
  12556. The utility functions described in this section are in the
  12557. \key{utilities.rkt} file of the support code.
  12558. \paragraph{\code{interp-tests}}
  12559. The \key{interp-tests} function runs the compiler passes and the
  12560. interpreters on each of the specified tests to check whether each pass
  12561. is correct. The \key{interp-tests} function has the following
  12562. parameters:
  12563. \begin{description}
  12564. \item[name (a string)] a name to identify the compiler,
  12565. \item[typechecker] a function of exactly one argument that either
  12566. raises an error using the \code{error} function when it encounters a
  12567. type error, or returns \code{\#f} when it encounters a type
  12568. error. If there is no type error, the type checker returns the
  12569. program.
  12570. \item[passes] a list with one entry per pass. An entry is a list with
  12571. four things:
  12572. \begin{enumerate}
  12573. \item a string giving the name of the pass,
  12574. \item the function that implements the pass (a translator from AST
  12575. to AST),
  12576. \item a function that implements the interpreter (a function from
  12577. AST to result value) for the output language,
  12578. \item and a type checker for the output language. Type checkers for
  12579. the $R$ and $C$ languages are provided in the support code. For
  12580. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12581. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12582. type checker entry is optional. The support code does not provide
  12583. type checkers for the x86 languages.
  12584. \end{enumerate}
  12585. \item[source-interp] an interpreter for the source language. The
  12586. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12587. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12588. \item[tests] a list of test numbers that specifies which tests to
  12589. run. (see below)
  12590. \end{description}
  12591. %
  12592. The \key{interp-tests} function assumes that the subdirectory
  12593. \key{tests} has a collection of Racket programs whose names all start
  12594. with the family name, followed by an underscore and then the test
  12595. number, ending with the file extension \key{.rkt}. Also, for each test
  12596. program that calls \code{read} one or more times, there is a file with
  12597. the same name except that the file extension is \key{.in} that
  12598. provides the input for the Racket program. If the test program is
  12599. expected to fail type checking, then there should be an empty file of
  12600. the same name but with extension \key{.tyerr}.
  12601. \paragraph{\code{compiler-tests}}
  12602. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12603. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12604. machine code and checks that the output is $42$. The parameters to the
  12605. \code{compiler-tests} function are similar to those of the
  12606. \code{interp-tests} function, and consist of
  12607. \begin{itemize}
  12608. \item a compiler name (a string),
  12609. \item a type checker,
  12610. \item description of the passes,
  12611. \item name of a test-family, and
  12612. \item a list of test numbers.
  12613. \end{itemize}
  12614. \paragraph{\code{compile-file}}
  12615. takes a description of the compiler passes (see the comment for
  12616. \key{interp-tests}) and returns a function that, given a program file
  12617. name (a string ending in \key{.rkt}), applies all of the passes and
  12618. writes the output to a file whose name is the same as the program file
  12619. name but with \key{.rkt} replaced with \key{.s}.
  12620. \paragraph{\code{read-program}}
  12621. takes a file path and parses that file (it must be a Racket program)
  12622. into an abstract syntax tree.
  12623. \paragraph{\code{parse-program}}
  12624. takes an S-expression representation of an abstract syntax tree and converts it into
  12625. the struct-based representation.
  12626. \paragraph{\code{assert}}
  12627. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12628. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12629. \paragraph{\code{lookup}}
  12630. % remove discussion of lookup? -Jeremy
  12631. takes a key and an alist, and returns the first value that is
  12632. associated with the given key, if there is one. If not, an error is
  12633. triggered. The alist may contain both immutable pairs (built with
  12634. \key{cons}) and mutable pairs (built with \key{mcons}).
  12635. %The \key{map2} function ...
  12636. \section{x86 Instruction Set Quick-Reference}
  12637. \label{sec:x86-quick-reference}
  12638. \index{subject}{x86}
  12639. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12640. do. We write $A \to B$ to mean that the value of $A$ is written into
  12641. location $B$. Address offsets are given in bytes. The instruction
  12642. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12643. registers (such as \code{\%rax}), or memory references (such as
  12644. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12645. reference per instruction. Other operands must be immediates or
  12646. registers.
  12647. \begin{table}[tbp]
  12648. \centering
  12649. \begin{tabular}{l|l}
  12650. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12651. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12652. \texttt{negq} $A$ & $- A \to A$ \\
  12653. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12654. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12655. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12656. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12657. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12658. \texttt{retq} & Pops the return address and jumps to it \\
  12659. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12660. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12661. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12662. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12663. be an immediate) \\
  12664. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12665. matches the condition code of the instruction, otherwise go to the
  12666. next instructions. The condition codes are \key{e} for ``equal'',
  12667. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12668. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12669. \texttt{jl} $L$ & \\
  12670. \texttt{jle} $L$ & \\
  12671. \texttt{jg} $L$ & \\
  12672. \texttt{jge} $L$ & \\
  12673. \texttt{jmp} $L$ & Jump to label $L$ \\
  12674. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12675. \texttt{movzbq} $A$, $B$ &
  12676. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12677. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12678. and the extra bytes of $B$ are set to zero.} \\
  12679. & \\
  12680. & \\
  12681. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12682. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12683. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12684. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12685. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12686. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12687. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12688. description of the condition codes. $A$ must be a single byte register
  12689. (e.g., \texttt{al} or \texttt{cl}).} \\
  12690. \texttt{setl} $A$ & \\
  12691. \texttt{setle} $A$ & \\
  12692. \texttt{setg} $A$ & \\
  12693. \texttt{setge} $A$ &
  12694. \end{tabular}
  12695. \vspace{5pt}
  12696. \caption{Quick-reference for the x86 instructions used in this book.}
  12697. \label{tab:x86-instr}
  12698. \end{table}
  12699. \cleardoublepage
  12700. \section{Concrete Syntax for Intermediate Languages}
  12701. The concrete syntax of \LangAny{} is defined in
  12702. Figure~\ref{fig:Rany-concrete-syntax}.
  12703. \begin{figure}[tp]
  12704. \centering
  12705. \fbox{
  12706. \begin{minipage}{0.97\textwidth}\small
  12707. \[
  12708. \begin{array}{lcl}
  12709. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12710. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12711. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12712. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12713. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12714. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12715. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12716. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12717. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12718. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12719. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12720. \mid \LP\key{void?}\;\Exp\RP \\
  12721. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12722. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12723. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  12724. \end{array}
  12725. \]
  12726. \end{minipage}
  12727. }
  12728. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12729. (Figure~\ref{fig:Rlam-syntax}).}
  12730. \label{fig:Rany-concrete-syntax}
  12731. \end{figure}
  12732. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12733. defined in Figures~\ref{fig:c0-concrete-syntax},
  12734. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12735. and \ref{fig:c3-concrete-syntax}, respectively.
  12736. \begin{figure}[tbp]
  12737. \fbox{
  12738. \begin{minipage}{0.96\textwidth}
  12739. \[
  12740. \begin{array}{lcl}
  12741. \Atm &::=& \Int \mid \Var \\
  12742. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12743. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12744. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12745. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12746. \end{array}
  12747. \]
  12748. \end{minipage}
  12749. }
  12750. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12751. \label{fig:c0-concrete-syntax}
  12752. \end{figure}
  12753. \begin{figure}[tbp]
  12754. \fbox{
  12755. \begin{minipage}{0.96\textwidth}
  12756. \small
  12757. \[
  12758. \begin{array}{lcl}
  12759. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12760. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12761. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12762. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12763. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12764. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12765. \mid \key{goto}~\itm{label}\key{;}\\
  12766. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12767. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12768. \end{array}
  12769. \]
  12770. \end{minipage}
  12771. }
  12772. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12773. \label{fig:c1-concrete-syntax}
  12774. \end{figure}
  12775. \begin{figure}[tbp]
  12776. \fbox{
  12777. \begin{minipage}{0.96\textwidth}
  12778. \small
  12779. \[
  12780. \begin{array}{lcl}
  12781. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12782. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12783. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12784. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12785. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12786. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12787. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12788. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12789. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12790. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12791. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12792. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12793. \end{array}
  12794. \]
  12795. \end{minipage}
  12796. }
  12797. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12798. \label{fig:c2-concrete-syntax}
  12799. \end{figure}
  12800. \begin{figure}[tp]
  12801. \fbox{
  12802. \begin{minipage}{0.96\textwidth}
  12803. \small
  12804. \[
  12805. \begin{array}{lcl}
  12806. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12807. \\
  12808. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12809. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12810. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12811. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12812. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12813. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12814. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12815. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12816. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12817. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12818. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12819. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12820. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12821. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12822. \LangCFunM{} & ::= & \Def\ldots
  12823. \end{array}
  12824. \]
  12825. \end{minipage}
  12826. }
  12827. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12828. \label{fig:c3-concrete-syntax}
  12829. \end{figure}
  12830. \backmatter
  12831. \addtocontents{toc}{\vspace{11pt}}
  12832. %% \addtocontents{toc}{\vspace{11pt}}
  12833. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  12834. \nocite{*}\let\bibname\refname
  12835. \addcontentsline{toc}{fmbm}{\refname}
  12836. \printbibliography
  12837. \printindex{authors}{Author Index}
  12838. \printindex{subject}{Subject Index}
  12839. \end{document}