book.tex 572 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM!, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \newcommand{\ocaml}[1]{{\color{blue}{#1}}}
  70. \newenvironment{ocamlx}{
  71. \begin{color}{blue}
  72. }
  73. {
  74. \end{color}
  75. }
  76. \definecolor{BLUE}{rgb}{0,0,1} % no idea why we need this
  77. \lstdefinestyle{racket}{
  78. language=Lisp,
  79. basicstyle=\ttfamily\small,
  80. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  81. deletekeywords={read,mapping,vector},
  82. escapechar=|,
  83. columns=flexible,
  84. moredelim=[is][\color{red}]{~}{~},
  85. showstringspaces=false
  86. }
  87. \lstset{style=racket}
  88. \lstdefinestyle{ocaml}{
  89. language=[Objective]Caml,
  90. basicstyle=\ttfamily\small\color{blue},
  91. columns=flexible,
  92. escapechar=~,
  93. showstringspaces=false
  94. }
  95. \newtheorem{theorem}{Theorem}
  96. \newtheorem{lemma}[theorem]{Lemma}
  97. \newtheorem{corollary}[theorem]{Corollary}
  98. \newtheorem{proposition}[theorem]{Proposition}
  99. \newtheorem{constraint}[theorem]{Constraint}
  100. \newtheorem{definition}[theorem]{Definition}
  101. \newtheorem{exercise}[theorem]{Exercise}
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % 'dedication' environment: To add a dedication paragraph at the start of book %
  104. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \newenvironment{dedication}
  107. {
  108. \cleardoublepage
  109. \thispagestyle{empty}
  110. \vspace*{\stretch{1}}
  111. \hfill\begin{minipage}[t]{0.66\textwidth}
  112. \raggedright
  113. }
  114. {
  115. \end{minipage}
  116. \vspace*{\stretch{3}}
  117. \clearpage
  118. }
  119. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  120. % Chapter quote at the start of chapter %
  121. % Source: http://tex.stackexchange.com/a/53380 %
  122. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  123. \makeatletter
  124. \renewcommand{\@chapapp}{}% Not necessary...
  125. \newenvironment{chapquote}[2][2em]
  126. {\setlength{\@tempdima}{#1}%
  127. \def\chapquote@author{#2}%
  128. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  129. \itshape}
  130. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  131. \makeatother
  132. \input{defs}
  133. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  134. \title{\Huge \textbf{Essentials of Compilation} \\
  135. \huge The Incremental, Nano-Pass Approach}
  136. \author{\textsc{Jeremy G. Siek} \\
  137. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  138. Indiana University \\
  139. \\
  140. with contributions from: \\
  141. Carl Factora \\
  142. Andre Kuhlenschmidt \\
  143. Ryan R. Newton \\
  144. Ryan Scott \\
  145. Cameron Swords \\
  146. Michael M. Vitousek \\
  147. Michael Vollmer \\
  148. \\
  149. \ocaml{OCaml version:} \\
  150. \ocaml{Andrew Tolmach} \\
  151. \ocaml{(with inspiration from a Haskell version by Ian Winter)}
  152. }
  153. \begin{document}
  154. \frontmatter
  155. \maketitle
  156. \begin{dedication}
  157. This book is dedicated to the programming language wonks at Indiana
  158. University.
  159. \end{dedication}
  160. \tableofcontents
  161. \listoffigures
  162. %\listoftables
  163. \mainmatter
  164. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  165. \chapter*{Preface}
  166. There is a magical moment when a programmer presses the ``run'' button
  167. and the software begins to execute. Somehow a program written in a
  168. high-level language is running on a computer that is only capable of
  169. shuffling bits. Here we reveal the wizardry that makes that moment
  170. possible. Beginning with the groundbreaking work of Backus and
  171. colleagues in the 1950s, computer scientists discovered techniques for
  172. constructing programs, called \emph{compilers}, that automatically
  173. translate high-level programs into machine code.
  174. We take you on a journey by constructing your own compiler for a small
  175. but powerful language. Along the way we explain the essential
  176. concepts, algorithms, and data structures that underlie compilers. We
  177. develop your understanding of how programs are mapped onto computer
  178. hardware, which is helpful when reasoning about properties at the
  179. junction between hardware and software such as execution time,
  180. software errors, and security vulnerabilities. For those interested
  181. in pursuing compiler construction, our goal is to provide a
  182. stepping-stone to advanced topics such as just-in-time compilation,
  183. program analysis, and program optimization. For those interested in
  184. designing and implementing their own programming languages, we connect
  185. language design choices to their impact on the compiler its generated
  186. code.
  187. A compiler is typically organized as a sequence of stages that
  188. progressively translates a program to code that runs on hardware. We
  189. take this approach to the extreme by partitioning our compiler into a
  190. large number of \emph{nanopasses}, each of which performs a single
  191. task. This allows us to test the output of each pass in isolation, and
  192. furthermore, allows us to focus our attention making the compiler far
  193. easier to understand.
  194. %% [TODO: easier to understand/debug for those maintaining the compiler,
  195. %% proving correctness]
  196. The most familiar approach to describing compilers is with one pass
  197. per chapter. The problem with that is it obfuscates how language
  198. features motivate design choices in a compiler. We take an
  199. \emph{incremental} approach in which we build a complete compiler in
  200. each chapter, starting with arithmetic and variables and add new
  201. features in subsequent chapters.
  202. Our choice of language features is designed to elicit the fundamental
  203. concepts and algorithms used in compilers.
  204. \begin{itemize}
  205. \item We begin with integer arithmetic and local variables in
  206. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  207. the fundamental tools of compiler construction: \emph{abstract
  208. syntax trees} and \emph{recursive functions}.
  209. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  210. \emph{graph coloring} to assign variables to machine registers.
  211. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  212. an elegant recursive algorithm for mapping expressions to
  213. \emph{control-flow graphs}.
  214. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  215. \emph{garbage collection}.
  216. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  217. but lack lexical scoping, similar to the C programming
  218. language~\citep{Kernighan:1988nx} except that we generate efficient
  219. tail calls. The reader learns about the procedure call stack,
  220. \emph{calling conventions}, and their interaction with register
  221. allocation and garbage collection.
  222. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  223. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  224. \emph{closure conversion}, in which lambdas are translated into a
  225. combination of functions and tuples.
  226. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  227. point the input languages are statically typed. The reader extends
  228. the statically typed language with an \code{Any} type which serves
  229. as a target for compiling the dynamically typed language.
  230. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  231. programming languages with the addition of loops and mutable
  232. variables. These additions elicit the need for \emph{dataflow
  233. analysis} in the register allocator.
  234. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  235. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  236. in which different regions of a program may be static or dynamically
  237. typed. The reader implements runtime support for \emph{proxies} that
  238. allow values to safely move between regions.
  239. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  240. leveraging the \code{Any} type and type casts developed in Chapters
  241. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  242. \end{itemize}
  243. There are many language features that we do not include. Our choices
  244. weigh the incidental complexity of a feature against the fundamental
  245. concepts that it exposes. For example, we include tuples and not
  246. records because they both elicit the study of heap allocation and
  247. garbage collection but records come with more incidental complexity.
  248. Since 2016 this book has served as the textbook for the compiler
  249. course at Indiana University, a 16-week course for upper-level
  250. undergraduates and first-year graduate students.
  251. %
  252. Prior to this course, students learn to program in both imperative and
  253. functional languages, study data structures and algorithms, and take
  254. discrete mathematics.
  255. %
  256. At the beginning of the course, students form groups of 2-4 people.
  257. The groups complete one chapter every two weeks, starting with
  258. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  259. chapters include a challenge problem that we assign to the graduate
  260. students. The last two weeks of the course involve a final project in
  261. which students design and implement a compiler extension of their
  262. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  263. \ref{ch:Rpoly} can be used in support of these projects or they can
  264. replace some of the earlier chapters. For example, a course with an
  265. emphasis on statically-typed imperative languages would skip
  266. Chapter~\ref{ch:Rdyn} in favor of
  267. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  268. the dependencies between chapters.
  269. This book has also been used in compiler courses at California
  270. Polytechnic State University, Rose–Hulman Institute of Technology, and
  271. University of Massachusetts Lowell.
  272. \begin{figure}[tp]
  273. \begin{tikzpicture}[baseline=(current bounding box.center)]
  274. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  275. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  276. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  277. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  278. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  279. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  280. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  281. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  282. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  283. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  284. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  285. \path[->] (C1) edge [above] node {} (C2);
  286. \path[->] (C2) edge [above] node {} (C3);
  287. \path[->] (C3) edge [above] node {} (C4);
  288. \path[->] (C4) edge [above] node {} (C5);
  289. \path[->] (C5) edge [above] node {} (C6);
  290. \path[->] (C6) edge [above] node {} (C7);
  291. \path[->] (C4) edge [above] node {} (C8);
  292. \path[->] (C4) edge [above] node {} (C9);
  293. \path[->] (C8) edge [above] node {} (C10);
  294. \path[->] (C10) edge [above] node {} (C11);
  295. \end{tikzpicture}
  296. \caption{Diagram of chapter dependencies.}
  297. \label{fig:chapter-dependences}
  298. \end{figure}
  299. We use the \href{https://racket-lang.org/}{Racket} language both for
  300. the implementation of the compiler and for the input language, so the
  301. reader should be proficient with Racket or Scheme. There are many
  302. excellent resources for learning Scheme and
  303. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  304. support code for this book is in the \code{github} repository at the
  305. following URL:
  306. \begin{center}\small
  307. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  308. \end{center}
  309. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  310. is helpful but not necessary for the reader to have taken a computer
  311. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  312. of x86-64 assembly language that are needed.
  313. %
  314. We follow the System V calling
  315. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  316. that we generate works with the runtime system (written in C) when it
  317. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  318. operating systems.
  319. %
  320. On the Windows operating system, \code{gcc} uses the Microsoft x64
  321. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  322. assembly code that we generate does \emph{not} work with the runtime
  323. system on Windows. One workaround is to use a virtual machine with
  324. Linux as the guest operating system.
  325. \section*{Acknowledgments}
  326. The tradition of compiler construction at Indiana University goes back
  327. to research and courses on programming languages by Daniel Friedman in
  328. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  329. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  330. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  331. the compiler course and continued the development of Chez Scheme.
  332. %
  333. The compiler course evolved to incorporate novel pedagogical ideas
  334. while also including elements of efficient real-world compilers. One
  335. of Friedman's ideas was to split the compiler into many small
  336. passes. Another idea, called ``the game'', was to test the code
  337. generated by each pass on interpreters.
  338. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  339. developed infrastructure to support this approach and evolved the
  340. course to use even smaller
  341. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  342. design decisions in this book are inspired by the assignment
  343. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  344. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  345. organization of the course made it difficult for students to
  346. understand the rationale for the compiler design. Ghuloum proposed the
  347. incremental approach~\citep{Ghuloum:2006bh}.
  348. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  349. Nystrom, and Michael Wollowski for teaching courses based on early
  350. drafts.
  351. We thank Ronald Garcia for being Jeremy's partner when they took the
  352. compiler course in the early 2000's and especially for finding the bug
  353. that sent the garbage collector on a wild goose chase!
  354. \mbox{}\\
  355. \noindent Jeremy G. Siek \\
  356. Bloomington, Indiana
  357. %Oscar Waddell ??
  358. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  359. \chapter{Preliminaries}
  360. \label{ch:trees-recur}
  361. \begin{ocamlx}
  362. Text in blue, like this, represents additions to the original book
  363. text to support the use of OCaml rather than Racket as our compiler
  364. implementation language. The original text is never changed, so you
  365. can see both the Racket and OCaml versions in parallel. The main
  366. motivation for this is to save a lot of rote editing: the bulk of
  367. the story being told in this book is substantially the same
  368. regardless of implementation language, so most of what has been
  369. written about the Racket version applies directly to OCaml
  370. with just small mental adjustments between the syntaxes of the two
  371. languages. A secondary motivation is that it is sometimes easier to
  372. see key underlying ideas when they are expressed in more than one
  373. way.
  374. In many respects, Racket and OCaml are very similar languages: they
  375. both encourage a purely functional style of programming while also supporting
  376. imperative programming, provide higher-order functions, use
  377. garbage collection to guarantee memory safety, etc. Indeed, the
  378. ``back ends'' of Racket and OCaml implementations are nearly
  379. interchangeable. By far the most fundamental difference between them is
  380. that OCaml uses static typing, whereas Racket uses runtime typing.
  381. The latter can provide useful flexibility, but the former has the
  382. big advantage of providing compile-time feedback on type errors.
  383. This is our main motivation for using OCaml.
  384. \end{ocamlx}
  385. In this chapter we review the basic tools that are needed to implement
  386. a compiler. Programs are typically input by a programmer as text,
  387. i.e., a sequence of characters. The program-as-text representation is
  388. called \emph{concrete syntax}. We use concrete syntax to concisely
  389. write down and talk about programs. Inside the compiler, we use
  390. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  391. that efficiently supports the operations that the compiler needs to
  392. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  393. syntax tree}\index{AST}\index{program}\index{parse} The translation
  394. from concrete syntax to abstract syntax is a process called
  395. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  396. implementation of parsing in this book. A parser is provided in the
  397. support code for translating from concrete to abstract syntax.
  398. ASTs can be represented in many different ways inside the compiler,
  399. depending on the programming language used to write the compiler.
  400. %
  401. We use Racket's
  402. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  403. feature to represent ASTs (Section~\ref{sec:ast}).
  404. \ocaml{OCaml: we use \emph{variants} (also called algebraic data types) to
  405. represent ASTs.}
  406. We use grammars to
  407. define the abstract syntax of programming languages
  408. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  409. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  410. recursive functions to construct and deconstruct ASTs
  411. (Section~\ref{sec:recursion}). This chapter provides an brief
  412. introduction to these ideas. \index{struct}
  413. \section{Abstract Syntax Trees and Racket Structures \ocaml{/ OCaml Variants}}
  414. \label{sec:ast}
  415. Compilers use abstract syntax trees to represent programs because they
  416. often need to ask questions like: for a given part of a program, what
  417. kind of language feature is it? What are its sub-parts? Consider the
  418. program on the left and its AST on the right.
  419. \begin{ocamlx}
  420. This program is
  421. itself in Racket; in addition to using Racket as the compiler implementation
  422. language, the original version of this book uses subsets of Racket as the
  423. \emph{source} languages that we compile. In the OCaml version we will be using
  424. ad-hoc source languages that look a lot like subsets of Racket, but sometimes
  425. made simpler (because there is no particular advantage to matching the messier details
  426. of Racket syntax). The code on the left will be valid in all of our source languages too.
  427. \end{ocamlx}
  428. This program is an
  429. addition operation and it has two sub-parts, a read operation and a
  430. negation. The negation has another sub-part, the integer constant
  431. \code{8}. By using a tree to represent the program, we can easily
  432. follow the links to go from one part of a program to its sub-parts.
  433. \begin{center}
  434. \begin{minipage}{0.4\textwidth}
  435. \begin{lstlisting}
  436. (+ (read) (- 8))
  437. \end{lstlisting}
  438. \end{minipage}
  439. \begin{minipage}{0.4\textwidth}
  440. \begin{equation}
  441. \begin{tikzpicture}
  442. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  443. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  444. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  445. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  446. \draw[->] (plus) to (read);
  447. \draw[->] (plus) to (minus);
  448. \draw[->] (minus) to (8);
  449. \end{tikzpicture}
  450. \label{eq:arith-prog}
  451. \end{equation}
  452. \end{minipage}
  453. \end{center}
  454. We use the standard terminology for trees to describe ASTs: each
  455. circle above is called a \emph{node}. The arrows connect a node to its
  456. \emph{children} (which are also nodes). The top-most node is the
  457. \emph{root}. Every node except for the root has a \emph{parent} (the
  458. node it is the child of). If a node has no children, it is a
  459. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  460. \index{node}
  461. \index{children}
  462. \index{root}
  463. \index{parent}
  464. \index{leaf}
  465. \index{internal node}
  466. %% Recall that an \emph{symbolic expression} (S-expression) is either
  467. %% \begin{enumerate}
  468. %% \item an atom, or
  469. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  470. %% where $e_1$ and $e_2$ are each an S-expression.
  471. %% \end{enumerate}
  472. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  473. %% null value \code{'()}, etc. We can create an S-expression in Racket
  474. %% simply by writing a backquote (called a quasi-quote in Racket)
  475. %% followed by the textual representation of the S-expression. It is
  476. %% quite common to use S-expressions to represent a list, such as $a, b
  477. %% ,c$ in the following way:
  478. %% \begin{lstlisting}
  479. %% `(a . (b . (c . ())))
  480. %% \end{lstlisting}
  481. %% Each element of the list is in the first slot of a pair, and the
  482. %% second slot is either the rest of the list or the null value, to mark
  483. %% the end of the list. Such lists are so common that Racket provides
  484. %% special notation for them that removes the need for the periods
  485. %% and so many parenthesis:
  486. %% \begin{lstlisting}
  487. %% `(a b c)
  488. %% \end{lstlisting}
  489. %% The following expression creates an S-expression that represents AST
  490. %% \eqref{eq:arith-prog}.
  491. %% \begin{lstlisting}
  492. %% `(+ (read) (- 8))
  493. %% \end{lstlisting}
  494. %% When using S-expressions to represent ASTs, the convention is to
  495. %% represent each AST node as a list and to put the operation symbol at
  496. %% the front of the list. The rest of the list contains the children. So
  497. %% in the above case, the root AST node has operation \code{`+} and its
  498. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  499. %% diagram \eqref{eq:arith-prog}.
  500. %% To build larger S-expressions one often needs to splice together
  501. %% several smaller S-expressions. Racket provides the comma operator to
  502. %% splice an S-expression into a larger one. For example, instead of
  503. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  504. %% we could have first created an S-expression for AST
  505. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  506. %% S-expression.
  507. %% \begin{lstlisting}
  508. %% (define ast1.4 `(- 8))
  509. %% (define ast1.1 `(+ (read) ,ast1.4))
  510. %% \end{lstlisting}
  511. %% In general, the Racket expression that follows the comma (splice)
  512. %% can be any expression that produces an S-expression.
  513. We define a Racket \code{struct} for each kind of node. For this
  514. chapter we require just two kinds of nodes: one for integer constants
  515. and one for primitive operations. The following is the \code{struct}
  516. definition for integer constants.
  517. \begin{lstlisting}
  518. (struct Int (value))
  519. \end{lstlisting}
  520. An integer node includes just one thing: the integer value.
  521. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  522. \begin{lstlisting}
  523. (define eight (Int 8))
  524. \end{lstlisting}
  525. We say that the value created by \code{(Int 8)} is an
  526. \emph{instance} of the \code{Int} structure.
  527. The following is the \code{struct} definition for primitives operations.
  528. \begin{lstlisting}
  529. (struct Prim (op args))
  530. \end{lstlisting}
  531. A primitive operation node includes an operator symbol \code{op}
  532. and a list of children \code{args}. For example, to create
  533. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  534. \begin{lstlisting}
  535. (define neg-eight (Prim '- (list eight)))
  536. \end{lstlisting}
  537. Primitive operations may have zero or more children. The \code{read}
  538. operator has zero children:
  539. \begin{lstlisting}
  540. (define rd (Prim 'read '()))
  541. \end{lstlisting}
  542. whereas the addition operator has two children:
  543. \begin{lstlisting}
  544. (define ast1.1 (Prim '+ (list rd neg-eight)))
  545. \end{lstlisting}
  546. \begin{ocamlx}
  547. We define an OCaml variant type for ASTs, with a different constructor for each
  548. kind of node:
  549. \begin{lstlisting}[style=ocaml]
  550. type exp =
  551. Int of int
  552. | Prim of primop * exp list
  553. \end{lstlisting}
  554. This definition depends on the definition of another variant type that enumerates the possible primops
  555. (in place of the single-quoted symbols used in Racket):
  556. \begin{lstlisting}[style=ocaml]
  557. type primop =
  558. Read
  559. | Neg
  560. | Add
  561. \end{lstlisting}
  562. To create an AST node for the integer 8, we write \code{Int 8}.
  563. To create an AST that negates
  564. the number 8, we write \code{Prim(Neg,[Int 8])}, and so on:
  565. \begin{lstlisting}[style=ocaml]
  566. let eight = Int 8
  567. let neg_eight = Prim(Neg,[eight])
  568. let rd = Prim(Read,[])
  569. let ast1_1 = Prim(Add,[rd,neg_eight])
  570. \end{lstlisting}
  571. Note that OCaml identifiers are more restricted in form than those of Racket; we will typically replace uses of dash (\code{-}), dot (\code{.}), etc. by underscores (\code{\_}).
  572. \end{ocamlx}
  573. We have made a design choice regarding the \code{Prim} structure.
  574. Instead of using one structure for many different operations
  575. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  576. structure for each operation, as follows.
  577. \begin{lstlisting}
  578. (struct Read ())
  579. (struct Add (left right))
  580. (struct Neg (value))
  581. \end{lstlisting}
  582. The reason we choose to use just one structure is that in many parts
  583. of the compiler the code for the different primitive operators is the
  584. same, so we might as well just write that code once, which is enabled
  585. by using a single structure.
  586. \begin{ocamlx}
  587. We have made a similar design choice in OCaml. The corresponding
  588. alternative would have been to define our AST type as
  589. \begin{lstlisting}[style=ocaml]
  590. type exp =
  591. Int of int
  592. | Read
  593. | Add of exp * exp
  594. | Neg of exp
  595. \end{lstlisting}
  596. Note that one advantage of using this alternative is that it would explicitly enforce
  597. that each primitive operator is given the correct number of arguments (its \emph{arity});
  598. this restriction is not captured in the list-based version.
  599. \end{ocamlx}
  600. When compiling a program such as \eqref{eq:arith-prog}, we need to
  601. know that the operation associated with the root node is addition and
  602. we need to be able to access its two children. Racket provides pattern
  603. matching to support these kinds of queries, as we see in
  604. Section~\ref{sec:pattern-matching}. \ocaml{So does OCaml.}
  605. In this book, we often write down the concrete syntax of a program
  606. even when we really have in mind the AST because the concrete syntax
  607. is more concise. We recommend that, in your mind, you always think of
  608. programs as abstract syntax trees.
  609. \section{Grammars}
  610. \label{sec:grammar}
  611. \index{integer}
  612. \index{literal}
  613. \index{constant}
  614. A programming language can be thought of as a \emph{set} of programs.
  615. The set is typically infinite (one can always create larger and larger
  616. programs), so one cannot simply describe a language by listing all of
  617. the programs in the language. Instead we write down a set of rules, a
  618. \emph{grammar}, for building programs. Grammars are often used to
  619. define the concrete syntax of a language, but they can also be used to
  620. describe the abstract syntax. We write our rules in a variant of
  621. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  622. \index{Backus-Naur Form}\index{BNF}
  623. As an example, we describe a small language, named \LangInt{}, that consists of
  624. integers and arithmetic operations.
  625. \index{grammar}
  626. \begin{ocamlx}
  627. Using a grammar to describe abstract syntax is less useful in OCaml than in
  628. Racket, because our variant type definition for ASTs already serves to specify
  629. the legal forms of tree (except that it is overly flexible about the arity of
  630. primops, as mentioned above). So don't worry too much about the details of
  631. the AST grammar here---but do make sure you understand how the same ideas
  632. are applied to \emph{concrete} grammars, below.
  633. \end{ocamlx}
  634. The first grammar rule for the abstract syntax of \LangInt{} says that an
  635. instance of the \code{Int} structure is an expression:
  636. \begin{equation}
  637. \Exp ::= \INT{\Int} \label{eq:arith-int}
  638. \end{equation}
  639. %
  640. Each rule has a left-hand-side and a right-hand-side. The way to read
  641. a rule is that if you have an AST node that matches the
  642. right-hand-side, then you can categorize it according to the
  643. left-hand-side.
  644. %
  645. A name such as $\Exp$ that is defined by the grammar rules is a
  646. \emph{non-terminal}. \index{non-terminal}
  647. %
  648. The name $\Int$ is a also a non-terminal, but instead of defining it
  649. with a grammar rule, we define it with the following explanation. We
  650. make the simplifying design decision that all of the languages in this
  651. book only handle machine-representable integers. On most modern
  652. machines this corresponds to integers represented with 64-bits, i.e.,
  653. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  654. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  655. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  656. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  657. that the sequence of decimals represent an integer in range $-2^{62}$
  658. to $2^{62}-1$.
  659. \ocaml{As it happens, OCaml's standard integer type
  660. (\code{int}) is also 63 bits on a 64-bit machine. Initially, we
  661. will adopt the corresponding convention that $\Int$ is a 63-bit integer,
  662. but soon we will move to full 64-bit integers.}
  663. The second grammar rule is the \texttt{read} operation that receives
  664. an input integer from the user of the program.
  665. \begin{equation}
  666. \Exp ::= \READ{} \label{eq:arith-read}
  667. \end{equation}
  668. The third rule says that, given an $\Exp$ node, the negation of that
  669. node is also an $\Exp$.
  670. \begin{equation}
  671. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  672. \end{equation}
  673. Symbols in typewriter font such as \key{-} and \key{read} are
  674. \emph{terminal} symbols and must literally appear in the program for
  675. the rule to be applicable.
  676. \index{terminal}
  677. We can apply these rules to categorize the ASTs that are in the
  678. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  679. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  680. following AST is an $\Exp$.
  681. \begin{center}
  682. \begin{minipage}{0.4\textwidth}
  683. \begin{lstlisting}
  684. (Prim '- (list (Int 8)))
  685. \end{lstlisting}
  686. \end{minipage}
  687. \begin{minipage}{0.25\textwidth}
  688. \begin{equation}
  689. \begin{tikzpicture}
  690. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  691. \node[draw, circle] (8) at (0, -1.2) {$8$};
  692. \draw[->] (minus) to (8);
  693. \end{tikzpicture}
  694. \label{eq:arith-neg8}
  695. \end{equation}
  696. \end{minipage}
  697. \end{center}
  698. \begin{ocamlx}
  699. The corresponding OCaml AST expression is \code{Prim(Neg,[Int 8])}.
  700. \end{ocamlx}
  701. The next grammar rule is for addition expressions:
  702. \begin{equation}
  703. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  704. \end{equation}
  705. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  706. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  707. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  708. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  709. to show that
  710. \begin{lstlisting}
  711. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  712. \end{lstlisting}
  713. is an $\Exp$ in the \LangInt{} language.
  714. \ocaml{\\ OCaml: \code{Prim(Add,[Prim(Read,[]);Prim(Neg,[Int 8])])}.}
  715. If you have an AST for which the above rules do not apply, then the
  716. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  717. is not in \LangInt{} because there are no rules for \code{+} with only one
  718. argument, nor for \key{-} with two arguments. Whenever we define a
  719. language with a grammar, the language only includes those programs
  720. that are justified by the rules.
  721. The last grammar rule for \LangInt{} states that there is a \code{Program}
  722. node to mark the top of the whole program:
  723. \[
  724. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  725. \]
  726. The \code{Program} structure is defined as follows
  727. \begin{lstlisting}
  728. (struct Program (info body))
  729. \end{lstlisting}
  730. where \code{body} is an expression. In later chapters, the \code{info}
  731. part will be used to store auxiliary information but for now it is
  732. just the empty list.
  733. \begin{ocamlx}
  734. In OCaml:
  735. \begin{lstlisting}[style=ocaml]
  736. type 'info program = Program of 'info * exp
  737. \end{lstlisting}
  738. Again, we represent the structure as a variant type
  739. (\code{rint\_program}), this time just with one constructor
  740. (\code{Program)}. We \emph{parameterize} \code{program} by a
  741. \emph{type variable} \code{'info} (type variables are distinguished by having
  742. a leading tick mark). This says that \code{rint\_program} is a family of types which can
  743. be instantiated to represent programs holding a particular kind of auxiliary information.
  744. For now, we'll just instantiate \code{'info}
  745. with the \emph{unit} type, written \code{unit}, whose sole (boring)
  746. value is written \code{()}.
  747. \begin{lstlisting}[style=ocaml]
  748. let p : unit program = Program () body
  749. \end{lstlisting}
  750. Here the colon (\code{:}) introduces an explicit type annotation on \code{p}; it can be read ``has type.''
  751. \end{ocamlx}
  752. It is common to have many grammar rules with the same left-hand side
  753. but different right-hand sides, such as the rules for $\Exp$ in the
  754. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  755. combine several right-hand-sides into a single rule.
  756. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  757. in Figure~\ref{fig:r0-syntax} \ocaml{along with the corresponding OCaml type definitions}.
  758. The concrete syntax for \LangInt{} is
  759. defined in Figure~\ref{fig:r0-concrete-syntax}.
  760. The \code{read-program} function provided in \code{utilities.rkt} of
  761. the support code reads a program in from a file (the sequence of
  762. characters in the concrete syntax of Racket) and parses it into an
  763. abstract syntax tree. See the description of \code{read-program} in
  764. Appendix~\ref{appendix:utilities} for more details.
  765. \begin{ocamlx}
  766. As noted above, the concrete syntaxes we will use are similar to Racket's own syntax.
  767. In particular, programs are described as \emph{S-expressions}. An S-expression can be
  768. either an atom (an integer, symbol, or quoted string) or a list of S-expressions enclosed in
  769. parentheses. You can see that the concrete syntax for \LangInt{} is written as
  770. S-expressions where the symbols used are \code{read},\code{-}, and \code{+}, and
  771. a primitive operation invocation is described by a list whose first element is
  772. the operation symbol and whose remaining elements (0 or more of them) are
  773. S-expressions representing the arguments (which can themselves be lists).
  774. All the source languages we consider in this book will be written as S-expressions in
  775. a similar style; the details of which symbols and shapes of list are allowed
  776. will vary from language to language.
  777. To handle all this neatly in OCaml, we split the parsing of concrete
  778. programs into two phases. First, the \code{parse} function provided
  779. in \code{sexpr.ml} of the support code reads text from a file and
  780. parses it into a generic S-expression data type. (This code is a
  781. bit complicated and messy, but you don't have to understand its
  782. internals in order to use it.) Then, a source-language-specific
  783. program is used to convert the S-expression into the abstract syntax
  784. of that particular language. We will see later on that OCaml's pattern
  785. matching facilities make it very easy to write such conversion
  786. routines. This is particularly true because the S-expression format
  787. we use for our concrete source languages is already very close to an
  788. abstract syntax, which means the conversion has very little work to
  789. do. For example, as you have seen, primitive operations are all
  790. written in prefix, rather than infix, notation, so there is no need
  791. to worry about issues like precedence and associativity of operators
  792. in an expression like \code{(2 * 3 + 4)}: the S-expression syntax
  793. will be either \code{(+ (* 2 3) 4)} or \code{(* 2 (+ 3 4))}, so
  794. there is no possible ambiguity. The downside is that source programs
  795. are a bit more tedious to write, and may sometimes seem to be drowning in
  796. parentheses.
  797. The OCaml representation of generic S-expressions is just another
  798. variant type:
  799. \begin{lstlisting}[style=ocaml]
  800. type sexp =
  801. | SList of sexp list
  802. (* list of expressions delimited by parentheses *)
  803. | SNum of Int64.t
  804. (* 64-bit integers *)
  805. | SSym of string
  806. (* character sequence starting with non-digit,
  807. delimited by white space *)
  808. | SString of string
  809. (* arbitrary character sequence delimited by double quotes *)
  810. \end{lstlisting}
  811. The generic S-expression parser handles (nestable) comments delimited by
  812. curly braces (\code{\{} and \code{\}}). Symbols must start with a non-digit
  813. character and can contain any
  814. non-whitespace characters except parentheses, curly braces, and
  815. the back tick (\code{\`}); this last exclusion is handy when we want to
  816. generate internal names during compilation and be sure they don't clash
  817. with a user-defined symbol.
  818. \end{ocamlx}
  819. \begin{figure}[tp]
  820. \fbox{
  821. \begin{minipage}{0.96\textwidth}
  822. \[
  823. \begin{array}{rcl}
  824. \begin{array}{rcl}
  825. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  826. \LangInt{} &::=& \Exp
  827. \end{array}
  828. \end{array}
  829. \]
  830. \end{minipage}
  831. }
  832. \caption{The concrete syntax of \LangInt{}.}
  833. \label{fig:r0-concrete-syntax}
  834. \end{figure}
  835. \begin{figure}[tp]
  836. \fbox{
  837. \begin{minipage}{0.96\textwidth}
  838. \[
  839. \begin{array}{rcl}
  840. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  841. &\mid& \ADD{\Exp}{\Exp} \\
  842. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  843. \end{array}
  844. \]
  845. \end{minipage}
  846. }
  847. \begin{minipage}{0.96\textwidth}
  848. \begin{lstlisting}[style=ocaml,frame=single]
  849. type primop =
  850. Read
  851. | Neg
  852. | Add
  853. type exp =
  854. Int of int
  855. | Prim of primop * exp list
  856. type 'info program = Program of 'info * exp
  857. \end{lstlisting}
  858. \end{minipage}
  859. \caption{The abstract syntax of \LangInt{}.}
  860. \label{fig:r0-syntax}
  861. \end{figure}
  862. \section{Pattern Matching}
  863. \label{sec:pattern-matching}
  864. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  865. the parts of an AST node. Racket provides the \texttt{match} form to
  866. access the parts of a structure. Consider the following example and
  867. the output on the right. \index{match} \index{pattern matching}
  868. \begin{center}
  869. \begin{minipage}{0.5\textwidth}
  870. \begin{lstlisting}
  871. (match ast1.1
  872. [(Prim op (list child1 child2))
  873. (print op)])
  874. \end{lstlisting}
  875. \end{minipage}
  876. \vrule
  877. \begin{minipage}{0.25\textwidth}
  878. \begin{lstlisting}
  879. '+
  880. \end{lstlisting}
  881. \end{minipage}
  882. \end{center}
  883. In the above example, the \texttt{match} form takes an AST
  884. \eqref{eq:arith-prog} and binds its parts to the three pattern
  885. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  886. prints out the operator. In general, a match clause consists of a
  887. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  888. recursively defined to be either a pattern variable, a structure name
  889. followed by a pattern for each of the structure's arguments, or an
  890. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  891. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  892. and Chapter 9 of The Racket
  893. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  894. for a complete description of \code{match}.)
  895. %
  896. The body of a match clause may contain arbitrary Racket code. The
  897. pattern variables can be used in the scope of the body, such as
  898. \code{op} in \code{(print op)}.
  899. \begin{ocamlx}
  900. Here is the OCaml version, which is quite similar:
  901. \begin{center}
  902. \begin{minipage}{0.5\textwidth}
  903. \begin{lstlisting}[style=ocaml]
  904. match ast1_1 with
  905. | Prim(op,[child1;child2]) -> op
  906. \end{lstlisting}
  907. \end{minipage}
  908. \vrule
  909. \begin{minipage}{0.25\textwidth}
  910. \begin{lstlisting}[style=ocaml]
  911. Add
  912. \end{lstlisting}
  913. \end{minipage}
  914. \end{center}
  915. \end{ocamlx}
  916. A \code{match} form may contain several clauses, as in the following
  917. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  918. the AST. The \code{match} proceeds through the clauses in order,
  919. checking whether the pattern can match the input AST. The body of the
  920. first clause that matches is executed.
  921. \begin{ocamlx}
  922. In fact, in OCaml, we will get a warning message about the code above, because the \code{match} only contains
  923. a clause for a {\tt Prim} with two children, not for other other possible forms of \code{exp}.
  924. Although in this particular instance, that's OK (because of the value of \code{ast1\_1}), in general
  925. it suggests a possible error. Getting warnings like this is one of the advantages of static typing.
  926. \end{ocamlx}
  927. The output of \code{leaf?} for
  928. several ASTs is shown on the right.
  929. \begin{center}
  930. \begin{minipage}{0.6\textwidth}
  931. \begin{lstlisting}
  932. (define (leaf? arith)
  933. (match arith
  934. [(Int n) #t]
  935. [(Prim 'read '()) #t]
  936. [(Prim '- (list e1)) #f]
  937. [(Prim '+ (list e1 e2)) #f]))
  938. (leaf? (Prim 'read '()))
  939. (leaf? (Prim '- (list (Int 8))))
  940. (leaf? (Int 8))
  941. \end{lstlisting}
  942. \end{minipage}
  943. \vrule
  944. \begin{minipage}{0.25\textwidth}
  945. \begin{lstlisting}
  946. #t
  947. #f
  948. #t
  949. \end{lstlisting}
  950. \end{minipage}
  951. \end{center}
  952. When writing a \code{match}, we refer to the grammar definition to
  953. identify which non-terminal we are expecting to match against, then we
  954. make sure that 1) we have one clause for each alternative of that
  955. non-terminal and 2) that the pattern in each clause corresponds to the
  956. corresponding right-hand side of a grammar rule. For the \code{match}
  957. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  958. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  959. alternatives, so the \code{match} has 4 clauses. The pattern in each
  960. clause corresponds to the right-hand side of a grammar rule. For
  961. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  962. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  963. patterns, replace non-terminals such as $\Exp$ with pattern variables
  964. of your choice (e.g. \code{e1} and \code{e2}).
  965. \begin{ocamlx}
  966. Here is the directly corresponding OCaml version.
  967. \begin{center}
  968. \begin{minipage}{0.6\textwidth}
  969. \begin{lstlisting}[style=ocaml]
  970. let is_leaf arith =
  971. match arith with
  972. | Int n -> true
  973. | Prim(Read,[]) -> true
  974. | Prim(Neg,[e1]) -> false
  975. | Prim(Add,[e1;e2]) -> false
  976. | _ -> assert false
  977. is_leaf (Prim(Read,[]))
  978. is_leaf (Prim(Neg,[Int 8]))
  979. is_leaf (Int 8)
  980. \end{lstlisting}
  981. \end{minipage}
  982. \vrule
  983. \begin{minipage}{0.25\textwidth}
  984. \begin{lstlisting}[style=ocaml]
  985. true
  986. false
  987. true
  988. \end{lstlisting}
  989. \end{minipage}
  990. \end{center}
  991. The final clause uses a wildcard pattern {\tt \_}, which matches anything of type \code{exp},
  992. to cover the (ill-formed) cases where a primop is given the wrong number of arguments;
  993. otherwise, the compiler will again issue a warning that not all cases have been considered.
  994. The \code{assert false} causes OCaml execution to halt with an uncaught exception message.
  995. In this particular case, we can use wildcards to write a more idiomatic version of
  996. \code{is\_leaf} that doesn't require a catch-all case (and is also ``future-proof''
  997. against later additions to the \code{primop} type). We also make use of the following
  998. short-cut: a function that takes an argument $arg$ and then immediately performs
  999. a \code{match} over $arg$ can be written more concisely using the \code{function} keyword.
  1000. \begin{center}
  1001. \begin{minipage}{0.5\textwidth}
  1002. \begin{lstlisting}[style=ocaml]
  1003. let is_leaf = function
  1004. | Int _ -> true
  1005. | Prim(_,[]) -> true
  1006. | _ -> false
  1007. \end{lstlisting}
  1008. \end{minipage}
  1009. \end{center}
  1010. \end{ocamlx}
  1011. \section{Recursive Functions}
  1012. \label{sec:recursion}
  1013. \index{recursive function}
  1014. Programs are inherently recursive. For example, an \LangInt{} expression is
  1015. often made of smaller expressions. Thus, the natural way to process an
  1016. entire program is with a recursive function. As a first example of
  1017. such a recursive function, we define \texttt{exp?} below, which takes
  1018. an arbitrary value and determines whether or not it is an \LangInt{}
  1019. expression.
  1020. %
  1021. We say that a function is defined by \emph{structural recursion} when
  1022. it is defined using a sequence of match clauses that correspond to a
  1023. grammar, and the body of each clause makes a recursive call on each
  1024. child node.\footnote{This principle of structuring code according to
  1025. the data definition is advocated in the book \emph{How to Design
  1026. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  1027. Below we also define a second function, named \code{Rint?}, that
  1028. determines whether an AST is an \LangInt{} program. In general we can
  1029. expect to write one recursive function to handle each non-terminal in
  1030. a grammar.\index{structural recursion}
  1031. %
  1032. \begin{center}
  1033. \begin{minipage}{0.7\textwidth}
  1034. \begin{lstlisting}
  1035. (define (exp? ast)
  1036. (match ast
  1037. [(Int n) #t]
  1038. [(Prim 'read '()) #t]
  1039. [(Prim '- (list e)) (exp? e)]
  1040. [(Prim '+ (list e1 e2))
  1041. (and (exp? e1) (exp? e2))]
  1042. [else #f]))
  1043. (define (Rint? ast)
  1044. (match ast
  1045. [(Program '() e) (exp? e)]
  1046. [else #f]))
  1047. (Rint? (Program '() ast1.1)
  1048. (Rint? (Program '()
  1049. (Prim '- (list (Prim 'read '())
  1050. (Prim '+ (list (Num 8)))))))
  1051. \end{lstlisting}
  1052. \end{minipage}
  1053. \vrule
  1054. \begin{minipage}{0.25\textwidth}
  1055. \begin{lstlisting}
  1056. #t
  1057. #f
  1058. \end{lstlisting}
  1059. \end{minipage}
  1060. \end{center}
  1061. You may be tempted to merge the two functions into one, like this:
  1062. \begin{center}
  1063. \begin{minipage}{0.5\textwidth}
  1064. \begin{lstlisting}
  1065. (define (Rint? ast)
  1066. (match ast
  1067. [(Int n) #t]
  1068. [(Prim 'read '()) #t]
  1069. [(Prim '- (list e)) (Rint? e)]
  1070. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  1071. [(Program '() e) (Rint? e)]
  1072. [else #f]))
  1073. \end{lstlisting}
  1074. \end{minipage}
  1075. \end{center}
  1076. %
  1077. Sometimes such a trick will save a few lines of code, especially when
  1078. it comes to the \code{Program} wrapper. Yet this style is generally
  1079. \emph{not} recommended because it can get you into trouble.
  1080. %
  1081. For example, the above function is subtly wrong:
  1082. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  1083. returns true when it should return false.
  1084. \begin{ocamlx}
  1085. There is almost no point in writing OCaml analogs to \code{exp?} or \code{Rint?}, because static
  1086. typing guarantees that values claimed to be in type \code{exp} or \code{rint\_program} really are
  1087. (or the OCaml program will not pass the OCaml typechecker). However, it is still worth
  1088. writing a function to check that primops are applied to the right number of arguments.
  1089. Here is an idiomatic way to do that:
  1090. \begin{center}
  1091. \begin{minipage}{0.85\textwidth}
  1092. \begin{lstlisting}[style=ocaml]
  1093. let arity = function
  1094. | Read -> 0
  1095. | Neg -> 1
  1096. | Add -> 2
  1097. let rec check_exp = function
  1098. | Int _ -> true
  1099. | Prim(op,args) ->
  1100. List.length args = arity op && check_exps args
  1101. and check_exps = function
  1102. | [] -> true
  1103. | (exp::exps') -> check_exp exp && check_exps exps'
  1104. let check_program (Program(_,e)) = check_exp e
  1105. check_program (Program((),ast1_1))
  1106. check_program (Program((),Prim(Neg,[Prim(Read,[]);
  1107. Prim(Plus,[Int 8])])))
  1108. \end{lstlisting}
  1109. \end{minipage}
  1110. \vrule
  1111. \begin{minipage}{0.1\textwidth}
  1112. \begin{lstlisting}[style=ocaml]
  1113. true
  1114. false
  1115. \end{lstlisting}
  1116. \end{minipage}
  1117. \end{center}
  1118. In the definition of \code{check\_program}, since the argument type \code{rint\_program}
  1119. has only one constructor, we can write a pattern \code{Program(\_,e)} which matches that constructor directly in
  1120. place of an argument name; this binds the variable(s) (here \code{e}) of the pattern in the body of the function.
  1121. Note that \code{check\_exp} is declared to be recursive by using the \code{rec} keyword;
  1122. in fact, \code{check\_exp} and \code{check\_exps} are \emph{mutually} recursive because
  1123. their definitions are connected by the \code{and} keyword. \code{List.length} is a library
  1124. function that returns the length of a list. Actually, the library also has a handy higher-order
  1125. function \code{List.for\_all} that applies a specified boolean-value function to a list and returns
  1126. whether it is true on all elements. Using that, we could rewrite the \code{Prim}
  1127. clause of \code{check\_exp} as
  1128. \begin{lstlisting}[style=ocaml]
  1129. | Prim(op,args) ->
  1130. List.length args = arity op && List.for_all check_exp args
  1131. \end{lstlisting}
  1132. and dispense with \code{check\_exps} altogether. Being able to operate on entire lists
  1133. uniformly like this is one of the payoffs for using a single generic \code{Prim} constructor.
  1134. \end{ocamlx}
  1135. \section{Interpreters}
  1136. \label{sec:interp-Rint}
  1137. \index{interpreter}
  1138. In general, the intended behavior of a program is defined by the
  1139. specification of the language. For example, the Scheme language is
  1140. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  1141. defined in its reference manual~\citep{plt-tr}. In this book we use
  1142. interpreters to specify each language that we consider. An interpreter
  1143. that is designated as the definition of a language is called a
  1144. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1145. \index{definitional interpreter} We warm up by creating a definitional
  1146. interpreter for the \LangInt{} language, which serves as a second example
  1147. of structural recursion. The \texttt{interp-Rint} function is defined in
  1148. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  1149. input program followed by a call to the \lstinline{interp-exp} helper
  1150. function, which in turn has one match clause per grammar rule for
  1151. \LangInt{} expressions. \ocaml{The OCaml version is in Figure~\ref{fig:ocaml-interp-Rint}.}
  1152. \begin{figure}[tp]
  1153. \begin{lstlisting}
  1154. (define (interp-exp e)
  1155. (match e
  1156. [(Int n) n]
  1157. [(Prim 'read '())
  1158. (define r (read))
  1159. (cond [(fixnum? r) r]
  1160. [else (error 'interp-exp "read expected an integer" r)])]
  1161. [(Prim '- (list e))
  1162. (define v (interp-exp e))
  1163. (fx- 0 v)]
  1164. [(Prim '+ (list e1 e2))
  1165. (define v1 (interp-exp e1))
  1166. (define v2 (interp-exp e2))
  1167. (fx+ v1 v2)]))
  1168. (define (interp-Rint p)
  1169. (match p
  1170. [(Program '() e) (interp-exp e)]))
  1171. \end{lstlisting}
  1172. \caption{Interpreter for the \LangInt{} language.}
  1173. \label{fig:interp-Rint}
  1174. \end{figure}
  1175. \begin{figure}[tp]
  1176. \begin{lstlisting}[style=ocaml]
  1177. let interp_exp exp =
  1178. match exp with
  1179. | Int n -> n
  1180. | Prim(Read,[]) -> read_int()
  1181. | Prim(Neg,[e]) -> - (interp_exp e)
  1182. | Prim(Add,[e1;e2]) ->
  1183. (* must explicitly sequence evaluation order! *)
  1184. let v1 = interp_exp e1 in
  1185. let v2 = interp_exp e2 in
  1186. v1 + v2
  1187. | _ -> assert false (* arity mismatch *)
  1188. let interp_program (Program(_,e)) = interp_exp e
  1189. \end{lstlisting}
  1190. \caption{\ocaml{OCaml interpreter for the \LangInt{} language.}}
  1191. \label{fig:ocaml-interp-Rint}
  1192. \end{figure}
  1193. Let us consider the result of interpreting a few \LangInt{} programs. The
  1194. following program adds two integers.
  1195. \begin{lstlisting}
  1196. (+ 10 32)
  1197. \end{lstlisting}
  1198. The result is \key{42}, the answer to life, the universe, and
  1199. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1200. Galaxy} by Douglas Adams.}.
  1201. %
  1202. We wrote the above program in concrete syntax whereas the parsed
  1203. abstract syntax is:
  1204. \begin{lstlisting}
  1205. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1206. \end{lstlisting}
  1207. \begin{ocamlx}
  1208. Ocaml:
  1209. \begin{lstlisting}[style=ocaml]
  1210. Program((),Prim(Add,[Int 10; Int 32]))
  1211. \end{lstlisting}
  1212. \end{ocamlx}
  1213. The next example demonstrates that expressions may be nested within
  1214. each other, in this case nesting several additions and negations.
  1215. \begin{lstlisting}
  1216. (+ 10 (- (+ 12 20)))
  1217. \end{lstlisting}
  1218. What is the result of the above program?
  1219. As mentioned previously, the \LangInt{} language does not support
  1220. arbitrarily-large integers, but only $63$-bit integers, so we
  1221. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1222. in Racket.
  1223. Suppose
  1224. \[
  1225. n = 999999999999999999
  1226. \]
  1227. which indeed fits in $63$-bits. What happens when we run the
  1228. following program in our interpreter?
  1229. \begin{lstlisting}
  1230. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1231. \end{lstlisting}
  1232. It produces an error:
  1233. \begin{lstlisting}
  1234. fx+: result is not a fixnum
  1235. \end{lstlisting}
  1236. We establish the convention that if running the definitional
  1237. interpreter on a program produces an error then the meaning of that
  1238. program is \emph{unspecified}\index{unspecified behavior}, unless the
  1239. error is a \code{trapped-error}. A compiler for the language is under
  1240. no obligations regarding programs with unspecified behavior; it does
  1241. not have to produce an executable, and if it does, that executable can
  1242. do anything. On the other hand, if the error is a
  1243. \code{trapped-error}, then the compiler must produce an executable and
  1244. it is required to report that an error occurred. To signal an error,
  1245. exit with a return code of \code{255}. The interpreters in chapters
  1246. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1247. \code{trapped-error}.
  1248. \begin{ocamlx}
  1249. In OCaml, overflow does not cause a trap; instead values ``wrap around''
  1250. to produce results modulo $2^{63}$. The result of this program is
  1251. \key{-1223372036854775816}. We will embrace this wrap-around behavior
  1252. as the intended one for \LangInt{}, so the OCaml version will have
  1253. no undefined behaviors due to overflow.
  1254. \end{ocamlx}
  1255. %% This convention applies to the languages defined in this
  1256. %% book, as a way to simplify the student's task of implementing them,
  1257. %% but this convention is not applicable to all programming languages.
  1258. %%
  1259. Moving on to the last feature of the \LangInt{} language, the \key{read}
  1260. operation prompts the user of the program for an integer. \ocaml{The \code{read\_int}
  1261. function is in the standard library.} Recall that
  1262. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  1263. \code{8}. So if we run
  1264. \begin{lstlisting}
  1265. (interp-Rint (Program '() ast1.1))
  1266. \end{lstlisting}
  1267. and if the input is \code{50}, the result is \code{42}.
  1268. We include the \key{read} operation in \LangInt{} so a clever student
  1269. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1270. during compilation to obtain the output and then generates the trivial
  1271. code to produce the output. (Yes, a clever student did this in the
  1272. first instance of this course.)
  1273. The job of a compiler is to translate a program in one language into a
  1274. program in another language so that the output program behaves the
  1275. same way as the input program does. This idea is depicted in the
  1276. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1277. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1278. Given a compiler that translates from language $\mathcal{L}_1$ to
  1279. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1280. compiler must translate it into some program $P_2$ such that
  1281. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1282. same input $i$ yields the same output $o$.
  1283. \begin{equation} \label{eq:compile-correct}
  1284. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1285. \node (p1) at (0, 0) {$P_1$};
  1286. \node (p2) at (3, 0) {$P_2$};
  1287. \node (o) at (3, -2.5) {$o$};
  1288. \path[->] (p1) edge [above] node {compile} (p2);
  1289. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1290. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1291. \end{tikzpicture}
  1292. \end{equation}
  1293. In the next section we see our first example of a compiler.
  1294. \section{Example Compiler: a Partial Evaluator}
  1295. \label{sec:partial-evaluation}
  1296. In this section we consider a compiler that translates \LangInt{} programs
  1297. into \LangInt{} programs that may be more efficient, that is, this compiler
  1298. is an optimizer. This optimizer eagerly computes the parts of the
  1299. program that do not depend on any inputs, a process known as
  1300. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1301. \index{partial evaluation}
  1302. For example, given the following program
  1303. \begin{lstlisting}
  1304. (+ (read) (- (+ 5 3)))
  1305. \end{lstlisting}
  1306. our compiler will translate it into the program
  1307. \begin{lstlisting}
  1308. (+ (read) -8)
  1309. \end{lstlisting}
  1310. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1311. evaluator for the \LangInt{} language. The output of the partial evaluator
  1312. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1313. recursion over $\Exp$ is captured in the \code{pe-exp} function
  1314. whereas the code for partially evaluating the negation and addition
  1315. operations is factored into two separate helper functions:
  1316. \code{pe-neg} and \code{pe-add}. The input to these helper
  1317. functions is the output of partially evaluating the children.
  1318. \begin{figure}[tp]
  1319. \begin{lstlisting}
  1320. (define (pe-neg r)
  1321. (match r
  1322. [(Int n) (Int (fx- 0 n))]
  1323. [else (Prim '- (list r))]))
  1324. (define (pe-add r1 r2)
  1325. (match* (r1 r2)
  1326. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1327. [(_ _) (Prim '+ (list r1 r2))]))
  1328. (define (pe-exp e)
  1329. (match e
  1330. [(Int n) (Int n)]
  1331. [(Prim 'read '()) (Prim 'read '())]
  1332. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  1333. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  1334. (define (pe-Rint p)
  1335. (match p
  1336. [(Program '() e) (Program '() (pe-exp e))]))
  1337. \end{lstlisting}
  1338. \caption{A partial evaluator for \LangInt{}.}
  1339. \label{fig:pe-arith}
  1340. \end{figure}
  1341. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  1342. arguments are integers and if they are, perform the appropriate
  1343. arithmetic. Otherwise, they create an AST node for the arithmetic
  1344. operation.
  1345. \begin{ocamlx}
  1346. The corresponding OCaml code is in Figure~\ref{fig:ocaml-pe-arith}. In \code{pe\_add}, note
  1347. the syntax for matching over a pair of values simultaneously.
  1348. \begin{figure}[tp]
  1349. \begin{lstlisting}[style=ocaml]
  1350. let pe_neg = function
  1351. Int n -> Int (-n)
  1352. | e -> Prim(Neg,[e])
  1353. let pe_add e1 e2 =
  1354. match e1,e2 with
  1355. Int n1,Int n2 -> Int (n1+n2)
  1356. | e1,e2 -> Prim(Add,[e1;e2])
  1357. let rec pe_exp = function
  1358. Prim(Neg,[e]) -> pe_neg (pe_exp e)
  1359. | Prim(Add,[e1;e2]) -> pe_add (pe_exp e1) (pe_exp e2)
  1360. | e -> e
  1361. let pe_program (Program(info,e)) = Program(info,pe_exp e)
  1362. \end{lstlisting}
  1363. \caption{\ocaml{An OCaml partial evaluator for \LangInt{}}.}
  1364. \label{fig:ocaml-pe-arith}
  1365. \end{figure}
  1366. \end{ocamlx}
  1367. To gain some confidence that the partial evaluator is correct, we can
  1368. test whether it produces programs that get the same result as the
  1369. input programs. That is, we can test whether it satisfies Diagram
  1370. \ref{eq:compile-correct}. The following code runs the partial
  1371. evaluator on several examples and tests the output program. The
  1372. \texttt{parse-program} and \texttt{assert} functions are defined in
  1373. Appendix~\ref{appendix:utilities}.\\
  1374. \begin{minipage}{1.0\textwidth}
  1375. \begin{lstlisting}
  1376. (define (test-pe p)
  1377. (assert "testing pe-Rint"
  1378. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1379. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1380. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1381. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1382. \end{lstlisting}
  1383. \end{minipage}
  1384. \begin{ocamlx}
  1385. We can perform a similar kind of test in OCaml using a utility
  1386. function called \code{interp\_from\_string} which is in the support
  1387. code for this chapter (not yet in the Appendix).
  1388. Note, however, that comparing
  1389. results like this isn't a very satisfactory way of testing programs
  1390. that use \code{Read} anyhow, because it requires us to input the
  1391. same values twice, once for each execution, or the test will fail!
  1392. A more straightforward approach is to know what result value we
  1393. expect from each test program on a given set of input, and simply check
  1394. that the partially evaluated program still produces that result.
  1395. The support code also contains a simple driver that implements this approach.
  1396. \end{ocamlx}
  1397. \begin{ocamlx}
  1398. {\bf Warmup Exercises}
  1399. 1. Extend the concrete language and implementation for \LangInt{} with an additional arity-2 primop that
  1400. performs subtraction. The concrete form for this is \code{(- $e_1$ $e_2$)} where
  1401. $e_1$ and $e_2$ are expressions. Note that there are several ways to do this: you can add
  1402. an additional primop \code{Sub} to the AST, and add new code to check and interpret it,
  1403. or you can choose to ``de-sugar'' the new form into a combination of existing primops when
  1404. converting S-expressions to ASTs. Either way, make sure that you understand why the concrete
  1405. language remains unambiguous even though (a) we already have a unary negation operaror that is also written
  1406. with \code{-}, and (b) unlike addition, subtraction is not an associative operator, i.e.
  1407. $((a-b)-c$ is not generally the same thing as $(a-(b-c))$.
  1408. 2. Make some non-trivial improvement to the partial evaluator. This task is intentionally open-ended, but here
  1409. are some suggestions, in increasing order of difficulty.
  1410. \begin{itemize}
  1411. \item
  1412. If you added a new primop for subtraction in part 1, add support for
  1413. partially evaluating subtractions involving constants, analogous to what is already there
  1414. for addition.
  1415. \item
  1416. Add support for simplifying expressions
  1417. based on simple algebraic identities, e.g. $x + 0 = x$ for all $x$.
  1418. \item Try to simplify expressions to
  1419. the point where they contain no more than one \code{Int} leaf expression (the remaining leaves should all be
  1420. \code{Read}s).
  1421. \end{itemize}
  1422. 3. Change the AST, interpreter and (improved) partial evaluator for \LangInt{} so that they
  1423. use true 64-bit integers throughout.
  1424. (Currently, these are used in S-expressions in the front end, but everything else uses 63-bit integers instead.)
  1425. This will bring our interpreter and partial evaluator in line with X86-64 machine code, our ultimate
  1426. compilation target.
  1427. The point of this exercise is to get you familiar with exploring an OCaml library, in this case \code{Int64},
  1428. which is documented at \url{https://ocaml.org/releases/4.12/api/Int64.html}.
  1429. \end{ocamlx}
  1430. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1431. \chapter{Integers and Variables}
  1432. \label{ch:Rvar}
  1433. This chapter is about compiling a subset of Racket to x86-64 assembly
  1434. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1435. integer arithmetic and local variable binding. We often refer to
  1436. x86-64 simply as x86. The chapter begins with a description of the
  1437. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1438. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1439. is large so we discuss only the instructions needed for compiling
  1440. \LangVar{}. We introduce more x86 instructions in later chapters.
  1441. After introducing \LangVar{} and x86, we reflect on their differences
  1442. and come up with a plan to break down the translation from \LangVar{}
  1443. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1444. rest of the sections in this chapter give detailed hints regarding
  1445. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1446. We hope to give enough hints that the well-prepared reader, together
  1447. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1448. a couple weeks. To give the reader a feeling for the scale of this
  1449. first compiler, the instructor solution for the \LangVar{} compiler is
  1450. approximately 500 lines of code. \ocaml{For the OCaml-based course,
  1451. several pieces of the compiler will be provided for you, leaving enough
  1452. work for a week-long assignment. The instructor solution for
  1453. the tasks left to you is under 200 lines of code.
  1454. However, in return for not writing so much code,
  1455. you will need to \emph{read} more existing code.}
  1456. \section{The \LangVar{} Language}
  1457. \label{sec:s0}
  1458. \index{variable}
  1459. The \LangVar{} language extends the \LangInt{} language with variable
  1460. definitions. The concrete syntax of the \LangVar{} language is defined by
  1461. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1462. syntax is defined in Figure~\ref{fig:r1-syntax}. \ocaml{For the OCaml
  1463. version, we don't feel the need to match the syntax of Racket exactly,
  1464. so we can simplify the concrete syntax of \key{let} bindings.} The non-terminal
  1465. \Var{} may be any Racket identifier. \ocaml{For OCaml, it can be any S-expression symbol.}
  1466. As in \LangInt{}, \key{read} is a
  1467. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1468. operator. \ocaml{We also add \key{-} as a binary subtraction operator in
  1469. the concrete syntax, but not in the abstract syntax:
  1470. we will ``de-sugar'' substraction into a combination
  1471. of addition and negation.}Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1472. \key{Program} struct to mark the top of the program.
  1473. %% The $\itm{info}$
  1474. %% field of the \key{Program} structure contains an \emph{association
  1475. %% list} (a list of key-value pairs) that is used to communicate
  1476. %% auxiliary data from one compiler pass the next.
  1477. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1478. exhibit several compilation techniques.
  1479. \begin{figure}[tp]
  1480. \centering
  1481. \fbox{
  1482. \begin{minipage}{0.96\textwidth}
  1483. \[
  1484. \begin{array}{rcl}
  1485. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1486. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1487. \LangVar{} &::=& \Exp
  1488. \end{array}
  1489. \]
  1490. \end{minipage}
  1491. }
  1492. \begin{ocamlx}
  1493. \fbox{
  1494. \begin{minipage}{0.96\textwidth}
  1495. \[
  1496. \begin{array}{rcl}
  1497. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp}\\
  1498. &\mid& \Var \mid \code{(let $\Var$ $\Exp$ $\Exp$)}\\
  1499. \LangVar{} &::=& \Exp
  1500. \end{array}
  1501. \]
  1502. \end{minipage}
  1503. }
  1504. \end{ocamlx}
  1505. \caption{The concrete syntax of \LangVar{} \ocaml{in OCaml}.}
  1506. \label{fig:r1-concrete-syntax}
  1507. \end{figure}
  1508. \begin{figure}[tp]
  1509. \centering
  1510. \fbox{
  1511. \begin{minipage}{0.96\textwidth}
  1512. \[
  1513. \begin{array}{rcl}
  1514. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1515. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1516. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1517. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1518. \end{array}
  1519. \]
  1520. \end{minipage}
  1521. }
  1522. \begin{lstlisting}[style=ocaml,frame=single]
  1523. type primop =
  1524. Read
  1525. | Neg
  1526. | Add
  1527. type var = string
  1528. type exp =
  1529. Int of int64
  1530. | Prim of primop * exp list
  1531. | Var of var
  1532. | Let of var * exp * exp
  1533. type 'info program = Program of 'info * exp
  1534. \end{lstlisting}
  1535. \caption{The abstract syntax of \LangVar{}.}
  1536. \label{fig:r1-syntax}
  1537. \end{figure}
  1538. Let us dive further into the syntax and semantics of the \LangVar{}
  1539. language. The \key{let} feature defines a variable for use within its
  1540. body and initializes the variable with the value of an expression.
  1541. The abstract syntax for \key{let} is defined in
  1542. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1543. \begin{lstlisting}
  1544. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1545. \end{lstlisting}
  1546. \begin{lstlisting}[style=ocaml]
  1547. (let ~$\itm{var}$~ ~$\itm{exp}$~ ~$\itm{exp}$~)
  1548. \end{lstlisting}
  1549. For example, the following program initializes \code{x} to $32$ and then
  1550. evaluates the body \code{(+ 10 x)}, producing $42$.
  1551. \begin{lstlisting}
  1552. (let ([x (+ 12 20)]) (+ 10 x))
  1553. \end{lstlisting}
  1554. \begin{lstlisting}[style=ocaml]
  1555. (let x (+ 12 20) (+ 10 x))
  1556. \end{lstlisting}
  1557. When there are multiple \key{let}'s for the same variable, the closest
  1558. enclosing \key{let} is used. That is, variable definitions overshadow
  1559. prior definitions. Consider the following program with two \key{let}'s
  1560. that define variables named \code{x}. Can you figure out the result?
  1561. \begin{lstlisting}
  1562. (let ([x 32]) (+ (let ([x 10]) x) x))
  1563. \end{lstlisting}
  1564. \begin{lstlisting}[style=ocaml]
  1565. (let x 32 (+ (let x 10 x) x))
  1566. \end{lstlisting}
  1567. For the purposes of depicting which variable uses correspond to which
  1568. definitions, the following shows the \code{x}'s annotated with
  1569. subscripts to distinguish them. Double check that your answer for the
  1570. above is the same as your answer for this annotated version of the
  1571. program.
  1572. \begin{lstlisting}
  1573. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1574. \end{lstlisting}
  1575. \begin{lstlisting}[style=ocaml]
  1576. (let x~$_1$~ 32 (+ (let x~$_2$~ 10 x~$_2$~) x~$_1$~))
  1577. \end{lstlisting}
  1578. The initializing expression is always evaluated before the body of the
  1579. \key{let}, so in the following, the \key{read} for \code{x} is
  1580. performed before the \key{read} for \code{y}. Given the input
  1581. $52$ then $10$, the following produces $42$ (not $-42$).
  1582. \begin{lstlisting}
  1583. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1584. \end{lstlisting}
  1585. \begin{lstlisting}[style=ocaml]
  1586. (let x (read) (let y (read) (+ x (- y)))))
  1587. \end{lstlisting}
  1588. \subsection{Extensible Interpreters via Method Overriding}
  1589. \label{sec:extensible-interp}
  1590. \begin{ocamlx}
  1591. We are not going to bother with making our OCaml interpreters
  1592. extensible, although there are several mechanisms in OCaml that
  1593. we could use to acheive this. The languages involved here just
  1594. don't seem big enough to warrant the added complexity.
  1595. We will, however, break out the definition and interpretation of
  1596. primops into a separate module, so that this can be easily shared among
  1597. different languages.
  1598. \end{ocamlx}
  1599. To prepare for discussing the interpreter for \LangVar{}, we need to
  1600. explain why we choose to implement the interpreter using
  1601. object-oriented programming, that is, as a collection of methods
  1602. inside of a class. Throughout this book we define many interpreters,
  1603. one for each of the languages that we study. Because each language
  1604. builds on the prior one, there is a lot of commonality between their
  1605. interpreters. We want to write down those common parts just once
  1606. instead of many times. A naive approach would be to have, for example,
  1607. the interpreter for \LangIf{} handle all of the new features in that
  1608. language and then have a default case that dispatches to the
  1609. interpreter for \LangVar{}. The following code sketches this idea.
  1610. \begin{center}
  1611. \begin{minipage}{0.45\textwidth}
  1612. \begin{lstlisting}
  1613. (define (interp-Rvar e)
  1614. (match e
  1615. [(Prim '- (list e))
  1616. (fx- 0 (interp-Rvar e))]
  1617. ...))
  1618. \end{lstlisting}
  1619. \end{minipage}
  1620. \begin{minipage}{0.45\textwidth}
  1621. \begin{lstlisting}
  1622. (define (interp-Rif e)
  1623. (match e
  1624. [(If cnd thn els)
  1625. (match (interp-Rif cnd)
  1626. [#t (interp-Rif thn)]
  1627. [#f (interp-Rif els)])]
  1628. ...
  1629. [else (interp-Rvar e)]))
  1630. \end{lstlisting}
  1631. \end{minipage}
  1632. \end{center}
  1633. The problem with this approach is that it does not handle situations
  1634. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1635. feature, like the \code{-} operator, as in the following program.
  1636. \begin{lstlisting}
  1637. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1638. \end{lstlisting}
  1639. If we invoke \code{interp-Rif} on this program, it dispatches to
  1640. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1641. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1642. which is an \code{If}. But there is no case for \code{If} in
  1643. \code{interp-Rvar}, so we get an error!
  1644. To make our interpreters extensible we need something called
  1645. \emph{open recursion}\index{open recursion}, where the tying of the
  1646. recursive knot is delayed to when the functions are
  1647. composed. Object-oriented languages provide open recursion with the
  1648. late-binding of overridden methods\index{method overriding}. The
  1649. following code sketches this idea for interpreting \LangVar{} and
  1650. \LangIf{} using the
  1651. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1652. \index{class} feature of Racket. We define one class for each
  1653. language and define a method for interpreting expressions inside each
  1654. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1655. and the method \code{interp-exp} in \LangIf{} overrides the
  1656. \code{interp-exp} in \LangVar{}. Note that the default case of
  1657. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1658. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1659. that dispatches to the \code{interp-exp} in \LangVar{}.
  1660. \begin{center}
  1661. \begin{minipage}{0.45\textwidth}
  1662. \begin{lstlisting}
  1663. (define interp-Rvar-class
  1664. (class object%
  1665. (define/public (interp-exp e)
  1666. (match e
  1667. [(Prim '- (list e))
  1668. (fx- 0 (interp-exp e))]
  1669. ...))
  1670. ...))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. \begin{minipage}{0.45\textwidth}
  1674. \begin{lstlisting}
  1675. (define interp-Rif-class
  1676. (class interp-Rvar-class
  1677. (define/override (interp-exp e)
  1678. (match e
  1679. [(If cnd thn els)
  1680. (match (interp-exp cnd)
  1681. [#t (interp-exp thn)]
  1682. [#f (interp-exp els)])]
  1683. ...
  1684. [else (super interp-exp e)]))
  1685. ...
  1686. ))
  1687. \end{lstlisting}
  1688. \end{minipage}
  1689. \end{center}
  1690. Getting back to the troublesome example, repeated here:
  1691. \begin{lstlisting}
  1692. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1693. \end{lstlisting}
  1694. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1695. expression by creating an object of the \LangIf{} class and sending it the
  1696. \code{interp-exp} method with the argument \code{e0}.
  1697. \begin{lstlisting}
  1698. (send (new interp-Rif-class) interp-exp e0)
  1699. \end{lstlisting}
  1700. The default case of \code{interp-exp} in \LangIf{} handles it by
  1701. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1702. handles the \code{-} operator. But then for the recursive method call,
  1703. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1704. \code{If} is handled correctly. Thus, method overriding gives us the
  1705. open recursion that we need to implement our interpreters in an
  1706. extensible way.
  1707. \newpage
  1708. \subsection{Definitional Interpreter for \LangVar{}}
  1709. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1710. \small
  1711. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1712. An \emph{association list} (alist) is a list of key-value pairs.
  1713. For example, we can map people to their ages with an alist.
  1714. \index{alist}\index{association list}
  1715. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1716. (define ages
  1717. '((jane . 25) (sam . 24) (kate . 45)))
  1718. \end{lstlisting}
  1719. The \emph{dictionary} interface is for mapping keys to values.
  1720. Every alist implements this interface. \index{dictionary} The package
  1721. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1722. provides many functions for working with dictionaries. Here
  1723. are a few of them:
  1724. \begin{description}
  1725. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1726. returns the value associated with the given $\itm{key}$.
  1727. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1728. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1729. but otherwise is the same as $\itm{dict}$.
  1730. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1731. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1732. of keys and values in $\itm{dict}$. For example, the following
  1733. creates a new alist in which the ages are incremented.
  1734. \end{description}
  1735. \vspace{-10pt}
  1736. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1737. (for/list ([(k v) (in-dict ages)])
  1738. (cons k (add1 v)))
  1739. \end{lstlisting}
  1740. \end{tcolorbox}
  1741. \end{wrapfigure}
  1742. Having justified the use of classes and methods to implement
  1743. interpreters \ocaml{(or not)}, we turn to the definitional interpreter for \LangVar{}
  1744. in Figure~\ref{fig:interp-Rvar} \ocaml{(Figure~\ref{fig:interp-Rvar-ocaml})}.
  1745. It is similar to the interpreter for
  1746. \LangInt{} but adds two new \key{match} cases for variables and
  1747. \key{let}. \ocaml{Also, the code for performing primops has been split out
  1748. into a separate function. We rely on the fact that
  1749. \code{List.map} processes list elements from left to right to
  1750. enforce the intended order of evaluation of primop subexpressions.}
  1751. For \key{let} we need a way to communicate the value bound
  1752. to a variable to all the uses of the variable. To accomplish this, we
  1753. maintain a mapping from variables to values. Throughout the compiler
  1754. we often need to map variables to information about them. We refer to
  1755. these mappings as
  1756. \emph{environments}\index{environment}.\footnote{Another common term
  1757. for environment in the compiler literature is \emph{symbol
  1758. table}\index{symbol table}.}
  1759. %
  1760. For simplicity, we use an association list (alist) to represent the
  1761. environment. The sidebar to the right gives a brief introduction to
  1762. alists and the \code{racket/dict} package. The \code{interp-exp}
  1763. function takes the current environment, \code{env}, as an extra
  1764. parameter. When the interpreter encounters a variable, it finds the
  1765. corresponding value using the \code{dict-ref} function. When the
  1766. interpreter encounters a \key{Let}, it evaluates the initializing
  1767. expression, extends the environment with the result value bound to the
  1768. variable, using \code{dict-set}, then evaluates the body of the
  1769. \key{Let}.
  1770. \begin{ocamlx}
  1771. In OCaml, we thread environments in the same way, but
  1772. it is convenient to represent environments using
  1773. the \code{Map} library module, which provides efficient
  1774. mappings from keys to values (using balanced binary trees,
  1775. although that is an implementation detail we don't need to
  1776. know about). \code{Map} is an example of a module that
  1777. is \emph{parameterized} by another module signature; this
  1778. is sometimes called a \emph{functor}. Here we use \code{Map.Make}
  1779. to \emph{apply} the functor, thereby defining a module \code{Env} that provides operations
  1780. specialized to \code{string} keys (suitable for variables).
  1781. The type of environments is written \code{'a Env.t}; it is
  1782. parametric in the type \code{'a} of values stored in the map.
  1783. Here we will be using \LangVar{}
  1784. values, i.e. \code{int64}s, so the type is \code{int64 Env.t}.
  1785. \code{Env.empty} represents an empty environment.
  1786. \code{Env.find $x$ $env$} returns the value associated with
  1787. variable $x$ in $env$ (throwing an exception if $x$ is not found).
  1788. \code{Env.add $x$ $v$ $env$} produces a new environment
  1789. that is the same as $env$ except that variable $x$ is associated to
  1790. value $v$. Note that these operations are \emph{pure}; that is, they
  1791. do not mutate any environment.
  1792. \end{ocamlx}
  1793. \begin{ocamlx}
  1794. The OCaml code for \LangVar{} ASTs, concrete parsing and printing (for debug purposes),
  1795. and interpretation are in file \texttt{RVar.ml}, which also imports
  1796. from file \texttt{Primops.ml}. These files also contain code for
  1797. static checking of \LangVar{} programs. The checker makes sure that
  1798. (i) every use of a variable is in the scope of a corresponding \code{let} binding;
  1799. and (ii) each primop is applied to the correct number of arguments.
  1800. Note that if a source program fails the checker for reason (i), this is a static user error
  1801. that should be reported as such. (Violations of (ii) in user programs
  1802. should be caught by the parser; parse errors are always reported as user errors.)
  1803. Your compiler should stop trying to process a file as soon as it reports a static user
  1804. error! (That's what the provided test driver will do.)
  1805. However, if a program initially passes
  1806. the checker but is subsequently transformed by the compiler and then
  1807. fails a re-check, this indicates that the problem is the compiler's fault.
  1808. In this case, the compiler itself should halt with a suitable error message.
  1809. The checker has a boolean flag to distinguish these cases.
  1810. \end{ocamlx}
  1811. \begin{figure}[tp]
  1812. \begin{lstlisting}
  1813. (define interp-Rvar-class
  1814. (class object%
  1815. (super-new)
  1816. (define/public ((interp-exp env) e)
  1817. (match e
  1818. [(Int n) n]
  1819. [(Prim 'read '())
  1820. (define r (read))
  1821. (cond [(fixnum? r) r]
  1822. [else (error 'interp-exp "expected an integer" r)])]
  1823. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1824. [(Prim '+ (list e1 e2))
  1825. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1826. [(Var x) (dict-ref env x)]
  1827. [(Let x e body)
  1828. (define new-env (dict-set env x ((interp-exp env) e)))
  1829. ((interp-exp new-env) body)]))
  1830. (define/public (interp-program p)
  1831. (match p
  1832. [(Program '() e) ((interp-exp '()) e)]))
  1833. ))
  1834. (define (interp-Rvar p)
  1835. (send (new interp-Rvar-class) interp-program p))
  1836. \end{lstlisting}
  1837. \caption{Interpreter for the \LangVar{} language.}
  1838. \label{fig:interp-Rvar}
  1839. \end{figure}
  1840. \begin{figure}[tp]
  1841. \begin{lstlisting}[style=ocaml]
  1842. type value = int64
  1843. let interp_primop (op:primop) (args: value list) : value =
  1844. match op,args with
  1845. Read,[] -> read_int()
  1846. | Neg,[v] -> Int64.neg v
  1847. | Add,[v1;v2] -> Int64.add v1 v2
  1848. | _,_ -> assert false (* arity mismatch *)
  1849. module StringKey = struct type t = string let compare = String.compare end
  1850. module Env = Map.Make(StringKey)
  1851. let rec interp_exp (env:value Env.t) = function
  1852. Int n -> n
  1853. | Prim(op,args) -> interp_primop op (List.map (interp_exp env) args)
  1854. | Var x -> Env.find x env
  1855. | Let (x,e1,e2) -> interp_exp (Env.add x (interp_exp env e1) env) e2
  1856. let interp_program (Program(_,e)) = interp_exp Env.empty e
  1857. \end{lstlisting}
  1858. \caption{\ocaml{Ocaml interpreter for the \LangVar{} language.}}
  1859. \label{fig:interp-Rvar-ocaml}
  1860. \end{figure}
  1861. The goal for this chapter is to implement a compiler that translates
  1862. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1863. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1864. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1865. is, they output the same integer $n$. We depict this correctness
  1866. criteria in the following diagram.
  1867. \[
  1868. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1869. \node (p1) at (0, 0) {$P_1$};
  1870. \node (p2) at (4, 0) {$P_2$};
  1871. \node (o) at (4, -2) {$n$};
  1872. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1873. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1874. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1875. \end{tikzpicture}
  1876. \]
  1877. In the next section we introduce the \LangXInt{} subset of x86 that
  1878. suffices for compiling \LangVar{}.
  1879. \section{The \LangXInt{} Assembly Language}
  1880. \label{sec:x86}
  1881. \index{x86}
  1882. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1883. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1884. assembler.
  1885. %
  1886. A program begins with a \code{main} label followed by a sequence of
  1887. instructions. The \key{globl} directive says that the \key{main}
  1888. procedure is externally visible, which is necessary so that the
  1889. operating system can call it. In the grammar, ellipses such as
  1890. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1891. \ldots$ is a sequence of instructions.\index{instruction}
  1892. %
  1893. An x86 program is stored in the computer's memory. For our purposes,
  1894. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1895. values. The computer has a \emph{program counter} (PC)\index{program
  1896. counter}\index{PC} stored in the \code{rip} register that points to
  1897. the address of the next instruction to be executed. For most
  1898. instructions, the program counter is incremented after the instruction
  1899. is executed, so it points to the next instruction in memory. Most x86
  1900. instructions take two operands, where each operand is either an
  1901. integer constant (called \emph{immediate value}\index{immediate
  1902. value}), a \emph{register}\index{register}, or a memory location.
  1903. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1904. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1905. && \key{r8} \mid \key{r9} \mid \key{r10}
  1906. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1907. \mid \key{r14} \mid \key{r15}}
  1908. \begin{figure}[tp]
  1909. \fbox{
  1910. \begin{minipage}{0.96\textwidth}
  1911. \[
  1912. \begin{array}{lcl}
  1913. \Reg &::=& \allregisters{} \\
  1914. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1915. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1916. \key{subq} \; \Arg\key{,} \Arg \mid
  1917. \key{negq} \; \Arg \mid \\
  1918. && \key{movq} \; \Arg\key{,} \Arg \mid \ocaml{\key{movabsq} \; \Arg\key{,} \Arg \mid} \\
  1919. && \key{callq} \; \mathit{label} \mid
  1920. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1921. && \itm{label}\key{:}\; \Instr \\
  1922. \LangXInt{} &::= & \key{.globl main}\\
  1923. & & \key{main:} \; \Instr\ldots
  1924. \end{array}
  1925. \]
  1926. \end{minipage}
  1927. }
  1928. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1929. \label{fig:x86-int-concrete}
  1930. \end{figure}
  1931. A register is a special kind of variable. Each one holds a 64-bit
  1932. value; there are 16 general-purpose registers in the computer and
  1933. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1934. is written with a \key{\%} followed by the register name, such as
  1935. \key{\%rax}.
  1936. An immediate value is written using the notation \key{\$}$n$ where $n$
  1937. is an integer.
  1938. %
  1939. %
  1940. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1941. which obtains the address stored in register $r$ and then adds $n$
  1942. bytes to the address. The resulting address is used to load or store
  1943. to memory depending on whether it occurs as a source or destination
  1944. argument of an instruction.
  1945. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1946. source $s$ and destination $d$, applies the arithmetic operation, then
  1947. writes the result back to the destination $d$.
  1948. %
  1949. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1950. stores the result in $d$.
  1951. %
  1952. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1953. specified by the label and $\key{retq}$ returns from a procedure to
  1954. its caller.
  1955. %
  1956. We discuss procedure calls in more detail later in this chapter and in
  1957. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1958. updates the program counter to the address of the instruction after
  1959. the specified label.
  1960. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1961. all of the x86 instructions used in this book.
  1962. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1963. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1964. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1965. adds $32$ to the $10$ in \key{rax} and
  1966. puts the result, $42$, back into \key{rax}.
  1967. %
  1968. The last instruction, \key{retq}, finishes the \key{main} function by
  1969. returning the integer in \key{rax} to the operating system. The
  1970. operating system interprets this integer as the program's exit
  1971. code. By convention, an exit code of 0 indicates that a program
  1972. completed successfully, and all other exit codes indicate various
  1973. errors. \ocaml{Also, exit codes are unsigned bytes, so they cannot accurately represent
  1974. arbitrary \code{int64}s.} Nevertheless, in this book we return the result of the program
  1975. as the exit code. \ocaml{(Incidentally, if you run a program at the unix shell
  1976. prompt, you can retrieve its exit code by typing \texttt{echo \$?} as the very next command.)}
  1977. \begin{figure}[tbp]
  1978. \begin{lstlisting}
  1979. .globl main
  1980. main:
  1981. movq $10, %rax
  1982. addq $32, %rax
  1983. retq
  1984. \end{lstlisting}
  1985. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1986. \label{fig:p0-x86}
  1987. \end{figure}
  1988. The x86 assembly language varies in a couple ways depending on what
  1989. operating system it is assembled in. The code examples shown here are
  1990. correct on Linux and most Unix-like platforms, but when assembled on
  1991. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1992. as in \key{\_main}. \ocaml{There is a utility function \code{get\_ostype}
  1993. provided in the \texttt{utils.ml} module provided with the support materials.}
  1994. We exhibit the use of memory for storing intermediate results in the
  1995. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1996. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1997. memory called the \emph{procedure call stack} (or \emph{stack} for
  1998. short). \index{stack}\index{procedure call stack} The stack consists
  1999. of a separate \emph{frame}\index{frame} for each procedure call. The
  2000. memory layout for an individual frame is shown in
  2001. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2002. \emph{stack pointer}\index{stack pointer} and points to the item at
  2003. the top of the stack. The stack grows downward in memory, so we
  2004. increase the size of the stack by subtracting from the stack pointer.
  2005. In the context of a procedure call, the \emph{return
  2006. address}\index{return address} is the instruction after the call
  2007. instruction on the caller side. The function call instruction,
  2008. \code{callq}, pushes the return address onto the stack prior to
  2009. jumping to the procedure. The register \key{rbp} is the \emph{base
  2010. pointer}\index{base pointer} and is used to access variables that
  2011. are stored in the frame of the current procedure call. The base
  2012. pointer of the caller is pushed onto the stack after the return
  2013. address and then the base pointer is set to the location of the old
  2014. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2015. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2016. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2017. \begin{figure}[tbp]
  2018. \begin{lstlisting}
  2019. start:
  2020. movq $10, -8(%rbp)
  2021. negq -8(%rbp)
  2022. movq -8(%rbp), %rax
  2023. addq $52, %rax
  2024. jmp conclusion
  2025. .globl main
  2026. main:
  2027. pushq %rbp
  2028. movq %rsp, %rbp
  2029. subq $16, %rsp
  2030. jmp start
  2031. conclusion:
  2032. addq $16, %rsp
  2033. popq %rbp
  2034. retq
  2035. \end{lstlisting}
  2036. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  2037. \label{fig:p1-x86}
  2038. \end{figure}
  2039. \begin{figure}[tbp]
  2040. \centering
  2041. \begin{tabular}{|r|l|} \hline
  2042. Position & Contents \\ \hline
  2043. 8(\key{\%rbp}) & return address \\
  2044. 0(\key{\%rbp}) & old \key{rbp} \\
  2045. -8(\key{\%rbp}) & variable $1$ \\
  2046. -16(\key{\%rbp}) & variable $2$ \\
  2047. \ldots & \ldots \\
  2048. 0(\key{\%rsp}) & variable $n$\\ \hline
  2049. \end{tabular}
  2050. \caption{Memory layout of a frame.}
  2051. \label{fig:frame}
  2052. \end{figure}
  2053. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2054. control is transferred from the operating system to the \code{main}
  2055. function. The operating system issues a \code{callq main} instruction
  2056. which pushes its return address on the stack and then jumps to
  2057. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2058. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2059. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2060. alignment (because the \code{callq} pushed the return address). The
  2061. first three instructions are the typical \emph{prelude}\index{prelude}
  2062. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2063. pointer for the caller onto the stack and subtracts $8$ from the stack
  2064. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2065. base pointer so that it points the location of the old base
  2066. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2067. pointer down to make enough room for storing variables. This program
  2068. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2069. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2070. functions. The last instruction of the prelude is \code{jmp start},
  2071. which transfers control to the instructions that were generated from
  2072. the Racket expression \code{(+ 52 (- 10))}.
  2073. The first instruction under the \code{start} label is
  2074. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2075. %
  2076. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2077. %
  2078. The next instruction moves the $-10$ from variable $1$ into the
  2079. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2080. the value in \code{rax}, updating its contents to $42$.
  2081. The three instructions under the label \code{conclusion} are the
  2082. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  2083. two instructions restore the \code{rsp} and \code{rbp} registers to
  2084. the state they were in at the beginning of the procedure. The
  2085. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2086. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2087. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2088. instruction, \key{retq}, jumps back to the procedure that called this
  2089. one and adds $8$ to the stack pointer.
  2090. The compiler needs a convenient representation for manipulating x86
  2091. programs, so we define an abstract syntax for x86 in
  2092. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2093. \LangXInt{}. The main difference compared to the concrete syntax of
  2094. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  2095. allowed in front of every instructions. Instead instructions are
  2096. grouped into \emph{blocks}\index{block}\index{basic block} with a
  2097. label associated with every block, which is why the \key{X86Program}
  2098. struct includes an alist mapping labels to blocks. The reason for this
  2099. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2100. introduce conditional branching. The \code{Block} structure includes
  2101. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2102. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2103. $\itm{info}$ field should contain an empty list. \ocaml{The \code{'binfo}
  2104. type parameter should be instantiated with \code{unit}.}
  2105. Also, regarding the
  2106. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  2107. integer for representing the arity of the function, i.e., the number
  2108. of arguments, which is helpful to know during register allocation
  2109. (Chapter~\ref{ch:register-allocation-Rvar}).
  2110. \begin{ocamlx}
  2111. The OCaml code for \LangXInt{} AST, printing, and checking is
  2112. in file \texttt{X86Int.ml}. Printing is used to produce \texttt{.s} files that
  2113. can be input to the system assembler; it can also be useful for debugging.
  2114. File \texttt{utils.ml} contains functions for invoking the assembler and linker and
  2115. running the resulting executables from inside OCaml; these are invoked
  2116. from the test drivers also defined in that file.
  2117. \end{ocamlx}
  2118. \begin{figure}[tp]
  2119. \fbox{
  2120. \begin{minipage}{0.98\textwidth}
  2121. \small
  2122. \[
  2123. \begin{array}{lcl}
  2124. \Reg &::=& \allregisters{} \\
  2125. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  2126. \mid \DEREF{\Reg}{\Int} \\
  2127. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2128. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2129. &\mid& \UNIINSTR{\code{negq}}{\Arg}\\
  2130. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2131. \ocaml{\mid \BININSTR{\code{movabsq}}{\Arg}{\Arg}} \\
  2132. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  2133. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  2134. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2135. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2136. \end{array}
  2137. \]
  2138. \end{minipage}
  2139. }
  2140. \begin{lstlisting}[style=ocaml,frame=single]
  2141. type reg =
  2142. RSP | RBP | RAX | RBX | RCX | RDX | RSI | RDI
  2143. | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15
  2144. type label = string
  2145. type arg =
  2146. Imm of int64 (* in most cases must actually be an int32 *)
  2147. | Reg of reg
  2148. | Deref of reg*int32
  2149. | Var of string (* a pseudo-argument for ~$\LangXVar{}$~ *)
  2150. type instr =
  2151. Addq of arg*arg | Subq of arg*arg | Negq of arg
  2152. | Movq of arg*arg | Movabsq of arg*arg | Callq of label*int
  2153. | Retq | Pushq of arg | Popq of arg | Jmp of label
  2154. type 'binfo block = Block of 'binfo * instr list
  2155. type ('pinfo,'binfo) program =
  2156. Program of 'pinfo * (label * 'binfo block) list
  2157. \end{lstlisting}
  2158. \caption{The abstract syntax of \LangXInt{} \ocaml{and \LangXVar{}} assembly.}
  2159. \label{fig:x86-int-ast}
  2160. \end{figure}
  2161. \section{Planning the trip to x86 via the \LangCVar{} language}
  2162. \label{sec:plan-s0-x86}
  2163. To compile one language to another it helps to focus on the
  2164. differences between the two languages because the compiler will need
  2165. to bridge those differences. What are the differences between \LangVar{}
  2166. and x86 assembly? Here are some of the most important ones:
  2167. \begin{enumerate}
  2168. \item[(a)] x86 arithmetic instructions typically have two arguments
  2169. and update the second argument in place. In contrast, \LangVar{}
  2170. arithmetic operations take two arguments and produce a new value.
  2171. An x86 instruction may have at most one memory-accessing argument.
  2172. Furthermore, some instructions place special restrictions on their
  2173. arguments. \ocaml{For example, immediate operands are usually restricted
  2174. to fit in 32 bits (except for the \code{movabsq} instruction).}
  2175. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  2176. expression, whereas x86 instructions restrict their arguments to be
  2177. integers constants, registers, and memory locations.
  2178. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2179. sequence of instructions and jumps to labeled positions, whereas in
  2180. \LangVar{} the order of evaluation is a left-to-right depth-first
  2181. traversal of the abstract syntax tree.
  2182. \item[(d)] A program in \LangVar{} can have any number of variables
  2183. whereas x86 has 16 registers and the procedure calls stack.
  2184. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  2185. same name. In x86, registers have unique names and memory locations
  2186. have unique addresses.
  2187. \end{enumerate}
  2188. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2189. the problem into several steps, dealing with the above differences one
  2190. at a time. Each of these steps is called a \emph{pass} of the
  2191. compiler.\index{pass}\index{compiler pass}
  2192. %
  2193. This terminology comes from the way each step passes over the AST of
  2194. the program.
  2195. %
  2196. We begin by sketching how we might implement each pass, and give them
  2197. names. We then figure out an ordering of the passes and the
  2198. input/output language for each pass. The very first pass has
  2199. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2200. its output language. In between we can choose whichever language is
  2201. most convenient for expressing the output of each pass, whether that
  2202. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2203. our own design. Finally, to implement each pass we write one
  2204. recursive function per non-terminal in the grammar of the input
  2205. language of the pass. \index{intermediate language}
  2206. \begin{description}
  2207. \item[\key{select-instructions}] handles the difference between
  2208. \LangVar{} operations and x86 instructions. This pass converts each
  2209. \LangVar{} operation to a short sequence of instructions that
  2210. accomplishes the same task.
  2211. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  2212. a primitive operation is a variable or integer, that is, an
  2213. \emph{atomic} expression. We refer to non-atomic expressions as
  2214. \emph{complex}. This pass introduces temporary variables to hold
  2215. the results of complex subexpressions.\index{atomic
  2216. expression}\index{complex expression}%
  2217. \footnote{The subexpressions of an operation are often called
  2218. operators and operands which explains the presence of
  2219. \code{opera*} in the name of this pass.}
  2220. \item[\key{explicate-control}] makes the execution order of the
  2221. program explicit. It convert the abstract syntax tree representation
  2222. into a control-flow graph in which each node contains a sequence of
  2223. statements and the edges between nodes say which nodes contain jumps
  2224. to other nodes.
  2225. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  2226. registers or stack locations in x86.
  2227. \item[\key{uniquify}] deals with the shadowing of variables by
  2228. renaming every variable to a unique name.
  2229. \end{description}
  2230. The next question is: in what order should we apply these passes? This
  2231. question can be challenging because it is difficult to know ahead of
  2232. time which orderings will be better (easier to implement, produce more
  2233. efficient code, etc.) so oftentimes trial-and-error is
  2234. involved. Nevertheless, we can try to plan ahead and make educated
  2235. choices regarding the ordering.
  2236. What should be the ordering of \key{explicate-control} with respect to
  2237. \key{uniquify}? The \key{uniquify} pass should come first because
  2238. \key{explicate-control} changes all the \key{let}-bound variables to
  2239. become local variables whose scope is the entire program, which would
  2240. confuse variables with the same name.
  2241. %
  2242. We place \key{remove-complex-opera*} before \key{explicate-control}
  2243. because the latter removes the \key{let} form, but it is convenient to
  2244. use \key{let} in the output of \key{remove-complex-opera*}.
  2245. %
  2246. The ordering of \key{uniquify} with respect to
  2247. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  2248. \key{uniquify} to come first.
  2249. Last, we consider \key{select-instructions} and \key{assign-homes}.
  2250. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  2251. learn that, in x86, registers are used for passing arguments to
  2252. functions and it is preferable to assign parameters to their
  2253. corresponding registers. On the other hand, by selecting instructions
  2254. first we may run into a dead end in \key{assign-homes}. Recall that
  2255. only one argument of an x86 instruction may be a memory access but
  2256. \key{assign-homes} might fail to assign even one of them to a
  2257. register.
  2258. %
  2259. A sophisticated approach is to iteratively repeat the two passes until
  2260. a solution is found. However, to reduce implementation complexity we
  2261. recommend a simpler approach in which \key{select-instructions} comes
  2262. first, followed by the \key{assign-homes}, then a third pass named
  2263. \key{patch-instructions} that uses a reserved register to fix
  2264. outstanding problems.
  2265. \begin{figure}[tbp]
  2266. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2267. \node (Rvar) at (0,2) {\large \LangVar{}};
  2268. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2269. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2270. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2271. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2272. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2273. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2274. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2275. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2276. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2277. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  2278. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  2279. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2280. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  2281. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2282. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2283. \end{tikzpicture}
  2284. \caption{Diagram of the passes for compiling \LangVar{}. }
  2285. \label{fig:Rvar-passes}
  2286. \end{figure}
  2287. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2288. passes and identifies the input and output language of each pass. The
  2289. last pass, \key{print-x86}, converts from the abstract syntax of
  2290. \LangXInt{} to the concrete syntax. In the following two sections
  2291. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  2292. dialect of x86. The remainder of this chapter gives hints regarding
  2293. the implementation of each of the compiler passes in
  2294. Figure~\ref{fig:Rvar-passes}.
  2295. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2296. %% are programs that are still in the \LangVar{} language, though the
  2297. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2298. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2299. %% %
  2300. %% The output of \key{explicate-control} is in an intermediate language
  2301. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2302. %% syntax, which we introduce in the next section. The
  2303. %% \key{select-instruction} pass translates from \LangCVar{} to
  2304. %% \LangXVar{}. The \key{assign-homes} and
  2305. %% \key{patch-instructions}
  2306. %% passes input and output variants of x86 assembly.
  2307. \subsection{The \LangCVar{} Intermediate Language}
  2308. The output of \key{explicate-control} is similar to the $C$
  2309. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2310. categories for expressions and statements, so we name it \LangCVar{}. The
  2311. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2312. (The concrete syntax for \LangCVar{} is in the Appendix,
  2313. Figure~\ref{fig:c0-concrete-syntax}. \ocaml{(This appendix is not quite accurate
  2314. for the OCaml version, but the details of the concrete syntax of
  2315. an IR like this don't matter much, since it will normally be used
  2316. only to dump out information when debugging; it won't be parsed.})
  2317. %
  2318. The \LangCVar{} language supports the same operators as \LangVar{} but
  2319. the arguments of operators are restricted to atomic
  2320. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2321. assignment statements which can be executed in sequence using the
  2322. \key{Seq} form. A sequence of statements always ends with
  2323. \key{Return}, a guarantee that is baked into the grammar rules for
  2324. \itm{tail}. The naming of this non-terminal comes from the term
  2325. \emph{tail position}\index{tail position}, which refers to an
  2326. expression that is the last one to execute within a function.
  2327. A \LangCVar{} program consists of a control-flow graph represented as
  2328. an alist mapping labels to tails \ocaml{(that is, a list of \code{(label*tail)} pairs)}.
  2329. This is more general than necessary
  2330. for the present chapter, as we do not yet introduce \key{goto} for
  2331. jumping to labels, but it saves us from having to change the syntax in
  2332. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2333. \key{start}, and the whole program \ocaml{body} is its tail.
  2334. %
  2335. The $\itm{info}$ field of the \key{CProgram} form, after the
  2336. \key{explicate-control} pass, contains a mapping from the symbol
  2337. \key{locals} to a list of variables, that is, a list of all the
  2338. variables used in the program. \ocaml{It is represented as a \code{unit Env.t},
  2339. a kind of degenerate map that effectively acts like a set.}
  2340. At the start of the program, these
  2341. variables are uninitialized; they become initialized on their first
  2342. assignment.
  2343. \begin{figure}[tbp]
  2344. \fbox{
  2345. \begin{minipage}{0.96\textwidth}
  2346. \[
  2347. \begin{array}{lcl}
  2348. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2349. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  2350. &\mid& \ADD{\Atm}{\Atm}\\
  2351. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2352. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  2353. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2354. \end{array}
  2355. \]
  2356. \end{minipage}
  2357. }
  2358. \begin{lstlisting}[style=ocaml,frame=single]
  2359. type var = string
  2360. type label = string
  2361. type atm =
  2362. Int of int64
  2363. | Var of var
  2364. type exp =
  2365. Atom of atm
  2366. | Prim of primop * atm list
  2367. type stmt =
  2368. Assign of var * exp
  2369. type tail =
  2370. Return of exp
  2371. | Seq of stmt*tail
  2372. type 'pinfo program = Program of 'pinfo * (label*tail) list
  2373. \end{lstlisting}
  2374. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2375. \label{fig:c0-syntax}
  2376. \end{figure}
  2377. The definitional interpreter for \LangCVar{} is in the support code,
  2378. in the file \code{interp-Cvar.rkt}.
  2379. \begin{ocamlx}
  2380. The OCaml code for \LangCVar{} AST, checking, printing (for debug purposes),
  2381. and interpretation is in file \texttt{CVar.ml}.
  2382. \end{ocamlx}
  2383. \subsection{The \LangXVar{} dialect}
  2384. The \LangXVar{} language is the output of the pass
  2385. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  2386. number of program-scope variables and removes the restrictions
  2387. regarding instruction arguments.
  2388. \begin{ocamlx}
  2389. For simplicity, we treat \LangXInt{} and \LangXVar{} as the same
  2390. language, defined in \texttt{X86Int.ml}. In particular, we allow \code{Var}
  2391. as one of the possible forms for an instruction argument (\code{arg}).
  2392. We provide two different check routines.
  2393. \begin{itemize}
  2394. \item \code{CheckLabels.check\_program}
  2395. just checks that all label
  2396. declarations are unique and that all jump targets are defined; this
  2397. is suitable for checking the code produced from the \key{select-instructions}
  2398. pass, which will use \code{Var} arguments freely.
  2399. \item
  2400. \code{CheckArgs.check\_program} checks that all arguments are legal for the
  2401. actual X86-64 machine (in particular, that they are not \code{Var} arguments);
  2402. this is suitable for checking the output of the \key{patch-instr} pass.
  2403. \end{itemize}
  2404. \end{ocamlx}
  2405. \section{Uniquify Variables}
  2406. \label{sec:uniquify-Rvar}
  2407. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2408. programs in which every \key{let} binds a unique variable name. For
  2409. example, the \code{uniquify} pass should translate the program on the
  2410. left into the program on the right. \\
  2411. \begin{tabular}{lll}
  2412. \begin{minipage}{0.4\textwidth}
  2413. \begin{lstlisting}
  2414. (let ([x 32])
  2415. (+ (let ([x 10]) x) x))
  2416. \end{lstlisting}
  2417. \end{minipage}
  2418. &
  2419. $\Rightarrow$
  2420. &
  2421. \begin{minipage}{0.4\textwidth}
  2422. \begin{lstlisting}
  2423. (let ([x.1 32])
  2424. (+ (let ([x.2 10]) x.2) x.1))
  2425. \end{lstlisting}
  2426. \end{minipage}
  2427. \end{tabular} \\
  2428. %
  2429. \begin{tabular}{lll}
  2430. \begin{minipage}{0.4\textwidth}
  2431. \begin{lstlisting}[style=ocaml]
  2432. (let x 32
  2433. (+ (let x 10 x) x))
  2434. \end{lstlisting}
  2435. \end{minipage}
  2436. &
  2437. \ocaml{$\Rightarrow$}
  2438. &
  2439. \begin{minipage}{0.4\textwidth}
  2440. \begin{lstlisting}[style=ocaml]
  2441. (let x.1 32
  2442. (+ (let x.2 10 x.2) x.1))
  2443. \end{lstlisting}
  2444. \end{minipage}
  2445. \end{tabular} \\
  2446. %
  2447. The following is another example translation, this time of a program
  2448. with a \key{let} nested inside the initializing expression of another
  2449. \key{let}.\\
  2450. \begin{tabular}{lll}
  2451. \begin{minipage}{0.4\textwidth}
  2452. \begin{lstlisting}
  2453. (let ([x (let ([x 4])
  2454. (+ x 1))])
  2455. (+ x 2))
  2456. \end{lstlisting}
  2457. \end{minipage}
  2458. &
  2459. $\Rightarrow$
  2460. &
  2461. \begin{minipage}{0.4\textwidth}
  2462. \begin{lstlisting}
  2463. (let ([x.2 (let ([x.1 4])
  2464. (+ x.1 1))])
  2465. (+ x.2 2))
  2466. \end{lstlisting}
  2467. \end{minipage}
  2468. \end{tabular}
  2469. \ocaml{You can transliterate examples like this for yourself by now...}
  2470. We recommend implementing \code{uniquify} by creating a structurally
  2471. recursive function named \code{uniquify-exp} that mostly just copies
  2472. an expression. However, when encountering a \key{let}, it should
  2473. generate a unique name for the variable and associate the old name
  2474. with the new name in an alist \ocaml{(Ocaml: \key{Env})}.\footnote{The Racket function
  2475. \code{gensym} is handy for generating unique variable names. \ocaml{There is a similar
  2476. function defined in \texttt{utils.ml}.}} The
  2477. \code{uniquify-exp} function needs to access this alist \ocaml{(\key{Env})} when it gets
  2478. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2479. for the alist \ocaml{(\key{Env})} .
  2480. The skeleton of the \code{uniquify-exp} function is shown in
  2481. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2482. convenient to partially apply it to an alist \ocaml{(\key{Env})} and then apply it to
  2483. different expressions, as in the last case for primitive operations in
  2484. Figure~\ref{fig:uniquify-Rvar}. The
  2485. %
  2486. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2487. %
  2488. form of Racket is useful for transforming each element of a list to
  2489. produce a new list.\index{for/list}
  2490. \ocaml{The \code{List.map} function is similar.}
  2491. \ocaml{In addition to writing the \code{uniquify} transformation, it is worthwhile
  2492. to write a \emph{checker} to make sure that the result obeys any invariants we
  2493. expect to hold. (Sometimes these invariants are baked into the abstract syntax
  2494. of the target, but that's not the case here.) Our checker should re-traverse the
  2495. result AST and make sure that no identifier is bound more than once. It should also
  2496. re-run the \LangVar{} checker defined in module \code{RVar} to make sure that
  2497. all variables uses are in the scope of a binding (something we might easily have
  2498. messed up) and that we have not accidentally introduced a primop arity error (much
  2499. less likely, but still possible).
  2500. }
  2501. \begin{exercise}
  2502. \normalfont % I don't like the italics for exercises. -Jeremy
  2503. Complete the \code{uniquify} pass by filling in the blanks in
  2504. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2505. variables and for the \key{let} form in the file \code{compiler.rkt}
  2506. in the support code. \ocaml{This exercise is done for you, in the
  2507. \code{Uniquify} module of file \code{Chapter2.ml}.}
  2508. \end{exercise}
  2509. \begin{figure}[tbp]
  2510. \begin{lstlisting}
  2511. (define (uniquify-exp env)
  2512. (lambda (e)
  2513. (match e
  2514. [(Var x) ___]
  2515. [(Int n) (Int n)]
  2516. [(Let x e body) ___]
  2517. [(Prim op es)
  2518. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2519. (define (uniquify p)
  2520. (match p
  2521. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2522. \end{lstlisting}
  2523. \caption{Skeleton for the \key{uniquify} pass.}
  2524. \label{fig:uniquify-Rvar}
  2525. \end{figure}
  2526. \begin{exercise}
  2527. \normalfont % I don't like the italics for exercises. -Jeremy
  2528. Create five \LangVar{} programs that exercise the most interesting
  2529. parts of the \key{uniquify} pass, that is, the programs should include
  2530. \key{let} forms, variables, and variables that overshadow each other.
  2531. The five programs should be placed in the subdirectory named
  2532. \key{tests} and the file names should start with \code{var\_test\_}
  2533. followed by a unique integer and end with the file extension
  2534. \key{.rkt}. \ocaml{OCaml: use extension \key{.r}.}
  2535. %
  2536. The \key{run-tests.rkt} script in the support code \ocaml{(\key{test\_files}
  2537. function in \code{Chapter2.ml}, which is invoked by the \code{driver}
  2538. executable)} checks whether the
  2539. output programs produce the same result as the input programs. The
  2540. script uses the \key{interp-tests} function
  2541. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} \ocaml{(\key{test\_files}
  2542. function from \code{utils.ml})} to test
  2543. your \key{uniquify} pass on the example programs. The \code{passes}
  2544. parameter of \key{interp-tests} is a list that should have one entry
  2545. for each pass in your compiler. For now, define \code{passes} to
  2546. contain just one entry for \code{uniquify} \ocaml{(plus the fixed initial pass)} as follows.
  2547. \begin{lstlisting}
  2548. (define passes
  2549. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  2550. \end{lstlisting}
  2551. \begin{ocamlx}
  2552. \begin{lstlisting}{style=ocaml}
  2553. let passes = PCons(initial_pass,
  2554. PCons(Uniquify.pass,PNil))
  2555. \end{lstlisting}
  2556. \end{ocamlx}
  2557. Run the \key{run-tests.rkt} script in the support code
  2558. \ocaml{(the \key{driver} executable)} to check
  2559. whether the output programs produce the same result as the input
  2560. programs.
  2561. \end{exercise}
  2562. \section{Remove Complex Operands}
  2563. \label{sec:remove-complex-opera-Rvar}
  2564. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  2565. into a restricted form in which the arguments of operations are atomic
  2566. expressions. Put another way, this pass removes complex
  2567. operands\index{complex operand}, such as the expression \code{(- 10)}
  2568. in the program below. This is accomplished by introducing a new
  2569. \key{let}-bound variable, binding the complex operand to the new
  2570. variable, and then using the new variable in place of the complex
  2571. operand, as shown in the output of \code{remove-complex-opera*} on the
  2572. right.\\
  2573. \begin{tabular}{lll}
  2574. \begin{minipage}{0.4\textwidth}
  2575. % var_test_19.rkt
  2576. \begin{lstlisting}
  2577. (+ 52 (- 10))
  2578. \end{lstlisting}
  2579. \end{minipage}
  2580. &
  2581. $\Rightarrow$
  2582. &
  2583. \begin{minipage}{0.4\textwidth}
  2584. \begin{lstlisting}
  2585. (let ([tmp.1 (- 10)])
  2586. (+ 52 tmp.1))
  2587. \end{lstlisting}
  2588. \end{minipage}
  2589. \end{tabular}
  2590. \begin{ocamlx}
  2591. We suggest generating temporary names that begin with a back-tick (\verb'`')
  2592. since these are illegal as S-expression symbols, and so cannot conflict with existing
  2593. user-defined names.
  2594. \end{ocamlx}
  2595. \begin{figure}[tp]
  2596. \centering
  2597. \fbox{
  2598. \begin{minipage}{0.96\textwidth}
  2599. \[
  2600. \begin{array}{rcl}
  2601. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2602. \Exp &::=& \Atm \mid \READ{} \\
  2603. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  2604. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  2605. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  2606. \end{array}
  2607. \]
  2608. \end{minipage}
  2609. }
  2610. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  2611. \label{fig:r1-anf-syntax}
  2612. \end{figure}
  2613. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  2614. this pass, the language \LangVarANF{}. The only difference is that
  2615. operator arguments are restricted to be atomic expressions that are
  2616. defined by the \Atm{} non-terminal. In particular, integer constants
  2617. and variables are atomic. In the literature, restricting arguments to
  2618. be atomic expressions is called \emph{administrative normal form}, or
  2619. ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2620. \index{administrative normal form} \index{ANF}
  2621. \ocaml{Actually, ANF
  2622. as defined in~\citep{Flanagan:1993cg}
  2623. refers to a more restricted form in which the defining expressions of
  2624. \code{let}s cannot themselves contain \code{lets}s. This essentially
  2625. corresponds to the \LangCVar{} language.}
  2626. We recommend implementing this pass with two mutually recursive
  2627. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  2628. \code{rco-atom} to subexpressions that need to become atomic and to
  2629. apply \code{rco-exp} to subexpressions that do not. Both functions
  2630. take an \LangVar{} expression as input. The \code{rco-exp} function
  2631. returns an expression. The \code{rco-atom} function returns two
  2632. things: an atomic expression and alist \ocaml{(i.e. list of pairs)} mapping temporary variables to
  2633. complex subexpressions. You can return multiple things from a function
  2634. using Racket's \key{values} form and you can receive multiple things
  2635. from a function call using the \key{define-values} form. If you are
  2636. not familiar with these features, review the Racket documentation.
  2637. Also, the
  2638. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2639. form is useful for applying a function to each element of a list, in
  2640. the case where the function returns multiple values.
  2641. \index{for/lists}
  2642. \ocaml{OCaml: You can return multiple things from a function using a tuple
  2643. and binding the return value to a tuple pattern. Again, the \code{List.map}
  2644. function is handy.}
  2645. Returning to the example program \code{(+ 52 (- 10))}, the
  2646. subexpression \code{(- 10)} should be processed using the
  2647. \code{rco-atom} function because it is an argument of the \code{+} and
  2648. therefore needs to become atomic. The output of \code{rco-atom}
  2649. applied to \code{(- 10)} is as follows.
  2650. \begin{tabular}{lll}
  2651. \begin{minipage}{0.4\textwidth}
  2652. \begin{lstlisting}
  2653. (- 10)
  2654. \end{lstlisting}
  2655. \end{minipage}
  2656. &
  2657. $\Rightarrow$
  2658. &
  2659. \begin{minipage}{0.4\textwidth}
  2660. \begin{lstlisting}
  2661. tmp.1
  2662. ((tmp.1 . (- 10)))
  2663. \end{lstlisting}
  2664. \end{minipage}
  2665. \end{tabular}
  2666. Take special care of programs such as the following one that binds a
  2667. variable to an atomic expression. You should leave such variable
  2668. bindings unchanged, as shown in to the program on the right \\
  2669. \begin{tabular}{lll}
  2670. \begin{minipage}{0.4\textwidth}
  2671. % var_test_20.rkt
  2672. \begin{lstlisting}
  2673. (let ([a 42])
  2674. (let ([b a])
  2675. b))
  2676. \end{lstlisting}
  2677. \end{minipage}
  2678. &
  2679. $\Rightarrow$
  2680. &
  2681. \begin{minipage}{0.4\textwidth}
  2682. \begin{lstlisting}
  2683. (let ([a 42])
  2684. (let ([b a])
  2685. b))
  2686. \end{lstlisting}
  2687. \end{minipage}
  2688. \end{tabular} \\
  2689. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2690. produce the following output with unnecessary temporary variables.\\
  2691. \begin{minipage}{0.4\textwidth}
  2692. \begin{lstlisting}
  2693. (let ([tmp.1 42])
  2694. (let ([a tmp.1])
  2695. (let ([tmp.2 a])
  2696. (let ([b tmp.2])
  2697. b))))
  2698. \end{lstlisting}
  2699. \end{minipage}
  2700. \begin{exercise}\normalfont
  2701. %
  2702. Implement the \code{remove-complex-opera*} function in
  2703. \code{compiler.rkt}. \ocaml{Fill in the RemoveComplexOperations submodule in \code{Chapter2.ml}.
  2704. Be sure to include a checker that re-traverses the target AST to make sure that
  2705. all primop arguments are indeed now atomic, and that we haven't broken any of the
  2706. other invariants we expect to hold of \LangInt{} programs at this point.
  2707. Fill in the {\tt pass} definition appropriately.
  2708. }
  2709. %
  2710. Create three new \LangInt{} programs that exercise the interesting
  2711. code in the \code{remove-complex-opera*} pass (Following the same file
  2712. name guidelines as before.).
  2713. %
  2714. In the \code{run-tests.rkt} script, add the following entry to the
  2715. list of \code{passes} and then run the script to test your compiler.
  2716. \begin{lstlisting}
  2717. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2718. \end{lstlisting}
  2719. \begin{ocamlx}
  2720. In \code{Chapter2.ml}, add an additional entry to the {\tt passes} list:
  2721. \begin{lstlisting}[style=ocaml]
  2722. let passes =
  2723. PCons(initial_pass,
  2724. PCons(Uniquify.pass,
  2725. PCons(RemoveComplexOperands.pass, PNil)))
  2726. \end{lstlisting}
  2727. \end{ocamlx}
  2728. While debugging your compiler, it is often useful to see the
  2729. intermediate programs that are output from each pass. To print the
  2730. intermediate programs, place the following before the call to
  2731. \code{interp-tests} in \code{run-tests.rkt}.
  2732. \begin{lstlisting}
  2733. (debug-level 1)
  2734. \end{lstlisting}
  2735. \begin{ocamlx}
  2736. Adjust the assignment near the bottom of \code{Chapter2.ml}:
  2737. \begin{lstlisting}[style=ocaml]
  2738. let _ = Util.debug_level := 2
  2739. \end{lstlisting}
  2740. \end{ocamlx}
  2741. \end{exercise}
  2742. \section{Explicate Control}
  2743. \label{sec:explicate-control-Rvar}
  2744. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2745. programs that make the order of execution explicit in their
  2746. syntax. For now this amounts to flattening \key{let} constructs into a
  2747. sequence of assignment statements. For example, consider the following
  2748. \LangVar{} program.\\
  2749. % var_test_11.rkt
  2750. \begin{minipage}{0.96\textwidth}
  2751. \begin{lstlisting}
  2752. (let ([y (let ([x 20])
  2753. (+ x (let ([x 22]) x)))])
  2754. y)
  2755. \end{lstlisting}
  2756. \end{minipage}\\
  2757. %
  2758. The output of the previous pass and of \code{explicate-control} is
  2759. shown below. Recall that the right-hand-side of a \key{let} executes
  2760. before its body, so the order of evaluation for this program is to
  2761. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2762. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2763. output of \code{explicate-control} makes this ordering explicit.\\
  2764. \begin{tabular}{lll}
  2765. \begin{minipage}{0.4\textwidth}
  2766. \begin{lstlisting}
  2767. (let ([y (let ([x.1 20])
  2768. (let ([x.2 22])
  2769. (+ x.1 x.2)))])
  2770. y)
  2771. \end{lstlisting}
  2772. \end{minipage}
  2773. &
  2774. $\Rightarrow$
  2775. &
  2776. \begin{minipage}{0.4\textwidth}
  2777. \begin{lstlisting}[language=C]
  2778. start:
  2779. x.1 = 20;
  2780. x.2 = 22;
  2781. y = (+ x.1 x.2);
  2782. return y;
  2783. \end{lstlisting}
  2784. \end{minipage}
  2785. \end{tabular}
  2786. %
  2787. \begin{figure}[tbp]
  2788. \begin{lstlisting}
  2789. (define (explicate-tail e)
  2790. (match e
  2791. [(Var x) ___]
  2792. [(Int n) (Return (Int n))]
  2793. [(Let x rhs body) ___]
  2794. [(Prim op es) ___]
  2795. [else (error "explicate-tail unhandled case" e)]))
  2796. (define (explicate-assign e x cont)
  2797. (match e
  2798. [(Var x) ___]
  2799. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2800. [(Let y rhs body) ___]
  2801. [(Prim op es) ___]
  2802. [else (error "explicate-assign unhandled case" e)]))
  2803. (define (explicate-control p)
  2804. (match p
  2805. [(Program info body) ___]))
  2806. \end{lstlisting}
  2807. \caption{Skeleton for the \key{explicate-control} pass.}
  2808. \label{fig:explicate-control-Rvar}
  2809. \end{figure}
  2810. The organization of this pass depends on the notion of tail position
  2811. that we have alluded to earlier. Formally, \emph{tail
  2812. position}\index{tail position} in the context of \LangVar{} is
  2813. defined recursively by the following two rules.
  2814. \begin{enumerate}
  2815. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2816. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2817. \end{enumerate}
  2818. We recommend implementing \code{explicate-control} using two mutually
  2819. recursive functions, \code{explicate-tail} and
  2820. \code{explicate-assign}, as suggested in the skeleton code in
  2821. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2822. function should be applied to expressions in tail position whereas the
  2823. \code{explicate-assign} should be applied to expressions that occur on
  2824. the right-hand-side of a \key{let}.
  2825. %
  2826. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2827. input and produces a \Tail{} in \LangCVar{} (see
  2828. Figure~\ref{fig:c0-syntax}).
  2829. %
  2830. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2831. the variable that it is to be assigned to, and a \Tail{} in
  2832. \LangCVar{} for the code that will come after the assignment. The
  2833. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2834. The \code{explicate-assign} function is in accumulator-passing style
  2835. in that the \code{cont} parameter is used for accumulating the
  2836. output. The reader might be tempted to instead organize
  2837. \code{explicate-assign} in a more direct fashion, without the
  2838. \code{cont} parameter and perhaps using \code{append} to combine
  2839. statements. We warn against that alternative because the
  2840. accumulator-passing style is key to how we generate high-quality code
  2841. for conditional expressions in Chapter~\ref{ch:Rif}.
  2842. \begin{ocamlx}
  2843. Don't take this advice too seriously. Organize things in the cleanest way you
  2844. can find; it will always be possible to adjust your approach in later chapters.
  2845. \end{ocamlx}
  2846. \begin{exercise}\normalfont
  2847. %
  2848. Implement the \code{explicate-control} function in
  2849. \code{compiler.rkt}. \ocaml{Fill in the \code{ExplicateControl} submodule
  2850. of \code{Chapter2.ml} by implementing the \code{do\_program} function.
  2851. The checking field of this pass should invoke \code{CVar.check\_program},
  2852. which checks that the target code is properly bound (and also fills in
  2853. some information about the set of bound variables in the \code{'pinfo}
  2854. field of the program that will be useful in a later pass).}
  2855. %
  2856. Create three new \LangInt{} programs that
  2857. exercise the code in \code{explicate-control}.
  2858. %
  2859. In the \code{run-tests.rkt} script, add the following entry to the
  2860. list of \code{passes} and then run the script to test your compiler.
  2861. \begin{lstlisting}
  2862. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2863. \end{lstlisting}
  2864. \ocaml{Make the analogous change to the \code{passes} list in \code{Chapter2.ml}.}
  2865. \end{exercise}
  2866. \section{Select Instructions}
  2867. \label{sec:select-Rvar}
  2868. \index{instruction selection}
  2869. In the \code{select-instructions} pass we begin the work of
  2870. translating from \LangCVar{} to \LangXVar{}. The target language of
  2871. this pass is a variant of x86 that still uses variables, so we add an
  2872. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2873. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). \ocaml{Recall that
  2874. we use the same module to define \LangXInt{} and \LangXVar{}.}
  2875. We recommend implementing the \code{select-instructions} with
  2876. three auxiliary functions, one for each of the non-terminals of
  2877. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2878. The cases for $\Atm$ are straightforward, variables stay
  2879. the same and integer constants are changed to immediates:
  2880. $\INT{n}$ changes to $\IMM{n}$.
  2881. Next we consider the cases for $\Stmt$, starting with arithmetic
  2882. operations. For example, consider the addition operation. We can use
  2883. the \key{addq} instruction, but it performs an in-place update. So we
  2884. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2885. add $\itm{arg}_2$ to \itm{var}. \\
  2886. \begin{tabular}{lll}
  2887. \begin{minipage}{0.4\textwidth}
  2888. \begin{lstlisting}
  2889. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2890. \end{lstlisting}
  2891. \end{minipage}
  2892. &
  2893. $\Rightarrow$
  2894. &
  2895. \begin{minipage}{0.4\textwidth}
  2896. \begin{lstlisting}
  2897. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2898. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2899. \end{lstlisting}
  2900. \end{minipage}
  2901. \end{tabular} \\
  2902. %
  2903. There are also cases that require special care to avoid generating
  2904. needlessly complicated code. For example, if one of the arguments of
  2905. the addition is the same variable as the left-hand side of the
  2906. assignment, then there is no need for the extra move instruction. The
  2907. assignment statement can be translated into a single \key{addq}
  2908. instruction as follows.\\
  2909. \begin{tabular}{lll}
  2910. \begin{minipage}{0.4\textwidth}
  2911. \begin{lstlisting}
  2912. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2913. \end{lstlisting}
  2914. \end{minipage}
  2915. &
  2916. $\Rightarrow$
  2917. &
  2918. \begin{minipage}{0.4\textwidth}
  2919. \begin{lstlisting}
  2920. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2921. \end{lstlisting}
  2922. \end{minipage}
  2923. \end{tabular}
  2924. The \key{read} operation does not have a direct counterpart in x86
  2925. assembly, so we provide this functionality with the function
  2926. \code{read\_int} in the file \code{runtime.c}, written in
  2927. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2928. functionality in this file as the \emph{runtime system}\index{runtime
  2929. system}, or simply the \emph{runtime} for short. When compiling your
  2930. generated x86 assembly code, you need to compile \code{runtime.c} to
  2931. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2932. \code{-c}) and link it into the executable. For our purposes of code
  2933. generation, all you need to do is translate an assignment of
  2934. \key{read} into a call to the \code{read\_int} function followed by a
  2935. move from \code{rax} to the left-hand-side variable. (Recall that the
  2936. return value of a function goes into \code{rax}.) \\
  2937. \begin{tabular}{lll}
  2938. \begin{minipage}{0.3\textwidth}
  2939. \begin{lstlisting}
  2940. |$\itm{var}$| = (read);
  2941. \end{lstlisting}
  2942. \end{minipage}
  2943. &
  2944. $\Rightarrow$
  2945. &
  2946. \begin{minipage}{0.3\textwidth}
  2947. \begin{lstlisting}
  2948. callq read_int
  2949. movq %rax, |$\itm{var}$|
  2950. \end{lstlisting}
  2951. \end{minipage}
  2952. \end{tabular}
  2953. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2954. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2955. assignment to the \key{rax} register followed by a jump to the
  2956. conclusion of the program (so the conclusion needs to be labeled).
  2957. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2958. recursively and then append the resulting instructions.
  2959. \begin{exercise}
  2960. \normalfont Implement the \key{select-instructions} pass in
  2961. \code{compiler.rkt}. \ocaml{Fill out the \code{SelectInstructions} submodule
  2962. of \code{Chapter2.ml}. The checking field of this pass should invoke
  2963. \code{X86Int.CheckLabels.check\_program}, passing a list of externally
  2964. defined labels (just \code{["read\_int"]}).}
  2965. Create three new example programs that are
  2966. designed to exercise all of the interesting cases in this pass.
  2967. %
  2968. In the \code{run-tests.rkt} script, add the following entry to the
  2969. list of \code{passes} and then run the script to test your compiler.
  2970. \begin{lstlisting}
  2971. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2972. \end{lstlisting}
  2973. \ocaml{Make the analogous change to the \code{passes} list in \code{Chapter2.ml}.}
  2974. \end{exercise}
  2975. \section{Assign Homes}
  2976. \label{sec:assign-Rvar}
  2977. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2978. \LangXVar{} programs that no longer use program variables.
  2979. Thus, the \key{assign-homes} pass is responsible for placing all of
  2980. the program variables in registers or on the stack. For runtime
  2981. efficiency, it is better to place variables in registers, but as there
  2982. are only 16 registers, some programs must necessarily resort to
  2983. placing some variables on the stack. In this chapter we focus on the
  2984. mechanics of placing variables on the stack. We study an algorithm for
  2985. placing variables in registers in
  2986. Chapter~\ref{ch:register-allocation-Rvar}.
  2987. Consider again the following \LangVar{} program from
  2988. Section~\ref{sec:remove-complex-opera-Rvar}.
  2989. % var_test_20.rkt
  2990. \begin{lstlisting}
  2991. (let ([a 42])
  2992. (let ([b a])
  2993. b))
  2994. \end{lstlisting}
  2995. The output of \code{select-instructions} is shown on the left and the
  2996. output of \code{assign-homes} on the right. In this example, we
  2997. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2998. variable \code{b} to location \code{-16(\%rbp)}.\\
  2999. \begin{tabular}{l}
  3000. \begin{minipage}{0.4\textwidth}
  3001. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3002. locals-types:
  3003. a : Integer, b : Integer
  3004. start:
  3005. movq $42, a
  3006. movq a, b
  3007. movq b, %rax
  3008. jmp conclusion
  3009. \end{lstlisting}
  3010. \end{minipage}
  3011. {$\Rightarrow$}
  3012. \begin{minipage}{0.4\textwidth}
  3013. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3014. stack-space: 16
  3015. start:
  3016. movq $42, -8(%rbp)
  3017. movq -8(%rbp), -16(%rbp)
  3018. movq -16(%rbp), %rax
  3019. jmp conclusion
  3020. \end{lstlisting}
  3021. \end{minipage}
  3022. \end{tabular}
  3023. The \code{locals-types} entry in the $\itm{info}$ of the
  3024. \code{X86Program} node is an alist mapping all the variables in the
  3025. program to their types (for now just \code{Integer}). The
  3026. \code{assign-homes} pass should replace all uses of those variables
  3027. with stack locations. As an aside, the \code{locals-types} entry is
  3028. computed by \code{type-check-Cvar} in the support code, which installs
  3029. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  3030. be propagated to the \code{X86Program} node.
  3031. \ocaml{The locals sets is represented as a \code{unit Env.t}.}
  3032. In the process of assigning variables to stack locations, it is
  3033. convenient for you to compute and store the size of the frame (in
  3034. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  3035. the key \code{stack-space}, which is needed later to generate the
  3036. conclusion of the \code{main} procedure. The x86-64 standard requires
  3037. the frame size to be a multiple of 16 bytes.\index{frame}
  3038. \ocaml{The \code{'pinfo} parameter should be instantiated with an \code{int}
  3039. representing the frame size.}
  3040. \begin{exercise}\normalfont
  3041. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  3042. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  3043. \Block{}. \ocaml{Fill in the definition of submodule \code{AssignHomes}.}
  3044. We recommend that the auxiliary functions take an extra
  3045. parameter that is an alist \ocaml{(\code{arg Env.t})} mapping variable names to homes (stack
  3046. locations for now). \ocaml{Use the same checker as in the previous pass.}
  3047. %
  3048. In the \code{run-tests.rkt} script, add the following entry to the
  3049. list of \code{passes} and then run the script to test your compiler.
  3050. \begin{lstlisting}
  3051. (list "assign homes" assign-homes interp-x86-0)
  3052. \end{lstlisting}
  3053. \ocaml{Make the analogous change to the \code{passes} list in \code{Chapter2.ml}.}
  3054. \end{exercise}
  3055. \section{Patch Instructions}
  3056. \label{sec:patch-s0}
  3057. The \code{patch-instructions} pass compiles from \LangXVar{} to
  3058. \LangXInt{} by making sure that each instruction adheres to the
  3059. restriction that at most one argument of an instruction may be a
  3060. memory reference. \ocaml{It also ensures that no immediate operand
  3061. to an ordinary instruction exceeds 32 bits, by introducing \code{movabsq}
  3062. instructions as needed. \code{movabsq} is the sole instruction that
  3063. allows a 64-bit immediate source operand; its destination must be a register.}
  3064. We return to the following example.
  3065. % var_test_20.rkt
  3066. \begin{lstlisting}
  3067. (let ([a 42])
  3068. (let ([b a])
  3069. b))
  3070. \end{lstlisting}
  3071. The \key{assign-homes} pass produces the following output
  3072. for this program. \\
  3073. \begin{minipage}{0.5\textwidth}
  3074. \begin{lstlisting}
  3075. stack-space: 16
  3076. start:
  3077. movq $42, -8(%rbp)
  3078. movq -8(%rbp), -16(%rbp)
  3079. movq -16(%rbp), %rax
  3080. jmp conclusion
  3081. \end{lstlisting}
  3082. \end{minipage}\\
  3083. The second \key{movq} instruction is problematic because both
  3084. arguments are stack locations. We suggest fixing this problem by
  3085. moving from the source location to the register \key{rax} and then
  3086. from \key{rax} to the destination location, as follows.
  3087. \begin{lstlisting}
  3088. movq -8(%rbp), %rax
  3089. movq %rax, -16(%rbp)
  3090. \end{lstlisting}
  3091. \begin{exercise}
  3092. \normalfont Implement the \key{patch-instructions} pass in
  3093. \code{compiler.rkt}. \ocaml{This task has been done for you, in the \code{PatchInstructions} submodule
  3094. of \code{Chapter2}.}
  3095. Create three new example programs that are
  3096. designed to exercise all of the interesting cases in this pass.
  3097. %
  3098. In the \code{run-tests.rkt} script, add the following entry to the
  3099. list of \code{passes} and then run the script to test your compiler.
  3100. \begin{lstlisting}
  3101. (list "patch instructions" patch-instructions interp-x86-0)
  3102. \end{lstlisting}
  3103. \end{exercise}
  3104. \section{Print x86}
  3105. \label{sec:print-x86}
  3106. The last step of the compiler from \LangVar{} to x86 is to convert the
  3107. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  3108. string representation (defined in
  3109. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  3110. \key{string-append} functions are useful in this regard. \ocaml{The \code{Printf}
  3111. library is useful here.} The main work
  3112. that this step needs to perform is to create the \key{main} function
  3113. and the standard instructions for its prelude and conclusion, as shown
  3114. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  3115. know the amount of space needed for the stack frame, which you can
  3116. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  3117. the \key{X86Program} node.
  3118. When running on Mac OS X, you compiler should prefix an underscore to
  3119. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  3120. useful for determining which operating system the compiler is running
  3121. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  3122. \ocaml{There is a similar utility function \code{get\_ostype}
  3123. provided in the \texttt{utils.ml} module.}
  3124. \begin{exercise}\normalfont
  3125. %
  3126. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  3127. \ocaml{This task has been done for you; the relevant printing
  3128. code is in module \code{X86Int}.}
  3129. %
  3130. In the \code{run-tests.rkt} script, add the following entry to the
  3131. list of \code{passes} and then run the script to test your compiler.
  3132. \begin{lstlisting}
  3133. (list "print x86" print-x86 #f)
  3134. \end{lstlisting}
  3135. %
  3136. Uncomment the call to the \key{compiler-tests} function
  3137. (Appendix~\ref{appendix:utilities}), which tests your complete
  3138. compiler by executing the generated x86 code. Compile the provided
  3139. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  3140. script to test your compiler.
  3141. \ocaml{The OCaml version packages the process of emitting, assembling,
  3142. linking, and executing the assembly code as just another pass
  3143. (the \code{execute\_pass} defined in \code{Chapter2.ml}).
  3144. To emit code but not process it further, you can use the
  3145. \code{emit\_pass} instead; note that in this case, the test driver
  3146. should be configured not to compare initial and final values (since
  3147. there will be no useful final value).}
  3148. \end{exercise}
  3149. \section{Challenge: Partial Evaluator for \LangVar{}}
  3150. \label{sec:pe-Rvar}
  3151. \index{partial evaluation}
  3152. This section describes optional challenge exercises that involve
  3153. adapting and improving the partial evaluator for \LangInt{} that was
  3154. introduced in Section~\ref{sec:partial-evaluation}.
  3155. \begin{exercise}\label{ex:pe-Rvar}
  3156. \normalfont
  3157. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3158. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3159. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  3160. and variables to the \LangInt{} language, so you will need to add cases for
  3161. them in the \code{pe-exp} function. Once complete, add the partial
  3162. evaluation pass to the front of your compiler and make sure that your
  3163. compiler still passes all of the tests.
  3164. \end{exercise}
  3165. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3166. \begin{exercise}
  3167. \normalfont
  3168. Improve on the partial evaluator by replacing the \code{pe-neg} and
  3169. \code{pe-add} auxiliary functions with functions that know more about
  3170. arithmetic. For example, your partial evaluator should translate
  3171. \[
  3172. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3173. \code{(+ 2 (read))}
  3174. \]
  3175. To accomplish this, the \code{pe-exp} function should produce output
  3176. in the form of the $\itm{residual}$ non-terminal of the following
  3177. grammar. The idea is that when processing an addition expression, we
  3178. can always produce either 1) an integer constant, 2) and addition
  3179. expression with an integer constant on the left-hand side but not the
  3180. right-hand side, or 3) or an addition expression in which neither
  3181. subexpression is a constant.
  3182. \[
  3183. \begin{array}{lcl}
  3184. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  3185. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  3186. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  3187. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  3188. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  3189. \end{array}
  3190. \]
  3191. The \code{pe-add} and \code{pe-neg} functions may assume that their
  3192. inputs are $\itm{residual}$ expressions and they should return
  3193. $\itm{residual}$ expressions. Once the improvements are complete,
  3194. make sure that your compiler still passes all of the tests. After
  3195. all, fast code is useless if it produces incorrect results!
  3196. \end{exercise}
  3197. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3198. \chapter{Register Allocation}
  3199. \label{ch:register-allocation-Rvar}
  3200. \index{register allocation}
  3201. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3202. stack. In this Chapter we learn how to improve the performance of the
  3203. generated code by placing some variables into registers. The CPU can
  3204. access a register in a single cycle, whereas accessing the stack can
  3205. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3206. serves as a running example. The source program is on the left and the
  3207. output of instruction selection is on the right. The program is almost
  3208. in the x86 assembly language but it still uses variables.
  3209. \begin{figure}
  3210. \begin{minipage}{0.45\textwidth}
  3211. Example \LangVar{} program:
  3212. % var_test_28.rkt
  3213. \begin{lstlisting}
  3214. (let ([v 1])
  3215. (let ([w 42])
  3216. (let ([x (+ v 7)])
  3217. (let ([y x])
  3218. (let ([z (+ x w)])
  3219. (+ z (- y)))))))
  3220. \end{lstlisting}
  3221. \end{minipage}
  3222. \begin{minipage}{0.45\textwidth}
  3223. After instruction selection:
  3224. \begin{lstlisting}
  3225. locals-types:
  3226. x : Integer, y : Integer,
  3227. z : Integer, t : Integer,
  3228. v : Integer, w : Integer
  3229. start:
  3230. movq $1, v
  3231. movq $42, w
  3232. movq v, x
  3233. addq $7, x
  3234. movq x, y
  3235. movq x, z
  3236. addq w, z
  3237. movq y, t
  3238. negq t
  3239. movq z, %rax
  3240. addq t, %rax
  3241. jmp conclusion
  3242. \end{lstlisting}
  3243. \end{minipage}
  3244. \caption{A running example for register allocation.}
  3245. \label{fig:reg-eg}
  3246. \end{figure}
  3247. The goal of register allocation is to fit as many variables into
  3248. registers as possible. Some programs have more variables than
  3249. registers so we cannot always map each variable to a different
  3250. register. Fortunately, it is common for different variables to be
  3251. needed during different periods of time during program execution, and
  3252. in such cases several variables can be mapped to the same register.
  3253. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3254. After the variable \code{x} is moved to \code{z} it is no longer
  3255. needed. Variable \code{z}, on the other hand, is used only after this
  3256. point, so \code{x} and \code{z} could share the same register. The
  3257. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3258. where a variable is needed. Once we have that information, we compute
  3259. which variables are needed at the same time, i.e., which ones
  3260. \emph{interfere} with each other, and represent this relation as an
  3261. undirected graph whose vertices are variables and edges indicate when
  3262. two variables interfere (Section~\ref{sec:build-interference}). We
  3263. then model register allocation as a graph coloring problem
  3264. (Section~\ref{sec:graph-coloring}).
  3265. If we run out of registers despite these efforts, we place the
  3266. remaining variables on the stack, similar to what we did in
  3267. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3268. for assigning a variable to a stack location. The decision to spill a
  3269. variable is handled as part of the graph coloring process
  3270. (Section~\ref{sec:graph-coloring}).
  3271. We make the simplifying assumption that each variable is assigned to
  3272. one location (a register or stack address). A more sophisticated
  3273. approach is to assign a variable to one or more locations in different
  3274. regions of the program. For example, if a variable is used many times
  3275. in short sequence and then only used again after many other
  3276. instructions, it could be more efficient to assign the variable to a
  3277. register during the initial sequence and then move it to the stack for
  3278. the rest of its lifetime. We refer the interested reader to
  3279. \citet{Cooper:2011aa} for more information about that approach.
  3280. % discuss prioritizing variables based on how much they are used.
  3281. \section{Registers and Calling Conventions}
  3282. \label{sec:calling-conventions}
  3283. \index{calling conventions}
  3284. As we perform register allocation, we need to be aware of the
  3285. \emph{calling conventions} \index{calling conventions} that govern how
  3286. functions calls are performed in x86.
  3287. %
  3288. Even though \LangVar{} does not include programmer-defined functions,
  3289. our generated code includes a \code{main} function that is called by
  3290. the operating system and our generated code contains calls to the
  3291. \code{read\_int} function.
  3292. Function calls require coordination between two pieces of code that
  3293. may be written by different programmers or generated by different
  3294. compilers. Here we follow the System V calling conventions that are
  3295. used by the GNU C compiler on Linux and
  3296. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3297. %
  3298. The calling conventions include rules about how functions share the
  3299. use of registers. In particular, the caller is responsible for freeing
  3300. up some registers prior to the function call for use by the callee.
  3301. These are called the \emph{caller-saved registers}
  3302. \index{caller-saved registers}
  3303. and they are
  3304. \begin{lstlisting}
  3305. rax rcx rdx rsi rdi r8 r9 r10 r11
  3306. \end{lstlisting}
  3307. On the other hand, the callee is responsible for preserving the values
  3308. of the \emph{callee-saved registers}, \index{callee-saved registers}
  3309. which are
  3310. \begin{lstlisting}
  3311. rsp rbp rbx r12 r13 r14 r15
  3312. \end{lstlisting}
  3313. We can think about this caller/callee convention from two points of
  3314. view, the caller view and the callee view:
  3315. \begin{itemize}
  3316. \item The caller should assume that all the caller-saved registers get
  3317. overwritten with arbitrary values by the callee. On the other hand,
  3318. the caller can safely assume that all the callee-saved registers
  3319. contain the same values after the call that they did before the
  3320. call.
  3321. \item The callee can freely use any of the caller-saved registers.
  3322. However, if the callee wants to use a callee-saved register, the
  3323. callee must arrange to put the original value back in the register
  3324. prior to returning to the caller. This can be accomplished by saving
  3325. the value to the stack in the prelude of the function and restoring
  3326. the value in the conclusion of the function.
  3327. \end{itemize}
  3328. In x86, registers are also used for passing arguments to a function
  3329. and for the return value. In particular, the first six arguments to a
  3330. function are passed in the following six registers, in this order.
  3331. \begin{lstlisting}
  3332. rdi rsi rdx rcx r8 r9
  3333. \end{lstlisting}
  3334. If there are more than six arguments, then the convention is to use
  3335. space on the frame of the caller for the rest of the
  3336. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3337. need more than six arguments. For now, the only function we care about
  3338. is \code{read\_int} and it takes zero arguments.
  3339. %
  3340. The register \code{rax} is used for the return value of a function.
  3341. The next question is how these calling conventions impact register
  3342. allocation. Consider the \LangVar{} program in
  3343. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3344. example from the caller point of view and then from the callee point
  3345. of view.
  3346. The program makes two calls to the \code{read} function. Also, the
  3347. variable \code{x} is in use during the second call to \code{read}, so
  3348. we need to make sure that the value in \code{x} does not get
  3349. accidentally wiped out by the call to \code{read}. One obvious
  3350. approach is to save all the values in caller-saved registers to the
  3351. stack prior to each function call, and restore them after each
  3352. call. That way, if the register allocator chooses to assign \code{x}
  3353. to a caller-saved register, its value will be preserved across the
  3354. call to \code{read}. However, saving and restoring to the stack is
  3355. relatively slow. If \code{x} is not used many times, it may be better
  3356. to assign \code{x} to a stack location in the first place. Or better
  3357. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3358. register, then it won't need to be saved and restored during function
  3359. calls.
  3360. The approach that we recommend for variables that are in use during a
  3361. function call is to either assign them to callee-saved registers or to
  3362. spill them to the stack. On the other hand, for variables that are not
  3363. in use during a function call, we try the following alternatives in
  3364. order 1) look for an available caller-saved register (to leave room
  3365. for other variables in the callee-saved register), 2) look for a
  3366. callee-saved register, and 3) spill the variable to the stack.
  3367. It is straightforward to implement this approach in a graph coloring
  3368. register allocator. First, we know which variables are in use during
  3369. every function call because we compute that information for every
  3370. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3371. build the interference graph (Section~\ref{sec:build-interference}),
  3372. we can place an edge between each of these variables and the
  3373. caller-saved registers in the interference graph. This will prevent
  3374. the graph coloring algorithm from assigning those variables to
  3375. caller-saved registers.
  3376. Returning to the example in
  3377. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3378. generated x86 code on the right-hand side, focusing on the
  3379. \code{start} block. Notice that variable \code{x} is assigned to
  3380. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3381. place during the second call to \code{read\_int}. Next, notice that
  3382. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3383. because there are no function calls in the remainder of the block.
  3384. Next we analyze the example from the callee point of view, focusing on
  3385. the prelude and conclusion of the \code{main} function. As usual the
  3386. prelude begins with saving the \code{rbp} register to the stack and
  3387. setting the \code{rbp} to the current stack pointer. We now know why
  3388. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3389. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3390. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3391. (\code{x}). The other callee-saved registers are not saved in the
  3392. prelude because they are not used. The prelude subtracts 8 bytes from
  3393. the \code{rsp} to make it 16-byte aligned and then jumps to the
  3394. \code{start} block. Shifting attention to the \code{conclusion}, we
  3395. see that \code{rbx} is restored from the stack with a \code{popq}
  3396. instruction. \index{prelude}\index{conclusion}
  3397. \begin{figure}[tp]
  3398. \begin{minipage}{0.45\textwidth}
  3399. Example \LangVar{} program:
  3400. %var_test_14.rkt
  3401. \begin{lstlisting}
  3402. (let ([x (read)])
  3403. (let ([y (read)])
  3404. (+ (+ x y) 42)))
  3405. \end{lstlisting}
  3406. \end{minipage}
  3407. \begin{minipage}{0.45\textwidth}
  3408. Generated x86 assembly:
  3409. \begin{lstlisting}
  3410. start:
  3411. callq read_int
  3412. movq %rax, %rbx
  3413. callq read_int
  3414. movq %rax, %rcx
  3415. addq %rcx, %rbx
  3416. movq %rbx, %rax
  3417. addq $42, %rax
  3418. jmp _conclusion
  3419. .globl main
  3420. main:
  3421. pushq %rbp
  3422. movq %rsp, %rbp
  3423. pushq %rbx
  3424. subq $8, %rsp
  3425. jmp start
  3426. conclusion:
  3427. addq $8, %rsp
  3428. popq %rbx
  3429. popq %rbp
  3430. retq
  3431. \end{lstlisting}
  3432. \end{minipage}
  3433. \caption{An example with function calls.}
  3434. \label{fig:example-calling-conventions}
  3435. \end{figure}
  3436. \clearpage
  3437. \section{Liveness Analysis}
  3438. \label{sec:liveness-analysis-Rvar}
  3439. \index{liveness analysis}
  3440. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  3441. is, it discovers which variables are in-use in different regions of a
  3442. program.
  3443. %
  3444. A variable or register is \emph{live} at a program point if its
  3445. current value is used at some later point in the program. We
  3446. refer to variables and registers collectively as \emph{locations}.
  3447. %
  3448. Consider the following code fragment in which there are two writes to
  3449. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3450. \begin{center}
  3451. \begin{minipage}{0.96\textwidth}
  3452. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3453. movq $5, a
  3454. movq $30, b
  3455. movq a, c
  3456. movq $10, b
  3457. addq b, c
  3458. \end{lstlisting}
  3459. \end{minipage}
  3460. \end{center}
  3461. The answer is no because \code{a} is live from line 1 to 3 and
  3462. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3463. line 2 is never used because it is overwritten (line 4) before the
  3464. next read (line 5).
  3465. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  3466. \small
  3467. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3468. A \emph{set} is an unordered collection of elements without duplicates.
  3469. \index{set}
  3470. \begin{description}
  3471. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  3472. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  3473. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  3474. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  3475. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  3476. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  3477. \end{description}
  3478. \end{tcolorbox}
  3479. \end{wrapfigure}
  3480. The live locations can be computed by traversing the instruction
  3481. sequence back to front (i.e., backwards in execution order). Let
  3482. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3483. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3484. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3485. locations before instruction $I_k$. The live locations after an
  3486. instruction are always the same as the live locations before the next
  3487. instruction. \index{live-after} \index{live-before}
  3488. \begin{equation} \label{eq:live-after-before-next}
  3489. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3490. \end{equation}
  3491. To start things off, there are no live locations after the last
  3492. instruction, so
  3493. \begin{equation}\label{eq:live-last-empty}
  3494. L_{\mathsf{after}}(n) = \emptyset
  3495. \end{equation}
  3496. We then apply the following rule repeatedly, traversing the
  3497. instruction sequence back to front.
  3498. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3499. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3500. \end{equation}
  3501. where $W(k)$ are the locations written to by instruction $I_k$ and
  3502. $R(k)$ are the locations read by instruction $I_k$.
  3503. There is a special case for \code{jmp} instructions. The locations
  3504. that are live before a \code{jmp} should be the locations in
  3505. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3506. maintaining an alist named \code{label->live} that maps each label to
  3507. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3508. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3509. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3510. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3511. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3512. Let us walk through the above example, applying these formulas
  3513. starting with the instruction on line 5. We collect the answers in
  3514. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3515. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3516. instruction (formula~\ref{eq:live-last-empty}). The
  3517. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3518. because it reads from variables \code{b} and \code{c}
  3519. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3520. \[
  3521. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3522. \]
  3523. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3524. the live-before set from line 5 to be the live-after set for this
  3525. instruction (formula~\ref{eq:live-after-before-next}).
  3526. \[
  3527. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3528. \]
  3529. This move instruction writes to \code{b} and does not read from any
  3530. variables, so we have the following live-before set
  3531. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3532. \[
  3533. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3534. \]
  3535. The live-before for instruction \code{movq a, c}
  3536. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3537. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3538. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3539. variable that is not live and does not read from a variable.
  3540. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3541. because it writes to variable \code{a}.
  3542. \begin{figure}[tbp]
  3543. \begin{minipage}{0.45\textwidth}
  3544. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3545. movq $5, a
  3546. movq $30, b
  3547. movq a, c
  3548. movq $10, b
  3549. addq b, c
  3550. \end{lstlisting}
  3551. \end{minipage}
  3552. \vrule\hspace{10pt}
  3553. \begin{minipage}{0.45\textwidth}
  3554. \begin{align*}
  3555. L_{\mathsf{before}}(1)= \emptyset,
  3556. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3557. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3558. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3559. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3560. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3561. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3562. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3563. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3564. L_{\mathsf{after}}(5)= \emptyset
  3565. \end{align*}
  3566. \end{minipage}
  3567. \caption{Example output of liveness analysis on a short example.}
  3568. \label{fig:liveness-example-0}
  3569. \end{figure}
  3570. \begin{exercise}\normalfont
  3571. Perform liveness analysis on the running example in
  3572. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3573. sets for each instruction. Compare your answers to the solution
  3574. shown in Figure~\ref{fig:live-eg}.
  3575. \end{exercise}
  3576. \begin{figure}[tp]
  3577. \hspace{20pt}
  3578. \begin{minipage}{0.45\textwidth}
  3579. \begin{lstlisting}
  3580. |$\{\ttm{rsp}\}$|
  3581. movq $1, v
  3582. |$\{\ttm{v},\ttm{rsp}\}$|
  3583. movq $42, w
  3584. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3585. movq v, x
  3586. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3587. addq $7, x
  3588. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3589. movq x, y
  3590. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3591. movq x, z
  3592. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3593. addq w, z
  3594. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3595. movq y, t
  3596. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3597. negq t
  3598. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3599. movq z, %rax
  3600. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3601. addq t, %rax
  3602. |$\{\ttm{rax},\ttm{rsp}\}$|
  3603. jmp conclusion
  3604. \end{lstlisting}
  3605. \end{minipage}
  3606. \caption{The running example annotated with live-after sets.}
  3607. \label{fig:live-eg}
  3608. \end{figure}
  3609. \begin{exercise}\normalfont
  3610. Implement the \code{uncover-live} pass. Store the sequence of
  3611. live-after sets in the $\itm{info}$ field of the \code{Block}
  3612. structure.
  3613. %
  3614. We recommend creating an auxiliary function that takes a list of
  3615. instructions and an initial live-after set (typically empty) and
  3616. returns the list of live-after sets.
  3617. %
  3618. We also recommend creating auxiliary functions to 1) compute the set
  3619. of locations that appear in an \Arg{}, 2) compute the locations read
  3620. by an instruction (the $R$ function), and 3) the locations written by
  3621. an instruction (the $W$ function). The \code{callq} instruction should
  3622. include all of the caller-saved registers in its write-set $W$ because
  3623. the calling convention says that those registers may be written to
  3624. during the function call. Likewise, the \code{callq} instruction
  3625. should include the appropriate argument-passing registers in its
  3626. read-set $R$, depending on the arity of the function being
  3627. called. (This is why the abstract syntax for \code{callq} includes the
  3628. arity.)
  3629. \end{exercise}
  3630. \clearpage
  3631. \section{Build the Interference Graph}
  3632. \label{sec:build-interference}
  3633. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3634. \small
  3635. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3636. A \emph{graph} is a collection of vertices and edges where each
  3637. edge connects two vertices. A graph is \emph{directed} if each
  3638. edge points from a source to a target. Otherwise the graph is
  3639. \emph{undirected}.
  3640. \index{graph}\index{directed graph}\index{undirected graph}
  3641. \begin{description}
  3642. %% We currently don't use directed graphs. We instead use
  3643. %% directed multi-graphs. -Jeremy
  3644. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3645. %% directed graph from a list of edges. Each edge is a list
  3646. %% containing the source and target vertex.
  3647. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3648. undirected graph from a list of edges. Each edge is represented by
  3649. a list containing two vertices.
  3650. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3651. inserts a vertex into the graph.
  3652. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3653. inserts an edge between the two vertices into the graph.
  3654. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3655. returns a sequence of all the neighbors of the given vertex.
  3656. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3657. returns a sequence of all the vertices in the graph.
  3658. \end{description}
  3659. \end{tcolorbox}
  3660. \end{wrapfigure}
  3661. Based on the liveness analysis, we know where each location is live.
  3662. However, during register allocation, we need to answer questions of
  3663. the specific form: are locations $u$ and $v$ live at the same time?
  3664. (And therefore cannot be assigned to the same register.) To make this
  3665. question more efficient to answer, we create an explicit data
  3666. structure, an \emph{interference graph}\index{interference graph}. An
  3667. interference graph is an undirected graph that has an edge between two
  3668. locations if they are live at the same time, that is, if they
  3669. interfere with each other.
  3670. An obvious way to compute the interference graph is to look at the set
  3671. of live locations between each instruction and the next and add an edge to the graph
  3672. for every pair of variables in the same set. This approach is less
  3673. than ideal for two reasons. First, it can be expensive because it
  3674. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  3675. locations. Second, in the special case where two locations hold the
  3676. same value (because one was assigned to the other), they can be live
  3677. at the same time without interfering with each other.
  3678. A better way to compute the interference graph is to focus on
  3679. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3680. must not overwrite something in a live location. So for each
  3681. instruction, we create an edge between the locations being written to
  3682. and the live locations. (Except that one should not create self
  3683. edges.) Note that for the \key{callq} instruction, we consider all of
  3684. the caller-saved registers as being written to, so an edge is added
  3685. between every live variable and every caller-saved register. For
  3686. \key{movq}, we deal with the above-mentioned special case by not
  3687. adding an edge between a live variable $v$ and the destination if $v$
  3688. matches the source. So we have the following two rules.
  3689. \begin{enumerate}
  3690. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3691. $d$, then add the edge $(d,v)$ for every $v \in
  3692. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3693. \item For any other instruction $I_k$, for every $d \in W(k)$
  3694. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3695. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3696. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3697. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3698. %% \item If instruction $I_k$ is of the form \key{callq}
  3699. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3700. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3701. \end{enumerate}
  3702. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3703. the above rules to each instruction. We highlight a few of the
  3704. instructions. The first instruction is \lstinline{movq $1, v} and the
  3705. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  3706. interferes with \code{rsp}.
  3707. %
  3708. The fourth instruction is \lstinline{addq $7, x} and the live-after
  3709. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  3710. interferes with \ttm{w} and \ttm{rsp}.
  3711. %
  3712. The next instruction is \lstinline{movq x, y} and the live-after set
  3713. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  3714. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  3715. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  3716. same value. Figure~\ref{fig:interference-results} lists the
  3717. interference results for all of the instructions and the resulting
  3718. interference graph is shown in Figure~\ref{fig:interfere}.
  3719. \begin{figure}[tbp]
  3720. \begin{quote}
  3721. \begin{tabular}{ll}
  3722. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3723. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3724. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3725. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3726. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3727. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3728. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3729. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3730. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3731. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3732. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3733. \lstinline!jmp conclusion!& no interference.
  3734. \end{tabular}
  3735. \end{quote}
  3736. \caption{Interference results for the running example.}
  3737. \label{fig:interference-results}
  3738. \end{figure}
  3739. \begin{figure}[tbp]
  3740. \large
  3741. \[
  3742. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3743. \node (rax) at (0,0) {$\ttm{rax}$};
  3744. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3745. \node (t1) at (0,2) {$\ttm{t}$};
  3746. \node (z) at (3,2) {$\ttm{z}$};
  3747. \node (x) at (6,2) {$\ttm{x}$};
  3748. \node (y) at (3,0) {$\ttm{y}$};
  3749. \node (w) at (6,0) {$\ttm{w}$};
  3750. \node (v) at (9,0) {$\ttm{v}$};
  3751. \draw (t1) to (rax);
  3752. \draw (t1) to (z);
  3753. \draw (z) to (y);
  3754. \draw (z) to (w);
  3755. \draw (x) to (w);
  3756. \draw (y) to (w);
  3757. \draw (v) to (w);
  3758. \draw (v) to (rsp);
  3759. \draw (w) to (rsp);
  3760. \draw (x) to (rsp);
  3761. \draw (y) to (rsp);
  3762. \path[-.,bend left=15] (z) edge node {} (rsp);
  3763. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3764. \draw (rax) to (rsp);
  3765. \end{tikzpicture}
  3766. \]
  3767. \caption{The interference graph of the example program.}
  3768. \label{fig:interfere}
  3769. \end{figure}
  3770. %% Our next concern is to choose a data structure for representing the
  3771. %% interference graph. There are many choices for how to represent a
  3772. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3773. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3774. %% data structure is to study the algorithm that uses the data structure,
  3775. %% determine what operations need to be performed, and then choose the
  3776. %% data structure that provide the most efficient implementations of
  3777. %% those operations. Often times the choice of data structure can have an
  3778. %% effect on the time complexity of the algorithm, as it does here. If
  3779. %% you skim the next section, you will see that the register allocation
  3780. %% algorithm needs to ask the graph for all of its vertices and, given a
  3781. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3782. %% correct choice of graph representation is that of an adjacency
  3783. %% list. There are helper functions in \code{utilities.rkt} for
  3784. %% representing graphs using the adjacency list representation:
  3785. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3786. %% (Appendix~\ref{appendix:utilities}).
  3787. %% %
  3788. %% \margincomment{\footnotesize To do: change to use the
  3789. %% Racket graph library. \\ --Jeremy}
  3790. %% %
  3791. %% In particular, those functions use a hash table to map each vertex to
  3792. %% the set of adjacent vertices, and the sets are represented using
  3793. %% Racket's \key{set}, which is also a hash table.
  3794. \begin{exercise}\normalfont
  3795. Implement the compiler pass named \code{build-interference} according
  3796. to the algorithm suggested above. We recommend using the \code{graph}
  3797. package to create and inspect the interference graph. The output
  3798. graph of this pass should be stored in the $\itm{info}$ field of the
  3799. program, under the key \code{conflicts}.
  3800. \end{exercise}
  3801. \section{Graph Coloring via Sudoku}
  3802. \label{sec:graph-coloring}
  3803. \index{graph coloring}
  3804. \index{Sudoku}
  3805. \index{color}
  3806. We come to the main event, mapping variables to registers and stack
  3807. locations. Variables that interfere with each other must be mapped to
  3808. different locations. In terms of the interference graph, this means
  3809. that adjacent vertices must be mapped to different locations. If we
  3810. think of locations as colors, the register allocation problem becomes
  3811. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3812. The reader may be more familiar with the graph coloring problem than he
  3813. or she realizes; the popular game of Sudoku is an instance of the
  3814. graph coloring problem. The following describes how to build a graph
  3815. out of an initial Sudoku board.
  3816. \begin{itemize}
  3817. \item There is one vertex in the graph for each Sudoku square.
  3818. \item There is an edge between two vertices if the corresponding squares
  3819. are in the same row, in the same column, or if the squares are in
  3820. the same $3\times 3$ region.
  3821. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3822. \item Based on the initial assignment of numbers to squares in the
  3823. Sudoku board, assign the corresponding colors to the corresponding
  3824. vertices in the graph.
  3825. \end{itemize}
  3826. If you can color the remaining vertices in the graph with the nine
  3827. colors, then you have also solved the corresponding game of Sudoku.
  3828. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3829. the corresponding graph with colored vertices. We map the Sudoku
  3830. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3831. sampling of the vertices (the colored ones) because showing edges for
  3832. all of the vertices would make the graph unreadable.
  3833. \begin{figure}[tbp]
  3834. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3835. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3836. \caption{A Sudoku game board and the corresponding colored graph.}
  3837. \label{fig:sudoku-graph}
  3838. \end{figure}
  3839. It turns out that some techniques for playing Sudoku correspond to
  3840. heuristics used in graph coloring algorithms. For example, one of the
  3841. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3842. a process of elimination to determine what numbers are no longer
  3843. available for a square and write down those numbers in the square
  3844. (writing very small). For example, if the number $1$ is assigned to a
  3845. square, then write the pencil mark $1$ in all the squares in the same
  3846. row, column, and region.
  3847. %
  3848. The Pencil Marks technique corresponds to the notion of
  3849. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3850. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3851. are no longer available. In graph terminology, we have the following
  3852. definition:
  3853. \begin{equation*}
  3854. \mathrm{saturation}(u) = \{ c \mid \exists v. v \in \mathrm{neighbors}(u)
  3855. \text{ and } \mathrm{color}(v) = c \}
  3856. \end{equation*}
  3857. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3858. edge with $u$.
  3859. Using the Pencil Marks technique leads to a simple strategy for
  3860. filling in numbers: if there is a square with only one possible number
  3861. left, then choose that number! But what if there are no squares with
  3862. only one possibility left? One brute-force approach is to try them
  3863. all: choose the first one and if it ultimately leads to a solution,
  3864. great. If not, backtrack and choose the next possibility. One good
  3865. thing about Pencil Marks is that it reduces the degree of branching in
  3866. the search tree. Nevertheless, backtracking can be horribly time
  3867. consuming. One way to reduce the amount of backtracking is to use the
  3868. most-constrained-first heuristic. That is, when choosing a square,
  3869. always choose one with the fewest possibilities left (the vertex with
  3870. the highest saturation). The idea is that choosing highly constrained
  3871. squares earlier rather than later is better because later on there may
  3872. not be any possibilities left in the highly saturated squares.
  3873. However, register allocation is easier than Sudoku because the
  3874. register allocator can map variables to stack locations when the
  3875. registers run out. Thus, it makes sense to replace backtracking with
  3876. greedy search: make the best choice at the time and keep going. We
  3877. still wish to minimize the number of colors needed, so we use the
  3878. most-constrained-first heuristic in the greedy search.
  3879. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3880. algorithm for register allocation based on saturation and the
  3881. most-constrained-first heuristic. It is roughly equivalent to the
  3882. DSATUR
  3883. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3884. as in Sudoku, the algorithm represents colors with integers. The
  3885. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3886. for register allocation. The integers $k$ and larger correspond to
  3887. stack locations. The registers that are not used for register
  3888. allocation, such as \code{rax}, are assigned to negative integers. In
  3889. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3890. %% One might wonder why we include registers at all in the liveness
  3891. %% analysis and interference graph. For example, we never allocate a
  3892. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3893. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3894. %% to use register for passing arguments to functions, it will be
  3895. %% necessary for those registers to appear in the interference graph
  3896. %% because those registers will also be assigned to variables, and we
  3897. %% don't want those two uses to encroach on each other. Regarding
  3898. %% registers such as \code{rax} and \code{rsp} that are not used for
  3899. %% variables, we could omit them from the interference graph but that
  3900. %% would require adding special cases to our algorithm, which would
  3901. %% complicate the logic for little gain.
  3902. \begin{figure}[btp]
  3903. \centering
  3904. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3905. Algorithm: DSATUR
  3906. Input: a graph |$G$|
  3907. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3908. |$W \gets \mathrm{vertices}(G)$|
  3909. while |$W \neq \emptyset$| do
  3910. pick a vertex |$u$| from |$W$| with the highest saturation,
  3911. breaking ties randomly
  3912. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3913. |$\mathrm{color}[u] \gets c$|
  3914. |$W \gets W - \{u\}$|
  3915. \end{lstlisting}
  3916. \caption{The saturation-based greedy graph coloring algorithm.}
  3917. \label{fig:satur-algo}
  3918. \end{figure}
  3919. With the DSATUR algorithm in hand, let us return to the running
  3920. example and consider how to color the interference graph in
  3921. Figure~\ref{fig:interfere}.
  3922. %
  3923. We start by assigning the register nodes to their own color. For
  3924. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3925. assigned $-2$. The variables are not yet colored, so they are
  3926. annotated with a dash. We then update the saturation for vertices that
  3927. are adjacent to a register, obtaining the following annotated
  3928. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3929. it interferes with both \code{rax} and \code{rsp}.
  3930. \[
  3931. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3932. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3933. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3934. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3935. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3936. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3937. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3938. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3939. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3940. \draw (t1) to (rax);
  3941. \draw (t1) to (z);
  3942. \draw (z) to (y);
  3943. \draw (z) to (w);
  3944. \draw (x) to (w);
  3945. \draw (y) to (w);
  3946. \draw (v) to (w);
  3947. \draw (v) to (rsp);
  3948. \draw (w) to (rsp);
  3949. \draw (x) to (rsp);
  3950. \draw (y) to (rsp);
  3951. \path[-.,bend left=15] (z) edge node {} (rsp);
  3952. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3953. \draw (rax) to (rsp);
  3954. \end{tikzpicture}
  3955. \]
  3956. The algorithm says to select a maximally saturated vertex. So we pick
  3957. $\ttm{t}$ and color it with the first available integer, which is
  3958. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3959. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3960. \[
  3961. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3962. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3963. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3964. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3965. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3966. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3967. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3968. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3969. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3970. \draw (t1) to (rax);
  3971. \draw (t1) to (z);
  3972. \draw (z) to (y);
  3973. \draw (z) to (w);
  3974. \draw (x) to (w);
  3975. \draw (y) to (w);
  3976. \draw (v) to (w);
  3977. \draw (v) to (rsp);
  3978. \draw (w) to (rsp);
  3979. \draw (x) to (rsp);
  3980. \draw (y) to (rsp);
  3981. \path[-.,bend left=15] (z) edge node {} (rsp);
  3982. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3983. \draw (rax) to (rsp);
  3984. \end{tikzpicture}
  3985. \]
  3986. We repeat the process, selecting the next maximally saturated vertex,
  3987. which is \code{z}, and color it with the first available number, which
  3988. is $1$. We add $1$ to the saturation for the neighboring vertices
  3989. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3990. \[
  3991. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3992. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3993. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3994. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3995. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3996. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3997. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3998. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3999. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4000. \draw (t1) to (rax);
  4001. \draw (t1) to (z);
  4002. \draw (z) to (y);
  4003. \draw (z) to (w);
  4004. \draw (x) to (w);
  4005. \draw (y) to (w);
  4006. \draw (v) to (w);
  4007. \draw (v) to (rsp);
  4008. \draw (w) to (rsp);
  4009. \draw (x) to (rsp);
  4010. \draw (y) to (rsp);
  4011. \path[-.,bend left=15] (z) edge node {} (rsp);
  4012. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4013. \draw (rax) to (rsp);
  4014. \end{tikzpicture}
  4015. \]
  4016. The most saturated vertices are now \code{w} and \code{y}. We color
  4017. \code{w} with the first available color, which is $0$.
  4018. \[
  4019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4020. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4021. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4022. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4023. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4024. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4025. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4026. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4027. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4028. \draw (t1) to (rax);
  4029. \draw (t1) to (z);
  4030. \draw (z) to (y);
  4031. \draw (z) to (w);
  4032. \draw (x) to (w);
  4033. \draw (y) to (w);
  4034. \draw (v) to (w);
  4035. \draw (v) to (rsp);
  4036. \draw (w) to (rsp);
  4037. \draw (x) to (rsp);
  4038. \draw (y) to (rsp);
  4039. \path[-.,bend left=15] (z) edge node {} (rsp);
  4040. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4041. \draw (rax) to (rsp);
  4042. \end{tikzpicture}
  4043. \]
  4044. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4045. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4046. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4047. and \code{z}, whose colors are $0$ and $1$ respectively.
  4048. \[
  4049. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4050. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4051. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4052. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4053. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4054. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4055. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4056. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4057. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4058. \draw (t1) to (rax);
  4059. \draw (t1) to (z);
  4060. \draw (z) to (y);
  4061. \draw (z) to (w);
  4062. \draw (x) to (w);
  4063. \draw (y) to (w);
  4064. \draw (v) to (w);
  4065. \draw (v) to (rsp);
  4066. \draw (w) to (rsp);
  4067. \draw (x) to (rsp);
  4068. \draw (y) to (rsp);
  4069. \path[-.,bend left=15] (z) edge node {} (rsp);
  4070. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4071. \draw (rax) to (rsp);
  4072. \end{tikzpicture}
  4073. \]
  4074. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4075. \[
  4076. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4077. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4078. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4079. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4080. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4081. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4082. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4083. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4084. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4085. \draw (t1) to (rax);
  4086. \draw (t1) to (z);
  4087. \draw (z) to (y);
  4088. \draw (z) to (w);
  4089. \draw (x) to (w);
  4090. \draw (y) to (w);
  4091. \draw (v) to (w);
  4092. \draw (v) to (rsp);
  4093. \draw (w) to (rsp);
  4094. \draw (x) to (rsp);
  4095. \draw (y) to (rsp);
  4096. \path[-.,bend left=15] (z) edge node {} (rsp);
  4097. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4098. \draw (rax) to (rsp);
  4099. \end{tikzpicture}
  4100. \]
  4101. In the last step of the algorithm, we color \code{x} with $1$.
  4102. \[
  4103. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4104. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4105. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4106. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4107. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4108. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4109. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4110. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4111. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4112. \draw (t1) to (rax);
  4113. \draw (t1) to (z);
  4114. \draw (z) to (y);
  4115. \draw (z) to (w);
  4116. \draw (x) to (w);
  4117. \draw (y) to (w);
  4118. \draw (v) to (w);
  4119. \draw (v) to (rsp);
  4120. \draw (w) to (rsp);
  4121. \draw (x) to (rsp);
  4122. \draw (y) to (rsp);
  4123. \path[-.,bend left=15] (z) edge node {} (rsp);
  4124. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4125. \draw (rax) to (rsp);
  4126. \end{tikzpicture}
  4127. \]
  4128. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  4129. \small
  4130. \begin{tcolorbox}[title=Priority Queue]
  4131. A \emph{priority queue} is a collection of items in which the
  4132. removal of items is governed by priority. In a ``min'' queue,
  4133. lower priority items are removed first. An implementation is in
  4134. \code{priority\_queue.rkt} of the support code. \index{priority
  4135. queue} \index{minimum priority queue}
  4136. \begin{description}
  4137. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4138. priority queue that uses the $\itm{cmp}$ predicate to determine
  4139. whether its first argument has lower or equal priority to its
  4140. second argument.
  4141. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4142. items in the queue.
  4143. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4144. the item into the queue and returns a handle for the item in the
  4145. queue.
  4146. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4147. the lowest priority.
  4148. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4149. notifies the queue that the priority has decreased for the item
  4150. associated with the given handle.
  4151. \end{description}
  4152. \end{tcolorbox}
  4153. \end{wrapfigure}
  4154. We recommend creating an auxiliary function named \code{color-graph}
  4155. that takes an interference graph and a list of all the variables in
  4156. the program. This function should return a mapping of variables to
  4157. their colors (represented as natural numbers). By creating this helper
  4158. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4159. when we add support for functions.
  4160. To prioritize the processing of highly saturated nodes inside the
  4161. \code{color-graph} function, we recommend using the priority queue
  4162. data structure (see the side bar on the right). In addition, you will
  4163. need to maintain a mapping from variables to their ``handles'' in the
  4164. priority queue so that you can notify the priority queue when their
  4165. saturation changes.
  4166. With the coloring complete, we finalize the assignment of variables to
  4167. registers and stack locations. We map the first $k$ colors to the $k$
  4168. registers and the rest of the colors to stack locations. Suppose for
  4169. the moment that we have just one register to use for register
  4170. allocation, \key{rcx}. Then we have the following map from colors to
  4171. locations.
  4172. \[
  4173. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4174. \]
  4175. Composing this mapping with the coloring, we arrive at the following
  4176. assignment of variables to locations.
  4177. \begin{gather*}
  4178. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4179. \ttm{w} \mapsto \key{\%rcx}, \,
  4180. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4181. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4182. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4183. \ttm{t} \mapsto \key{\%rcx} \}
  4184. \end{gather*}
  4185. Adapt the code from the \code{assign-homes} pass
  4186. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4187. assigned location. Applying the above assignment to our running
  4188. example, on the left, yields the program on the right.
  4189. % why frame size of 32? -JGS
  4190. \begin{center}
  4191. \begin{minipage}{0.3\textwidth}
  4192. \begin{lstlisting}
  4193. movq $1, v
  4194. movq $42, w
  4195. movq v, x
  4196. addq $7, x
  4197. movq x, y
  4198. movq x, z
  4199. addq w, z
  4200. movq y, t
  4201. negq t
  4202. movq z, %rax
  4203. addq t, %rax
  4204. jmp conclusion
  4205. \end{lstlisting}
  4206. \end{minipage}
  4207. $\Rightarrow\qquad$
  4208. \begin{minipage}{0.45\textwidth}
  4209. \begin{lstlisting}
  4210. movq $1, -8(%rbp)
  4211. movq $42, %rcx
  4212. movq -8(%rbp), -8(%rbp)
  4213. addq $7, -8(%rbp)
  4214. movq -8(%rbp), -16(%rbp)
  4215. movq -8(%rbp), -8(%rbp)
  4216. addq %rcx, -8(%rbp)
  4217. movq -16(%rbp), %rcx
  4218. negq %rcx
  4219. movq -8(%rbp), %rax
  4220. addq %rcx, %rax
  4221. jmp conclusion
  4222. \end{lstlisting}
  4223. \end{minipage}
  4224. \end{center}
  4225. \begin{exercise}\normalfont
  4226. %
  4227. Implement the compiler pass \code{allocate-registers}.
  4228. %
  4229. Create five programs that exercise all of the register allocation
  4230. algorithm, including spilling variables to the stack.
  4231. %
  4232. Replace \code{assign-homes} in the list of \code{passes} in the
  4233. \code{run-tests.rkt} script with the three new passes:
  4234. \code{uncover-live}, \code{build-interference}, and
  4235. \code{allocate-registers}.
  4236. %
  4237. Temporarily remove the \code{print-x86} pass from the list of passes
  4238. and the call to \code{compiler-tests}.
  4239. %
  4240. Run the script to test the register allocator.
  4241. \end{exercise}
  4242. \section{Patch Instructions}
  4243. \label{sec:patch-instructions}
  4244. The remaining step in the compilation to x86 is to ensure that the
  4245. instructions have at most one argument that is a memory access.
  4246. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  4247. is problematic. The fix is to first move \code{-8(\%rbp)}
  4248. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  4249. %
  4250. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4251. problematic, but they can be fixed by simply deleting them. In
  4252. general, we recommend deleting all the trivial moves whose source and
  4253. destination are the same location.
  4254. %
  4255. The following is the output of \code{patch-instructions} on the
  4256. running example.
  4257. \begin{center}
  4258. \begin{minipage}{0.4\textwidth}
  4259. \begin{lstlisting}
  4260. movq $1, -8(%rbp)
  4261. movq $42, %rcx
  4262. movq -8(%rbp), -8(%rbp)
  4263. addq $7, -8(%rbp)
  4264. movq -8(%rbp), -16(%rbp)
  4265. movq -8(%rbp), -8(%rbp)
  4266. addq %rcx, -8(%rbp)
  4267. movq -16(%rbp), %rcx
  4268. negq %rcx
  4269. movq -8(%rbp), %rax
  4270. addq %rcx, %rax
  4271. jmp conclusion
  4272. \end{lstlisting}
  4273. \end{minipage}
  4274. $\Rightarrow\qquad$
  4275. \begin{minipage}{0.45\textwidth}
  4276. \begin{lstlisting}
  4277. movq $1, -8(%rbp)
  4278. movq $42, %rcx
  4279. addq $7, -8(%rbp)
  4280. movq -8(%rbp), %rax
  4281. movq %rax, -16(%rbp)
  4282. addq %rcx, -8(%rbp)
  4283. movq -16(%rbp), %rcx
  4284. negq %rcx
  4285. movq -8(%rbp), %rax
  4286. addq %rcx, %rax
  4287. jmp conclusion
  4288. \end{lstlisting}
  4289. \end{minipage}
  4290. \end{center}
  4291. \begin{exercise}\normalfont
  4292. %
  4293. Implement the \code{patch-instructions} compiler pass.
  4294. %
  4295. Insert it after \code{allocate-registers} in the list of \code{passes}
  4296. in the \code{run-tests.rkt} script.
  4297. %
  4298. Run the script to test the \code{patch-instructions} pass.
  4299. \end{exercise}
  4300. \section{Print x86}
  4301. \label{sec:print-x86-reg-alloc}
  4302. \index{calling conventions}
  4303. \index{prelude}\index{conclusion}
  4304. Recall that the \code{print-x86} pass generates the prelude and
  4305. conclusion instructions to satisfy the x86 calling conventions
  4306. (Section~\ref{sec:calling-conventions}). With the addition of the
  4307. register allocator, the callee-saved registers used by the register
  4308. allocator must be saved in the prelude and restored in the conclusion.
  4309. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  4310. of \code{X86Program} named \code{used-callee} that stores the set of
  4311. callee-saved registers that were assigned to variables. The
  4312. \code{print-x86} pass can then access this information to decide which
  4313. callee-saved registers need to be saved and restored.
  4314. %
  4315. When calculating the size of the frame to adjust the \code{rsp} in the
  4316. prelude, make sure to take into account the space used for saving the
  4317. callee-saved registers. Also, don't forget that the frame needs to be
  4318. a multiple of 16 bytes!
  4319. An overview of all of the passes involved in register allocation is
  4320. shown in Figure~\ref{fig:reg-alloc-passes}.
  4321. \begin{figure}[tbp]
  4322. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4323. \node (Rvar) at (0,2) {\large \LangVar{}};
  4324. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4325. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4326. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4327. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4328. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4329. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4330. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4331. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4332. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4333. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4334. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  4335. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  4336. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  4337. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4338. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4339. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4340. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4341. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  4342. \end{tikzpicture}
  4343. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  4344. \label{fig:reg-alloc-passes}
  4345. \end{figure}
  4346. \begin{exercise}\normalfont
  4347. Update the \code{print-x86} pass as described in this section.
  4348. %
  4349. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  4350. list of passes and the call to \code{compiler-tests}.
  4351. %
  4352. Run the script to test the complete compiler for \LangVar{} that
  4353. performs register allocation.
  4354. \end{exercise}
  4355. \section{Challenge: Move Biasing}
  4356. \label{sec:move-biasing}
  4357. \index{move biasing}
  4358. This section describes an enhancement to the register allocator for
  4359. students looking for an extra challenge or who have a deeper interest
  4360. in register allocation.
  4361. To motivate the need for move biasing we return to the running example
  4362. but this time use all of the general purpose registers. So we have
  4363. the following mapping of color numbers to registers.
  4364. \[
  4365. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  4366. \]
  4367. Using the same assignment of variables to color numbers that was
  4368. produced by the register allocator described in the last section, we
  4369. get the following program.
  4370. \begin{center}
  4371. \begin{minipage}{0.3\textwidth}
  4372. \begin{lstlisting}
  4373. movq $1, v
  4374. movq $42, w
  4375. movq v, x
  4376. addq $7, x
  4377. movq x, y
  4378. movq x, z
  4379. addq w, z
  4380. movq y, t
  4381. negq t
  4382. movq z, %rax
  4383. addq t, %rax
  4384. jmp conclusion
  4385. \end{lstlisting}
  4386. \end{minipage}
  4387. $\Rightarrow\qquad$
  4388. \begin{minipage}{0.45\textwidth}
  4389. \begin{lstlisting}
  4390. movq $1, %rdx
  4391. movq $42, %rcx
  4392. movq %rdx, %rdx
  4393. addq $7, %rdx
  4394. movq %rdx, %rsi
  4395. movq %rdx, %rdx
  4396. addq %rcx, %rdx
  4397. movq %rsi, %rcx
  4398. negq %rcx
  4399. movq %rdx, %rax
  4400. addq %rcx, %rax
  4401. jmp conclusion
  4402. \end{lstlisting}
  4403. \end{minipage}
  4404. \end{center}
  4405. In the above output code there are two \key{movq} instructions that
  4406. can be removed because their source and target are the same. However,
  4407. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  4408. register, we could instead remove three \key{movq} instructions. We
  4409. can accomplish this by taking into account which variables appear in
  4410. \key{movq} instructions with which other variables.
  4411. We say that two variables $p$ and $q$ are \emph{move
  4412. related}\index{move related} if they participate together in a
  4413. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  4414. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  4415. for a variable, it should prefer a color that has already been used
  4416. for a move-related variable (assuming that they do not interfere). Of
  4417. course, this preference should not override the preference for
  4418. registers over stack locations. This preference should be used as a
  4419. tie breaker when choosing between registers or when choosing between
  4420. stack locations.
  4421. We recommend representing the move relationships in a graph, similar
  4422. to how we represented interference. The following is the \emph{move
  4423. graph} for our running example.
  4424. \[
  4425. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4426. \node (rax) at (0,0) {$\ttm{rax}$};
  4427. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4428. \node (t) at (0,2) {$\ttm{t}$};
  4429. \node (z) at (3,2) {$\ttm{z}$};
  4430. \node (x) at (6,2) {$\ttm{x}$};
  4431. \node (y) at (3,0) {$\ttm{y}$};
  4432. \node (w) at (6,0) {$\ttm{w}$};
  4433. \node (v) at (9,0) {$\ttm{v}$};
  4434. \draw (v) to (x);
  4435. \draw (x) to (y);
  4436. \draw (x) to (z);
  4437. \draw (y) to (t);
  4438. \end{tikzpicture}
  4439. \]
  4440. Now we replay the graph coloring, pausing to see the coloring of
  4441. \code{y}. Recall the following configuration. The most saturated vertices
  4442. were \code{w} and \code{y}.
  4443. \[
  4444. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4445. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4446. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4447. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4448. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4449. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4450. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4451. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4452. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4453. \draw (t1) to (rax);
  4454. \draw (t1) to (z);
  4455. \draw (z) to (y);
  4456. \draw (z) to (w);
  4457. \draw (x) to (w);
  4458. \draw (y) to (w);
  4459. \draw (v) to (w);
  4460. \draw (v) to (rsp);
  4461. \draw (w) to (rsp);
  4462. \draw (x) to (rsp);
  4463. \draw (y) to (rsp);
  4464. \path[-.,bend left=15] (z) edge node {} (rsp);
  4465. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4466. \draw (rax) to (rsp);
  4467. \end{tikzpicture}
  4468. \]
  4469. %
  4470. Last time we chose to color \code{w} with $0$. But this time we see
  4471. that \code{w} is not move related to any vertex, but \code{y} is move
  4472. related to \code{t}. So we choose to color \code{y} the same color as
  4473. \code{t}, $0$.
  4474. \[
  4475. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4476. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4477. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4478. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4479. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4480. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4481. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  4482. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  4483. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4484. \draw (t1) to (rax);
  4485. \draw (t1) to (z);
  4486. \draw (z) to (y);
  4487. \draw (z) to (w);
  4488. \draw (x) to (w);
  4489. \draw (y) to (w);
  4490. \draw (v) to (w);
  4491. \draw (v) to (rsp);
  4492. \draw (w) to (rsp);
  4493. \draw (x) to (rsp);
  4494. \draw (y) to (rsp);
  4495. \path[-.,bend left=15] (z) edge node {} (rsp);
  4496. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4497. \draw (rax) to (rsp);
  4498. \end{tikzpicture}
  4499. \]
  4500. Now \code{w} is the most saturated, so we color it $2$.
  4501. \[
  4502. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4503. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4504. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4505. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4506. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4507. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  4508. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4509. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4510. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  4511. \draw (t1) to (rax);
  4512. \draw (t1) to (z);
  4513. \draw (z) to (y);
  4514. \draw (z) to (w);
  4515. \draw (x) to (w);
  4516. \draw (y) to (w);
  4517. \draw (v) to (w);
  4518. \draw (v) to (rsp);
  4519. \draw (w) to (rsp);
  4520. \draw (x) to (rsp);
  4521. \draw (y) to (rsp);
  4522. \path[-.,bend left=15] (z) edge node {} (rsp);
  4523. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4524. \draw (rax) to (rsp);
  4525. \end{tikzpicture}
  4526. \]
  4527. At this point, vertices \code{x} and \code{v} are most saturated, but
  4528. \code{x} is move related to \code{y} and \code{z}, so we color
  4529. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  4530. \[
  4531. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4532. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4533. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4534. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4535. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4536. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  4537. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4538. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4539. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  4540. \draw (t1) to (rax);
  4541. \draw (t) to (z);
  4542. \draw (z) to (y);
  4543. \draw (z) to (w);
  4544. \draw (x) to (w);
  4545. \draw (y) to (w);
  4546. \draw (v) to (w);
  4547. \draw (v) to (rsp);
  4548. \draw (w) to (rsp);
  4549. \draw (x) to (rsp);
  4550. \draw (y) to (rsp);
  4551. \path[-.,bend left=15] (z) edge node {} (rsp);
  4552. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4553. \draw (rax) to (rsp);
  4554. \end{tikzpicture}
  4555. \]
  4556. So we have the following assignment of variables to registers.
  4557. \begin{gather*}
  4558. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  4559. \ttm{w} \mapsto \key{\%rsi}, \,
  4560. \ttm{x} \mapsto \key{\%rcx}, \,
  4561. \ttm{y} \mapsto \key{\%rcx}, \,
  4562. \ttm{z} \mapsto \key{\%rdx}, \,
  4563. \ttm{t} \mapsto \key{\%rcx} \}
  4564. \end{gather*}
  4565. We apply this register assignment to the running example, on the left,
  4566. to obtain the code in the middle. The \code{patch-instructions} then
  4567. removes the three trivial moves to obtain the code on the right.
  4568. \begin{minipage}{0.25\textwidth}
  4569. \begin{lstlisting}
  4570. movq $1, v
  4571. movq $42, w
  4572. movq v, x
  4573. addq $7, x
  4574. movq x, y
  4575. movq x, z
  4576. addq w, z
  4577. movq y, t
  4578. negq t
  4579. movq z, %rax
  4580. addq t, %rax
  4581. jmp conclusion
  4582. \end{lstlisting}
  4583. \end{minipage}
  4584. $\Rightarrow\qquad$
  4585. \begin{minipage}{0.25\textwidth}
  4586. \begin{lstlisting}
  4587. movq $1, %rcx
  4588. movq $42, %rsi
  4589. movq %rcx, %rcx
  4590. addq $7, %rcx
  4591. movq %rcx, %rcx
  4592. movq %rcx, %rdx
  4593. addq %rsi, %rdx
  4594. movq %rcx, %rcx
  4595. negq %rcx
  4596. movq %rdx, %rax
  4597. addq %rcx, %rax
  4598. jmp conclusion
  4599. \end{lstlisting}
  4600. \end{minipage}
  4601. $\Rightarrow\qquad$
  4602. \begin{minipage}{0.25\textwidth}
  4603. \begin{lstlisting}
  4604. movq $1, %rcx
  4605. movq $42, %rsi
  4606. addq $7, %rcx
  4607. movq %rcx, %rdx
  4608. addq %rsi, %rdx
  4609. negq %rcx
  4610. movq %rdx, %rax
  4611. addq %rcx, %rax
  4612. jmp conclusion
  4613. \end{lstlisting}
  4614. \end{minipage}
  4615. \begin{exercise}\normalfont
  4616. Change your implementation of \code{allocate-registers} to take move
  4617. biasing into account. Create two new tests that include at least one
  4618. opportunity for move biasing and visually inspect the output x86
  4619. programs to make sure that your move biasing is working properly. Make
  4620. sure that your compiler still passes all of the tests.
  4621. \end{exercise}
  4622. \margincomment{\footnotesize To do: another neat challenge would be to do
  4623. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  4624. %% \subsection{Output of the Running Example}
  4625. %% \label{sec:reg-alloc-output}
  4626. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4627. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  4628. and move biasing. To demonstrate both the use of registers and the
  4629. stack, we have limited the register allocator to use just two
  4630. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  4631. of the \code{main} function, we push \code{rbx} onto the stack because
  4632. it is a callee-saved register and it was assigned to variable by the
  4633. register allocator. We subtract \code{8} from the \code{rsp} at the
  4634. end of the prelude to reserve space for the one spilled variable.
  4635. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  4636. Moving on the the \code{start} block, we see how the registers were
  4637. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  4638. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  4639. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  4640. that the prelude saved the callee-save register \code{rbx} onto the
  4641. stack. The spilled variables must be placed lower on the stack than
  4642. the saved callee-save registers, so in this case \code{w} is placed at
  4643. \code{-16(\%rbp)}.
  4644. In the \code{conclusion}\index{conclusion}, we undo the work that was
  4645. done in the prelude. We move the stack pointer up by \code{8} bytes
  4646. (the room for spilled variables), then we pop the old values of
  4647. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4648. \code{retq} to return control to the operating system.
  4649. \begin{figure}[tbp]
  4650. % var_test_28.rkt
  4651. % (use-minimal-set-of-registers! #t)
  4652. % and only rbx rcx
  4653. % tmp 0 rbx
  4654. % z 1 rcx
  4655. % y 0 rbx
  4656. % w 2 16(%rbp)
  4657. % v 0 rbx
  4658. % x 0 rbx
  4659. \begin{lstlisting}
  4660. start:
  4661. movq $1, %rbx
  4662. movq $42, -16(%rbp)
  4663. addq $7, %rbx
  4664. movq %rbx, %rcx
  4665. addq -16(%rbp), %rcx
  4666. negq %rbx
  4667. movq %rcx, %rax
  4668. addq %rbx, %rax
  4669. jmp conclusion
  4670. .globl main
  4671. main:
  4672. pushq %rbp
  4673. movq %rsp, %rbp
  4674. pushq %rbx
  4675. subq $8, %rsp
  4676. jmp start
  4677. conclusion:
  4678. addq $8, %rsp
  4679. popq %rbx
  4680. popq %rbp
  4681. retq
  4682. \end{lstlisting}
  4683. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  4684. \label{fig:running-example-x86}
  4685. \end{figure}
  4686. % challenge: prioritize variables based on execution frequencies
  4687. % and the number of uses of a variable
  4688. % challenge: enhance the coloring algorithm using Chaitin's
  4689. % approach of prioritizing high-degree variables
  4690. % by removing low-degree variables (coloring them later)
  4691. % from the interference graph
  4692. \section{Further Reading}
  4693. \label{sec:register-allocation-further-reading}
  4694. Early register allocation algorithms were developed for Fortran
  4695. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  4696. of graph coloring began in the late 1970s and early 1980s with the
  4697. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  4698. algorithm is based on the following observation of
  4699. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  4700. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  4701. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  4702. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  4703. different colors, but since there are less than $k$ of them, there
  4704. will be one or more colors left over to use for coloring $v$ in $G$.
  4705. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  4706. less than $k$ from the graph and recursively colors the rest of the
  4707. graph. Upon returning from the recursion, it colors $v$ with one of
  4708. the available colors and returns. \citet{Chaitin:1982vn} augments
  4709. this algorithm to handle spilling as follows. If there are no vertices
  4710. of degree lower than $k$ then pick a vertex at random, spill it,
  4711. remove it from the graph, and proceed recursively to color the rest of
  4712. the graph.
  4713. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  4714. move-related and that don't interfere with each other, a process
  4715. called \emph{coalescing}. While coalescing decreases the number of
  4716. moves, it can make the graph more difficult to
  4717. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  4718. which two variables are merged only if they have fewer than $k$
  4719. neighbors of high degree. \citet{George:1996aa} observe that
  4720. conservative coalescing is sometimes too conservative and make it more
  4721. aggressive by iterating the coalescing with the removal of low-degree
  4722. vertices.
  4723. %
  4724. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  4725. also propose \emph{biased coloring} in which a variable is assigned to
  4726. the same color as another move-related variable if possible, as
  4727. discussed in Section~\ref{sec:move-biasing}.
  4728. %
  4729. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  4730. performs coalescing, graph coloring, and spill code insertion until
  4731. all variables have been assigned a location.
  4732. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  4733. spills variables that don't have to be: a high-degree variable can be
  4734. colorable if many of its neighbors are assigned the same color.
  4735. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  4736. high-degree vertex is not immediately spilled. Instead the decision is
  4737. deferred until after the recursive call, at which point it is apparent
  4738. whether there is actually an available color or not. We observe that
  4739. this algorithm is equivalent to the smallest-last ordering
  4740. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  4741. be registers and the rest to be stack locations.
  4742. %% biased coloring
  4743. Earlier editions of the compiler course at Indiana University
  4744. \citep{Dybvig:2010aa} were based on the algorithm of
  4745. \citet{Briggs:1994kx}.
  4746. The smallest-last ordering algorithm is one of many \emph{greedy}
  4747. coloring algorithms. A greedy coloring algorithm visits all the
  4748. vertices in a particular order and assigns each one the first
  4749. available color. An \emph{offline} greedy algorithm chooses the
  4750. ordering up-front, prior to assigning colors. The algorithm of
  4751. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4752. ordering does not depend on the colors assigned, so the algorithm
  4753. could be split into two phases. Other orderings are possible. For
  4754. example, \citet{Chow:1984ys} order variables according an estimate of
  4755. runtime cost.
  4756. An \emph{online} greedy coloring algorithm uses information about the
  4757. current assignment of colors to influence the order in which the
  4758. remaining vertices are colored. The saturation-based algorithm
  4759. described in this chapter is one such algorithm. We choose to use
  4760. saturation-based coloring is because it is fun to introduce graph
  4761. coloring via Sudoku.
  4762. A register allocator may choose to map each variable to just one
  4763. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4764. variable to one or more locations. The later can be achieved by
  4765. \emph{live range splitting}, where a variable is replaced by several
  4766. variables that each handle part of its live
  4767. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4768. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4769. %% replacement algorithm, bottom-up local
  4770. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4771. %% Cooper: top-down (priority bassed), bottom-up
  4772. %% top-down
  4773. %% order variables by priority (estimated cost)
  4774. %% caveat: split variables into two groups:
  4775. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4776. %% color the constrained ones first
  4777. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4778. %% cite J. Cocke for an algorithm that colors variables
  4779. %% in a high-degree first ordering
  4780. %Register Allocation via Usage Counts, Freiburghouse CACM
  4781. \citet{Palsberg:2007si} observe that many of the interference graphs
  4782. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4783. that is, every cycle with four or more edges has an edge which is not
  4784. part of the cycle but which connects two vertices on the cycle. Such
  4785. graphs can be optimally colored by the greedy algorithm with a vertex
  4786. ordering determined by maximum cardinality search.
  4787. In situations where compile time is of utmost importance, such as in
  4788. just-in-time compilers, graph coloring algorithms can be too expensive
  4789. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4790. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4791. \chapter{Booleans and Control Flow}
  4792. \label{ch:Rif}
  4793. \index{Boolean}
  4794. \index{control flow}
  4795. \index{conditional expression}
  4796. The \LangInt{} and \LangVar{} languages only have a single kind of
  4797. value, integers. In this chapter we add a second kind of value, the
  4798. Booleans, to create the \LangIf{} language. The Boolean values
  4799. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4800. respectively in Racket. The \LangIf{} language includes several
  4801. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4802. \key{<}, etc.) and the conditional \key{if} expression. With the
  4803. addition of \key{if}, programs can have non-trivial control flow which
  4804. impacts \code{explicate-control} and liveness analysis. Also, because
  4805. we now have two kinds of values, we need to handle programs that apply
  4806. an operation to the wrong kind of value, such as \code{(not 1)}.
  4807. There are two language design options for such situations. One option
  4808. is to signal an error and the other is to provide a wider
  4809. interpretation of the operation. The Racket language uses a mixture of
  4810. these two options, depending on the operation and the kind of
  4811. value. For example, the result of \code{(not 1)} in Racket is
  4812. \code{\#f} because Racket treats non-zero integers as if they were
  4813. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4814. error in Racket because \code{car} expects a pair.
  4815. Typed Racket makes similar design choices as Racket, except much of
  4816. the error detection happens at compile time instead of run time. Typed
  4817. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4818. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4819. because Typed Racket expects the type of the argument to be of the
  4820. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4821. The \LangIf{} language performs type checking during compilation like
  4822. Typed Racket. In Chapter~\ref{ch:Rdyn} we study the
  4823. alternative choice, that is, a dynamically typed language like Racket.
  4824. The \LangIf{} language is a subset of Typed Racket; for some
  4825. operations we are more restrictive, for example, rejecting
  4826. \code{(not 1)}.
  4827. This chapter is organized as follows. We begin by defining the syntax
  4828. and interpreter for the \LangIf{} language
  4829. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4830. checking and build a type checker for \LangIf{}
  4831. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4832. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4833. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4834. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4835. discuss how our compiler passes change to accommodate Booleans and
  4836. conditional control flow. There is one new pass, named \code{shrink},
  4837. that translates some operators into others, thereby reducing the
  4838. number of operators that need to be handled in later passes. The
  4839. largest changes occur in \code{explicate-control}, to translate
  4840. \code{if} expressions into control-flow graphs
  4841. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4842. allocation, the liveness analysis now has multiple basic blocks to
  4843. process and there is the interesting question of how to handle
  4844. conditional jumps.
  4845. \section{The \LangIf{} Language}
  4846. \label{sec:lang-if}
  4847. The concrete syntax of the \LangIf{} language is defined in
  4848. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4849. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4850. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4851. \code{\#f}, and the conditional \code{if} expression. We expand the
  4852. operators to include
  4853. \begin{enumerate}
  4854. \item subtraction on integers,
  4855. \item the logical operators \key{and}, \key{or} and \key{not},
  4856. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4857. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4858. comparing integers.
  4859. \end{enumerate}
  4860. We reorganize the abstract syntax for the primitive operations in
  4861. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4862. them. This means that the grammar no longer checks whether the arity
  4863. of an operators matches the number of arguments. That responsibility
  4864. is moved to the type checker for \LangIf{}, which we introduce in
  4865. Section~\ref{sec:type-check-Rif}.
  4866. \begin{figure}[tp]
  4867. \centering
  4868. \fbox{
  4869. \begin{minipage}{0.96\textwidth}
  4870. \[
  4871. \begin{array}{lcl}
  4872. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4873. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4874. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4875. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4876. &\mid& \itm{bool}
  4877. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4878. \mid (\key{not}\;\Exp) \\
  4879. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4880. \LangIf{} &::=& \Exp
  4881. \end{array}
  4882. \]
  4883. \end{minipage}
  4884. }
  4885. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4886. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4887. \label{fig:Rif-concrete-syntax}
  4888. \end{figure}
  4889. \begin{figure}[tp]
  4890. \centering
  4891. \fbox{
  4892. \begin{minipage}{0.96\textwidth}
  4893. \[
  4894. \begin{array}{lcl}
  4895. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4896. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4897. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4898. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4899. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4900. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4901. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4902. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4903. \end{array}
  4904. \]
  4905. \end{minipage}
  4906. }
  4907. \caption{The abstract syntax of \LangIf{}.}
  4908. \label{fig:Rif-syntax}
  4909. \end{figure}
  4910. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4911. which inherits from the interpreter for \LangVar{}
  4912. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4913. evaluate to the corresponding Boolean values. The conditional
  4914. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4915. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4916. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4917. operations \code{not} and \code{and} behave as you might expect, but
  4918. note that the \code{and} operation is short-circuiting. That is, given
  4919. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4920. evaluated if $e_1$ evaluates to \code{\#f}.
  4921. With the increase in the number of primitive operations, the
  4922. interpreter would become repetitive without some care. We refactor
  4923. the case for \code{Prim}, moving the code that differs with each
  4924. operation into the \code{interp-op} method shown in in
  4925. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4926. separately because of its short-circuiting behavior.
  4927. \begin{figure}[tbp]
  4928. \begin{lstlisting}
  4929. (define interp-Rif-class
  4930. (class interp-Rvar-class
  4931. (super-new)
  4932. (define/public (interp-op op) ...)
  4933. (define/override ((interp-exp env) e)
  4934. (define recur (interp-exp env))
  4935. (match e
  4936. [(Bool b) b]
  4937. [(If cnd thn els)
  4938. (match (recur cnd)
  4939. [#t (recur thn)]
  4940. [#f (recur els)])]
  4941. [(Prim 'and (list e1 e2))
  4942. (match (recur e1)
  4943. [#t (match (recur e2) [#t #t] [#f #f])]
  4944. [#f #f])]
  4945. [(Prim op args)
  4946. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4947. [else ((super interp-exp env) e)]))
  4948. ))
  4949. (define (interp-Rif p)
  4950. (send (new interp-Rif-class) interp-program p))
  4951. \end{lstlisting}
  4952. \caption{Interpreter for the \LangIf{} language. (See
  4953. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4954. \label{fig:interp-Rif}
  4955. \end{figure}
  4956. \begin{figure}[tbp]
  4957. \begin{lstlisting}
  4958. (define/public (interp-op op)
  4959. (match op
  4960. ['+ fx+]
  4961. ['- fx-]
  4962. ['read read-fixnum]
  4963. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4964. ['or (lambda (v1 v2)
  4965. (cond [(and (boolean? v1) (boolean? v2))
  4966. (or v1 v2)]))]
  4967. ['eq? (lambda (v1 v2)
  4968. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4969. (and (boolean? v1) (boolean? v2))
  4970. (and (vector? v1) (vector? v2)))
  4971. (eq? v1 v2)]))]
  4972. ['< (lambda (v1 v2)
  4973. (cond [(and (fixnum? v1) (fixnum? v2))
  4974. (< v1 v2)]))]
  4975. ['<= (lambda (v1 v2)
  4976. (cond [(and (fixnum? v1) (fixnum? v2))
  4977. (<= v1 v2)]))]
  4978. ['> (lambda (v1 v2)
  4979. (cond [(and (fixnum? v1) (fixnum? v2))
  4980. (> v1 v2)]))]
  4981. ['>= (lambda (v1 v2)
  4982. (cond [(and (fixnum? v1) (fixnum? v2))
  4983. (>= v1 v2)]))]
  4984. [else (error 'interp-op "unknown operator")]))
  4985. \end{lstlisting}
  4986. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4987. \label{fig:interp-op-Rif}
  4988. \end{figure}
  4989. \section{Type Checking \LangIf{} Programs}
  4990. \label{sec:type-check-Rif}
  4991. \index{type checking}
  4992. \index{semantic analysis}
  4993. It is helpful to think about type checking in two complementary
  4994. ways. A type checker predicts the type of value that will be produced
  4995. by each expression in the program. For \LangIf{}, we have just two types,
  4996. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4997. \begin{lstlisting}
  4998. (+ 10 (- (+ 12 20)))
  4999. \end{lstlisting}
  5000. produces an \key{Integer} while
  5001. \begin{lstlisting}
  5002. (and (not #f) #t)
  5003. \end{lstlisting}
  5004. produces a \key{Boolean}.
  5005. Another way to think about type checking is that it enforces a set of
  5006. rules about which operators can be applied to which kinds of
  5007. values. For example, our type checker for \LangIf{} signals an error
  5008. for the below expression
  5009. \begin{lstlisting}
  5010. (not (+ 10 (- (+ 12 20))))
  5011. \end{lstlisting}
  5012. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  5013. but the type checker enforces the rule that the argument of \code{not}
  5014. must be a \key{Boolean}.
  5015. We implement type checking using classes and methods because they
  5016. provide the open recursion needed to reuse code as we extend the type
  5017. checker in later chapters, analogous to the use of classes and methods
  5018. for the interpreters (Section~\ref{sec:extensible-interp}).
  5019. We separate the type checker for the \LangVar{} fragment into its own
  5020. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  5021. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  5022. from the type checker for \LangVar{}. These type checkers are in the
  5023. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  5024. support code.
  5025. %
  5026. Each type checker is a structurally recursive function over the AST.
  5027. Given an input expression \code{e}, the type checker either signals an
  5028. error or returns an expression and its type (\key{Integer} or
  5029. \key{Boolean}). It returns an expression because there are situations
  5030. in which we want to change or update the expression.
  5031. Next we discuss the \code{match} cases in \code{type-check-exp} of
  5032. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  5033. \code{Integer}. To handle variables, the type checker uses the
  5034. environment \code{env} to map variables to types. Consider the case
  5035. for \key{let}. We type check the initializing expression to obtain
  5036. its type \key{T} and then associate type \code{T} with the variable
  5037. \code{x} in the environment used to type check the body of the
  5038. \key{let}. Thus, when the type checker encounters a use of variable
  5039. \code{x}, it can find its type in the environment. Regarding
  5040. primitive operators, we recursively analyze the arguments and then
  5041. invoke \code{type-check-op} to check whether the argument types are
  5042. allowed.
  5043. Several auxiliary methods are used in the type checker. The method
  5044. \code{operator-types} defines a dictionary that maps the operator
  5045. names to their parameter and return types. The \code{type-equal?}
  5046. method determines whether two types are equal, which for now simply
  5047. dispatches to \code{equal?} (deep equality). The
  5048. \code{check-type-equal?} method triggers an error if the two types are
  5049. not equal. The \code{type-check-op} method looks up the operator in
  5050. the \code{operator-types} dictionary and then checks whether the
  5051. argument types are equal to the parameter types. The result is the
  5052. return type of the operator.
  5053. \begin{figure}[tbp]
  5054. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5055. (define type-check-Rvar-class
  5056. (class object%
  5057. (super-new)
  5058. (define/public (operator-types)
  5059. '((+ . ((Integer Integer) . Integer))
  5060. (- . ((Integer) . Integer))
  5061. (read . (() . Integer))))
  5062. (define/public (type-equal? t1 t2) (equal? t1 t2))
  5063. (define/public (check-type-equal? t1 t2 e)
  5064. (unless (type-equal? t1 t2)
  5065. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  5066. (define/public (type-check-op op arg-types e)
  5067. (match (dict-ref (operator-types) op)
  5068. [`(,param-types . ,return-type)
  5069. (for ([at arg-types] [pt param-types])
  5070. (check-type-equal? at pt e))
  5071. return-type]
  5072. [else (error 'type-check-op "unrecognized ~a" op)]))
  5073. (define/public (type-check-exp env)
  5074. (lambda (e)
  5075. (match e
  5076. [(Int n) (values (Int n) 'Integer)]
  5077. [(Var x) (values (Var x) (dict-ref env x))]
  5078. [(Let x e body)
  5079. (define-values (e^ Te) ((type-check-exp env) e))
  5080. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  5081. (values (Let x e^ b) Tb)]
  5082. [(Prim op es)
  5083. (define-values (new-es ts)
  5084. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  5085. (values (Prim op new-es) (type-check-op op ts e))]
  5086. [else (error 'type-check-exp "couldn't match" e)])))
  5087. (define/public (type-check-program e)
  5088. (match e
  5089. [(Program info body)
  5090. (define-values (body^ Tb) ((type-check-exp '()) body))
  5091. (check-type-equal? Tb 'Integer body)
  5092. (Program info body^)]
  5093. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  5094. ))
  5095. (define (type-check-Rvar p)
  5096. (send (new type-check-Rvar-class) type-check-program p))
  5097. \end{lstlisting}
  5098. \caption{Type checker for the \LangVar{} language.}
  5099. \label{fig:type-check-Rvar}
  5100. \end{figure}
  5101. \begin{figure}[tbp]
  5102. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5103. (define type-check-Rif-class
  5104. (class type-check-Rvar-class
  5105. (super-new)
  5106. (inherit check-type-equal?)
  5107. (define/override (operator-types)
  5108. (append '((- . ((Integer Integer) . Integer))
  5109. (and . ((Boolean Boolean) . Boolean))
  5110. (or . ((Boolean Boolean) . Boolean))
  5111. (< . ((Integer Integer) . Boolean))
  5112. (<= . ((Integer Integer) . Boolean))
  5113. (> . ((Integer Integer) . Boolean))
  5114. (>= . ((Integer Integer) . Boolean))
  5115. (not . ((Boolean) . Boolean))
  5116. )
  5117. (super operator-types)))
  5118. (define/override (type-check-exp env)
  5119. (lambda (e)
  5120. (match e
  5121. [(Prim 'eq? (list e1 e2))
  5122. (define-values (e1^ T1) ((type-check-exp env) e1))
  5123. (define-values (e2^ T2) ((type-check-exp env) e2))
  5124. (check-type-equal? T1 T2 e)
  5125. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  5126. [(Bool b) (values (Bool b) 'Boolean)]
  5127. [(If cnd thn els)
  5128. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  5129. (define-values (thn^ Tt) ((type-check-exp env) thn))
  5130. (define-values (els^ Te) ((type-check-exp env) els))
  5131. (check-type-equal? Tc 'Boolean e)
  5132. (check-type-equal? Tt Te e)
  5133. (values (If cnd^ thn^ els^) Te)]
  5134. [else ((super type-check-exp env) e)])))
  5135. ))
  5136. (define (type-check-Rif p)
  5137. (send (new type-check-Rif-class) type-check-program p))
  5138. \end{lstlisting}
  5139. \caption{Type checker for the \LangIf{} language.}
  5140. \label{fig:type-check-Rif}
  5141. \end{figure}
  5142. Next we discuss the type checker for \LangIf{} in
  5143. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  5144. two arguments to have the same type. The type of a Boolean constant is
  5145. \code{Boolean}. The condition of an \code{if} must be of
  5146. \code{Boolean} type and the two branches must have the same type. The
  5147. \code{operator-types} function adds dictionary entries for the other
  5148. new operators.
  5149. \begin{exercise}\normalfont
  5150. Create 10 new test programs in \LangIf{}. Half of the programs should
  5151. have a type error. For those programs, create an empty file with the
  5152. same base name but with file extension \code{.tyerr}. For example, if
  5153. the test \code{cond\_test\_14.rkt} is expected to error, then create
  5154. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  5155. \code{interp-tests} and \code{compiler-tests} that a type error is
  5156. expected. The other half of the test programs should not have type
  5157. errors.
  5158. In the \code{run-tests.rkt} script, change the second argument of
  5159. \code{interp-tests} and \code{compiler-tests} to
  5160. \code{type-check-Rif}, which causes the type checker to run prior to
  5161. the compiler passes. Temporarily change the \code{passes} to an empty
  5162. list and run the script, thereby checking that the new test programs
  5163. either type check or not as intended.
  5164. \end{exercise}
  5165. \section{The \LangCIf{} Intermediate Language}
  5166. \label{sec:Cif}
  5167. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  5168. \LangCIf{} intermediate language. (The concrete syntax is in the
  5169. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  5170. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  5171. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  5172. \key{\#f} to the \Arg{} non-terminal.
  5173. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  5174. statements to the \Tail{} non-terminal. The condition of an \code{if}
  5175. statement is a comparison operation and the branches are \code{goto}
  5176. statements, making it straightforward to compile \code{if} statements
  5177. to x86.
  5178. \begin{figure}[tp]
  5179. \fbox{
  5180. \begin{minipage}{0.96\textwidth}
  5181. \small
  5182. \[
  5183. \begin{array}{lcl}
  5184. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  5185. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  5186. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  5187. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5188. &\mid& \UNIOP{\key{'not}}{\Atm}
  5189. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  5190. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  5191. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  5192. \mid \GOTO{\itm{label}} \\
  5193. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  5194. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  5195. \end{array}
  5196. \]
  5197. \end{minipage}
  5198. }
  5199. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  5200. (Figure~\ref{fig:c0-syntax}).}
  5201. \label{fig:c1-syntax}
  5202. \end{figure}
  5203. \section{The \LangXIf{} Language}
  5204. \label{sec:x86-if}
  5205. \index{x86} To implement the new logical operations, the comparison
  5206. operations, and the \key{if} expression, we need to delve further into
  5207. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  5208. define the concrete and abstract syntax for the \LangXIf{} subset
  5209. of x86, which includes instructions for logical operations,
  5210. comparisons, and conditional jumps.
  5211. One challenge is that x86 does not provide an instruction that
  5212. directly implements logical negation (\code{not} in \LangIf{} and
  5213. \LangCIf{}). However, the \code{xorq} instruction can be used to
  5214. encode \code{not}. The \key{xorq} instruction takes two arguments,
  5215. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  5216. bit of its arguments, and writes the results into its second argument.
  5217. Recall the truth table for exclusive-or:
  5218. \begin{center}
  5219. \begin{tabular}{l|cc}
  5220. & 0 & 1 \\ \hline
  5221. 0 & 0 & 1 \\
  5222. 1 & 1 & 0
  5223. \end{tabular}
  5224. \end{center}
  5225. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  5226. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  5227. for the bit $1$, the result is the opposite of the second bit. Thus,
  5228. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  5229. the first argument:
  5230. \[
  5231. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  5232. \qquad\Rightarrow\qquad
  5233. \begin{array}{l}
  5234. \key{movq}~ \Arg\key{,} \Var\\
  5235. \key{xorq}~ \key{\$1,} \Var
  5236. \end{array}
  5237. \]
  5238. \begin{figure}[tp]
  5239. \fbox{
  5240. \begin{minipage}{0.96\textwidth}
  5241. \[
  5242. \begin{array}{lcl}
  5243. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  5244. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  5245. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  5246. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  5247. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  5248. \key{subq} \; \Arg\key{,} \Arg \mid
  5249. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  5250. && \gray{ \key{callq} \; \itm{label} \mid
  5251. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  5252. && \gray{ \itm{label}\key{:}\; \Instr }
  5253. \mid \key{xorq}~\Arg\key{,}~\Arg
  5254. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  5255. && \key{set}cc~\Arg
  5256. \mid \key{movzbq}~\Arg\key{,}~\Arg
  5257. \mid \key{j}cc~\itm{label}
  5258. \\
  5259. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  5260. & & \gray{ \key{main:} \; \Instr\ldots }
  5261. \end{array}
  5262. \]
  5263. \end{minipage}
  5264. }
  5265. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  5266. \label{fig:x86-1-concrete}
  5267. \end{figure}
  5268. \begin{figure}[tp]
  5269. \fbox{
  5270. \begin{minipage}{0.98\textwidth}
  5271. \small
  5272. \[
  5273. \begin{array}{lcl}
  5274. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  5275. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  5276. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  5277. \mid \BYTEREG{\itm{bytereg}} \\
  5278. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  5279. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  5280. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  5281. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  5282. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  5283. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  5284. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  5285. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  5286. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  5287. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  5288. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  5289. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  5290. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  5291. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  5292. \end{array}
  5293. \]
  5294. \end{minipage}
  5295. }
  5296. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  5297. \label{fig:x86-1}
  5298. \end{figure}
  5299. Next we consider the x86 instructions that are relevant for compiling
  5300. the comparison operations. The \key{cmpq} instruction compares its two
  5301. arguments to determine whether one argument is less than, equal, or
  5302. greater than the other argument. The \key{cmpq} instruction is unusual
  5303. regarding the order of its arguments and where the result is
  5304. placed. The argument order is backwards: if you want to test whether
  5305. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  5306. \key{cmpq} is placed in the special EFLAGS register. This register
  5307. cannot be accessed directly but it can be queried by a number of
  5308. instructions, including the \key{set} instruction. The instruction
  5309. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  5310. depending on whether the comparison comes out according to the
  5311. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  5312. for less-or-equal, \key{g} for greater, \key{ge} for
  5313. greater-or-equal). The \key{set} instruction has an annoying quirk in
  5314. that its destination argument must be single byte register, such as
  5315. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  5316. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  5317. instruction can be used to move from a single byte register to a
  5318. normal 64-bit register. The abstract syntax for the \code{set}
  5319. instruction differs from the concrete syntax in that it separates the
  5320. instruction name from the condition code.
  5321. The x86 instruction for conditional jump is relevant to the
  5322. compilation of \key{if} expressions. The instruction
  5323. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  5324. the instruction after \itm{label} depending on whether the result in
  5325. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  5326. jump instruction falls through to the next instruction. Like the
  5327. abstract syntax for \code{set}, the abstract syntax for conditional
  5328. jump separates the instruction name from the condition code. For
  5329. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  5330. the conditional jump instruction relies on the EFLAGS register, it is
  5331. common for it to be immediately preceded by a \key{cmpq} instruction
  5332. to set the EFLAGS register.
  5333. \section{Shrink the \LangIf{} Language}
  5334. \label{sec:shrink-Rif}
  5335. The \LangIf{} language includes several operators that are easily
  5336. expressible with other operators. For example, subtraction is
  5337. expressible using addition and negation.
  5338. \[
  5339. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  5340. \]
  5341. Several of the comparison operations are expressible using less-than
  5342. and logical negation.
  5343. \[
  5344. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  5345. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  5346. \]
  5347. The \key{let} is needed in the above translation to ensure that
  5348. expression $e_1$ is evaluated before $e_2$.
  5349. By performing these translations in the front-end of the compiler, the
  5350. later passes of the compiler do not need to deal with these operators,
  5351. making the passes shorter.
  5352. %% On the other hand, sometimes
  5353. %% these translations make it more difficult to generate the most
  5354. %% efficient code with respect to the number of instructions. However,
  5355. %% these differences typically do not affect the number of accesses to
  5356. %% memory, which is the primary factor that determines execution time on
  5357. %% modern computer architectures.
  5358. \begin{exercise}\normalfont
  5359. Implement the pass \code{shrink} to remove subtraction, \key{and},
  5360. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  5361. translating them to other constructs in \LangIf{}.
  5362. %
  5363. Create six test programs that involve these operators.
  5364. %
  5365. In the \code{run-tests.rkt} script, add the following entry for
  5366. \code{shrink} to the list of passes (it should be the only pass at
  5367. this point).
  5368. \begin{lstlisting}
  5369. (list "shrink" shrink interp-Rif type-check-Rif)
  5370. \end{lstlisting}
  5371. This instructs \code{interp-tests} to run the intepreter
  5372. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  5373. output of \code{shrink}.
  5374. %
  5375. Run the script to test your compiler on all the test programs.
  5376. \end{exercise}
  5377. \section{Uniquify Variables}
  5378. \label{sec:uniquify-Rif}
  5379. Add cases to \code{uniquify-exp} to handle Boolean constants and
  5380. \code{if} expressions.
  5381. \begin{exercise}\normalfont
  5382. Update the \code{uniquify-exp} for \LangIf{} and add the following
  5383. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  5384. \begin{lstlisting}
  5385. (list "uniquify" uniquify interp-Rif type-check-Rif)
  5386. \end{lstlisting}
  5387. Run the script to test your compiler.
  5388. \end{exercise}
  5389. \section{Remove Complex Operands}
  5390. \label{sec:remove-complex-opera-Rif}
  5391. The output language for this pass is \LangIfANF{}
  5392. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  5393. \LangIf{}. The \code{Bool} form is an atomic expressions but
  5394. \code{If} is not. All three sub-expressions of an \code{If} are
  5395. allowed to be complex expressions but the operands of \code{not} and
  5396. the comparisons must be atoms.
  5397. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  5398. \code{rco-atom} functions according to whether the output needs to be
  5399. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  5400. Regarding \code{If}, it is particularly important to \textbf{not}
  5401. replace its condition with a temporary variable because that would
  5402. interfere with the generation of high-quality output in the
  5403. \code{explicate-control} pass.
  5404. \begin{figure}[tp]
  5405. \centering
  5406. \fbox{
  5407. \begin{minipage}{0.96\textwidth}
  5408. \[
  5409. \begin{array}{rcl}
  5410. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  5411. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5412. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5413. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5414. &\mid& \UNIOP{\key{not}}{\Atm} \\
  5415. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  5416. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  5417. \end{array}
  5418. \]
  5419. \end{minipage}
  5420. }
  5421. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  5422. \label{fig:Rif-anf-syntax}
  5423. \end{figure}
  5424. \begin{exercise}\normalfont
  5425. %
  5426. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  5427. and \code{rco-exp} functions in \code{compiler.rkt}.
  5428. %
  5429. Create three new \LangInt{} programs that exercise the interesting
  5430. code in this pass.
  5431. %
  5432. In the \code{run-tests.rkt} script, add the following entry to the
  5433. list of \code{passes} and then run the script to test your compiler.
  5434. \begin{lstlisting}
  5435. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  5436. \end{lstlisting}
  5437. \end{exercise}
  5438. \section{Explicate Control}
  5439. \label{sec:explicate-control-Rif}
  5440. Recall that the purpose of \code{explicate-control} is to make the
  5441. order of evaluation explicit in the syntax of the program. With the
  5442. addition of \key{if} this get more interesting.
  5443. As a motivating example, consider the following program that has an
  5444. \key{if} expression nested in the predicate of another \key{if}.
  5445. % cond_test_41.rkt
  5446. \begin{center}
  5447. \begin{minipage}{0.96\textwidth}
  5448. \begin{lstlisting}
  5449. (let ([x (read)])
  5450. (let ([y (read)])
  5451. (if (if (< x 1) (eq? x 0) (eq? x 2))
  5452. (+ y 2)
  5453. (+ y 10))))
  5454. \end{lstlisting}
  5455. \end{minipage}
  5456. \end{center}
  5457. %
  5458. The naive way to compile \key{if} and the comparison would be to
  5459. handle each of them in isolation, regardless of their context. Each
  5460. comparison would be translated into a \key{cmpq} instruction followed
  5461. by a couple instructions to move the result from the EFLAGS register
  5462. into a general purpose register or stack location. Each \key{if} would
  5463. be translated into a \key{cmpq} instruction followed by a conditional
  5464. jump. The generated code for the inner \key{if} in the above example
  5465. would be as follows.
  5466. \begin{center}
  5467. \begin{minipage}{0.96\textwidth}
  5468. \begin{lstlisting}
  5469. ...
  5470. cmpq $1, x ;; (< x 1)
  5471. setl %al
  5472. movzbq %al, tmp
  5473. cmpq $1, tmp ;; (if ...)
  5474. je then_branch_1
  5475. jmp else_branch_1
  5476. ...
  5477. \end{lstlisting}
  5478. \end{minipage}
  5479. \end{center}
  5480. However, if we take context into account we can do better and reduce
  5481. the use of \key{cmpq} instructions for accessing the EFLAG register.
  5482. Our goal will be compile \key{if} expressions so that the relevant
  5483. comparison instruction appears directly before the conditional jump.
  5484. For example, we want to generate the following code for the inner
  5485. \code{if}.
  5486. \begin{center}
  5487. \begin{minipage}{0.96\textwidth}
  5488. \begin{lstlisting}
  5489. ...
  5490. cmpq $1, x
  5491. je then_branch_1
  5492. jmp else_branch_1
  5493. ...
  5494. \end{lstlisting}
  5495. \end{minipage}
  5496. \end{center}
  5497. One way to achieve this is to reorganize the code at the level of
  5498. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  5499. the following code.
  5500. \begin{center}
  5501. \begin{minipage}{0.96\textwidth}
  5502. \begin{lstlisting}
  5503. (let ([x (read)])
  5504. (let ([y (read)])
  5505. (if (< x 1)
  5506. (if (eq? x 0)
  5507. (+ y 2)
  5508. (+ y 10))
  5509. (if (eq? x 2)
  5510. (+ y 2)
  5511. (+ y 10)))))
  5512. \end{lstlisting}
  5513. \end{minipage}
  5514. \end{center}
  5515. Unfortunately, this approach duplicates the two branches from the
  5516. outer \code{if} and a compiler must never duplicate code!
  5517. We need a way to perform the above transformation but without
  5518. duplicating code. That is, we need a way for different parts of a
  5519. program to refer to the same piece of code. At the level of x86
  5520. assembly this is straightforward because we can label the code for
  5521. each branch and insert jumps in all the places that need to execute
  5522. the branch. In our intermediate language, we need to move away from
  5523. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  5524. particular, we use a standard program representation called a
  5525. \emph{control flow graph} (CFG), due to Frances Elizabeth
  5526. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  5527. labeled sequence of code, called a \emph{basic block}, and each edge
  5528. represents a jump to another block. The \key{CProgram} construct of
  5529. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  5530. as an alist mapping labels to basic blocks. Each basic block is
  5531. represented by the $\Tail$ non-terminal.
  5532. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  5533. \code{remove-complex-opera*} pass and then the
  5534. \code{explicate-control} pass on the example program. We walk through
  5535. the output program and then discuss the algorithm.
  5536. %
  5537. Following the order of evaluation in the output of
  5538. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  5539. and then the comparison \lstinline{(< x 1)} in the predicate of the
  5540. inner \key{if}. In the output of \code{explicate-control}, in the
  5541. block labeled \code{start}, is two assignment statements followed by a
  5542. \code{if} statement that branches to \code{block40} or
  5543. \code{block41}. The blocks associated with those labels contain the
  5544. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  5545. respectively. In particular, we start \code{block40} with the
  5546. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  5547. \code{block39}, the two branches of the outer \key{if}, i.e.,
  5548. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  5549. \code{block41} is similar.
  5550. \begin{figure}[tbp]
  5551. \begin{tabular}{lll}
  5552. \begin{minipage}{0.4\textwidth}
  5553. % cond_test_41.rkt
  5554. \begin{lstlisting}
  5555. (let ([x (read)])
  5556. (let ([y (read)])
  5557. (if (if (< x 1)
  5558. (eq? x 0)
  5559. (eq? x 2))
  5560. (+ y 2)
  5561. (+ y 10))))
  5562. \end{lstlisting}
  5563. \hspace{40pt}$\Downarrow$
  5564. \begin{lstlisting}
  5565. (let ([x (read)])
  5566. (let ([y (read)])
  5567. (if (if (< x 1)
  5568. (eq? x 0)
  5569. (eq? x 2))
  5570. (+ y 2)
  5571. (+ y 10))))
  5572. \end{lstlisting}
  5573. \end{minipage}
  5574. &
  5575. $\Rightarrow$
  5576. &
  5577. \begin{minipage}{0.55\textwidth}
  5578. \begin{lstlisting}
  5579. start:
  5580. x = (read);
  5581. y = (read);
  5582. if (< x 1) goto block40;
  5583. else goto block41;
  5584. block40:
  5585. if (eq? x 0) goto block38;
  5586. else goto block39;
  5587. block41:
  5588. if (eq? x 2) goto block38;
  5589. else goto block39;
  5590. block38:
  5591. return (+ y 2);
  5592. block39:
  5593. return (+ y 10);
  5594. \end{lstlisting}
  5595. \end{minipage}
  5596. \end{tabular}
  5597. \caption{Translation from \LangIf{} to \LangCIf{}
  5598. via the \code{explicate-control}.}
  5599. \label{fig:explicate-control-s1-38}
  5600. \end{figure}
  5601. %% The nice thing about the output of \code{explicate-control} is that
  5602. %% there are no unnecessary comparisons and every comparison is part of a
  5603. %% conditional jump.
  5604. %% The down-side of this output is that it includes
  5605. %% trivial blocks, such as the blocks labeled \code{block92} through
  5606. %% \code{block95}, that only jump to another block. We discuss a solution
  5607. %% to this problem in Section~\ref{sec:opt-jumps}.
  5608. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  5609. \code{explicate-control} for \LangVar{} using two mutually recursive
  5610. functions, \code{explicate-tail} and \code{explicate-assign}. The
  5611. former function translates expressions in tail position whereas the
  5612. later function translates expressions on the right-hand-side of a
  5613. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  5614. have a new kind of position to deal with: the predicate position of
  5615. the \key{if}. We need another function, \code{explicate-pred}, that
  5616. takes an \LangIf{} expression and two blocks for the then-branch and
  5617. else-branch. The output of \code{explicate-pred} is a block.
  5618. %
  5619. In the following paragraphs we discuss specific cases in the
  5620. \code{explicate-pred} function as well as additions to the
  5621. \code{explicate-tail} and \code{explicate-assign} functions.
  5622. \begin{figure}[tbp]
  5623. \begin{lstlisting}
  5624. (define (explicate-pred cnd thn els)
  5625. (match cnd
  5626. [(Var x) ___]
  5627. [(Let x rhs body) ___]
  5628. [(Prim 'not (list e)) ___]
  5629. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  5630. (IfStmt (Prim op arg*) (force (block->goto thn))
  5631. (force (block->goto els)))]
  5632. [(Bool b) (if b thn els)]
  5633. [(If cnd^ thn^ els^) ___]
  5634. [else (error "explicate-pred unhandled case" cnd)]))
  5635. \end{lstlisting}
  5636. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  5637. \label{fig:explicate-pred}
  5638. \end{figure}
  5639. The skeleton for the \code{explicate-pred} function is given in
  5640. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  5641. that can have type \code{Boolean}. We detail a few cases here and
  5642. leave the rest for the reader. The input to this function is an
  5643. expression and two blocks, \code{thn} and \code{els}, for the two
  5644. branches of the enclosing \key{if}.
  5645. %
  5646. Consider the case for Boolean constants in
  5647. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  5648. evaluation\index{partial evaluation} and output either the \code{thn}
  5649. or \code{els} branch depending on whether the constant is true or
  5650. false. This case demonstrates that we sometimes discard the \code{thn}
  5651. or \code{els} blocks that are input to \code{explicate-pred}.
  5652. The case for \key{if} in \code{explicate-pred} is particularly
  5653. illuminating because it deals with the challenges we discussed above
  5654. regarding nested \key{if} expressions
  5655. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  5656. \lstinline{els^} branches of the \key{if} inherit their context from
  5657. the current one, that is, predicate context. So you should recursively
  5658. apply \code{explicate-pred} to the \lstinline{thn^} and
  5659. \lstinline{els^} branches. For both of those recursive calls, pass
  5660. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  5661. and \code{els} may get used twice, once inside each recursive call. As
  5662. discussed above, to avoid duplicating code, we need to add them to the
  5663. control-flow graph so that we can instead refer to them by name and
  5664. execute them with a \key{goto}. However, as we saw in the cases above
  5665. for Boolean constants, the blocks \code{thn} and \code{els} may not
  5666. get used at all and we don't want to prematurely add them to the
  5667. control-flow graph if they end up being discarded.
  5668. The solution to this conundrum is to use \emph{lazy
  5669. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  5670. adding the blocks to the control-flow graph until the points where we
  5671. know they will be used. Racket provides support for lazy evaluation
  5672. with the
  5673. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  5674. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  5675. \index{delay} creates a \emph{promise}\index{promise} in which the
  5676. evaluation of the expressions is postponed. When \key{(force}
  5677. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  5678. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  5679. $e_n$ is cached in the promise and returned. If \code{force} is
  5680. applied again to the same promise, then the cached result is returned.
  5681. If \code{force} is applied to an argument that is not a promise,
  5682. \code{force} simply returns the argument.
  5683. We use lazy evaluation for the input and output blocks of the
  5684. functions \code{explicate-pred} and \code{explicate-assign} and for
  5685. the output block of \code{explicate-tail}. So instead of taking and
  5686. returning blocks, they take and return promises. Furthermore, when we
  5687. come to a situation in which we a block might be used more than once,
  5688. as in the case for \code{if} in \code{explicate-pred}, we transform
  5689. the promise into a new promise that will add the block to the
  5690. control-flow graph and return a \code{goto}. The following auxiliary
  5691. function named \code{block->goto} accomplishes this task. It begins
  5692. with \code{delay} to create a promise. When forced, this promise will
  5693. force the original promise. If that returns a \code{goto} (because the
  5694. block was already added to the control-flow graph), then we return the
  5695. \code{goto}. Otherwise we add the block to the control-flow graph with
  5696. another auxiliary function named \code{add-node}. That function
  5697. returns the label for the new block, which we use to create a
  5698. \code{goto}.
  5699. \begin{lstlisting}
  5700. (define (block->goto block)
  5701. (delay
  5702. (define b (force block))
  5703. (match b
  5704. [(Goto label) (Goto label)]
  5705. [else (Goto (add-node b))])))
  5706. \end{lstlisting}
  5707. Returning to the discussion of \code{explicate-pred}
  5708. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  5709. operators. This is one of the base cases of the recursive function so
  5710. we translate the comparison to an \code{if} statement. We apply
  5711. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  5712. that will add then to the control-flow graph, which we can immediately
  5713. \code{force} to obtain the two goto's that form the branches of the
  5714. \code{if} statement.
  5715. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  5716. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  5717. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  5718. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  5719. %% results from the two recursive calls. We complete the case for
  5720. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  5721. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  5722. %% the result $B_5$.
  5723. %% \[
  5724. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  5725. %% \quad\Rightarrow\quad
  5726. %% B_5
  5727. %% \]
  5728. The \code{explicate-tail} and \code{explicate-assign} functions need
  5729. additional cases for Boolean constants and \key{if}.
  5730. %
  5731. In the cases for \code{if}, the two branches inherit the current
  5732. context, so in \code{explicate-tail} they are in tail position and in
  5733. \code{explicate-assign} they are in assignment position. The
  5734. \code{cont} parameter of \code{explicate-assign} is used in both
  5735. recursive calls, so make sure to use \code{block->goto} on it.
  5736. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  5737. %% inherit the current context, so they are in tail position. Thus, the
  5738. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  5739. %% \code{explicate-tail}.
  5740. %% %
  5741. %% We need to pass $B_0$ as the accumulator argument for both of these
  5742. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  5743. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  5744. %% to the control-flow graph and obtain a promised goto $G_0$.
  5745. %% %
  5746. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5747. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5748. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5749. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5750. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5751. %% \[
  5752. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5753. %% \]
  5754. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5755. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5756. %% should not be confused with the labels for the blocks that appear in
  5757. %% the generated code. We initially construct unlabeled blocks; we only
  5758. %% attach labels to blocks when we add them to the control-flow graph, as
  5759. %% we see in the next case.
  5760. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5761. %% function. The context of the \key{if} is an assignment to some
  5762. %% variable $x$ and then the control continues to some promised block
  5763. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5764. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5765. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5766. %% branches of the \key{if} inherit the current context, so they are in
  5767. %% assignment positions. Let $B_2$ be the result of applying
  5768. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5769. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5770. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5771. %% the result of applying \code{explicate-pred} to the predicate
  5772. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5773. %% translates to the promise $B_4$.
  5774. %% \[
  5775. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5776. %% \]
  5777. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5778. The way in which the \code{shrink} pass transforms logical operations
  5779. such as \code{and} and \code{or} can impact the quality of code
  5780. generated by \code{explicate-control}. For example, consider the
  5781. following program.
  5782. % cond_test_21.rkt
  5783. \begin{lstlisting}
  5784. (if (and (eq? (read) 0) (eq? (read) 1))
  5785. 0
  5786. 42)
  5787. \end{lstlisting}
  5788. The \code{and} operation should transform into something that the
  5789. \code{explicate-pred} function can still analyze and descend through to
  5790. reach the underlying \code{eq?} conditions. Ideally, your
  5791. \code{explicate-control} pass should generate code similar to the
  5792. following for the above program.
  5793. \begin{center}
  5794. \begin{lstlisting}
  5795. start:
  5796. tmp1 = (read);
  5797. if (eq? tmp1 0) goto block40;
  5798. else goto block39;
  5799. block40:
  5800. tmp2 = (read);
  5801. if (eq? tmp2 1) goto block38;
  5802. else goto block39;
  5803. block38:
  5804. return 0;
  5805. block39:
  5806. return 42;
  5807. \end{lstlisting}
  5808. \end{center}
  5809. \begin{exercise}\normalfont
  5810. Implement the pass \code{explicate-control} by adding the cases for
  5811. Boolean constants and \key{if} to the \code{explicate-tail} and
  5812. \code{explicate-assign}. Implement the auxiliary function
  5813. \code{explicate-pred} for predicate contexts.
  5814. %
  5815. Create test cases that exercise all of the new cases in the code for
  5816. this pass.
  5817. %
  5818. Add the following entry to the list of \code{passes} in
  5819. \code{run-tests.rkt} and then run this script to test your compiler.
  5820. \begin{lstlisting}
  5821. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5822. \end{lstlisting}
  5823. \end{exercise}
  5824. \section{Select Instructions}
  5825. \label{sec:select-Rif}
  5826. \index{instruction selection}
  5827. The \code{select-instructions} pass translate \LangCIf{} to
  5828. \LangXIfVar{}. Recall that we implement this pass using three
  5829. auxiliary functions, one for each of the non-terminals $\Atm$,
  5830. $\Stmt$, and $\Tail$.
  5831. For $\Atm$, we have new cases for the Booleans. We take the usual
  5832. approach of encoding them as integers, with true as 1 and false as 0.
  5833. \[
  5834. \key{\#t} \Rightarrow \key{1}
  5835. \qquad
  5836. \key{\#f} \Rightarrow \key{0}
  5837. \]
  5838. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5839. be implemented in terms of \code{xorq} as we discussed at the
  5840. beginning of this section. Given an assignment
  5841. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5842. if the left-hand side $\itm{var}$ is
  5843. the same as $\Atm$, then just the \code{xorq} suffices.
  5844. \[
  5845. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5846. \quad\Rightarrow\quad
  5847. \key{xorq}~\key{\$}1\key{,}~\Var
  5848. \]
  5849. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5850. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5851. x86. Then we have
  5852. \[
  5853. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5854. \quad\Rightarrow\quad
  5855. \begin{array}{l}
  5856. \key{movq}~\Arg\key{,}~\Var\\
  5857. \key{xorq}~\key{\$}1\key{,}~\Var
  5858. \end{array}
  5859. \]
  5860. Next consider the cases for \code{eq?} and less-than comparison.
  5861. Translating these operations to x86 is slightly involved due to the
  5862. unusual nature of the \key{cmpq} instruction discussed above. We
  5863. recommend translating an assignment from \code{eq?} into the following
  5864. sequence of three instructions. \\
  5865. \begin{tabular}{lll}
  5866. \begin{minipage}{0.4\textwidth}
  5867. \begin{lstlisting}
  5868. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5869. \end{lstlisting}
  5870. \end{minipage}
  5871. &
  5872. $\Rightarrow$
  5873. &
  5874. \begin{minipage}{0.4\textwidth}
  5875. \begin{lstlisting}
  5876. cmpq |$\Arg_2$|, |$\Arg_1$|
  5877. sete %al
  5878. movzbq %al, |$\Var$|
  5879. \end{lstlisting}
  5880. \end{minipage}
  5881. \end{tabular} \\
  5882. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5883. and \key{if} statements. Both are straightforward to translate to
  5884. x86. A \key{goto} becomes a jump instruction.
  5885. \[
  5886. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5887. \]
  5888. An \key{if} statement becomes a compare instruction followed by a
  5889. conditional jump (for the ``then'' branch) and the fall-through is to
  5890. a regular jump (for the ``else'' branch).\\
  5891. \begin{tabular}{lll}
  5892. \begin{minipage}{0.4\textwidth}
  5893. \begin{lstlisting}
  5894. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5895. else goto |$\ell_2$|;
  5896. \end{lstlisting}
  5897. \end{minipage}
  5898. &
  5899. $\Rightarrow$
  5900. &
  5901. \begin{minipage}{0.4\textwidth}
  5902. \begin{lstlisting}
  5903. cmpq |$\Arg_2$|, |$\Arg_1$|
  5904. je |$\ell_1$|
  5905. jmp |$\ell_2$|
  5906. \end{lstlisting}
  5907. \end{minipage}
  5908. \end{tabular} \\
  5909. \begin{exercise}\normalfont
  5910. Expand your \code{select-instructions} pass to handle the new features
  5911. of the \LangIf{} language.
  5912. %
  5913. Add the following entry to the list of \code{passes} in
  5914. \code{run-tests.rkt}
  5915. \begin{lstlisting}
  5916. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5917. \end{lstlisting}
  5918. %
  5919. Run the script to test your compiler on all the test programs.
  5920. \end{exercise}
  5921. \section{Register Allocation}
  5922. \label{sec:register-allocation-Rif}
  5923. \index{register allocation}
  5924. The changes required for \LangIf{} affect liveness analysis, building the
  5925. interference graph, and assigning homes, but the graph coloring
  5926. algorithm itself does not change.
  5927. \subsection{Liveness Analysis}
  5928. \label{sec:liveness-analysis-Rif}
  5929. \index{liveness analysis}
  5930. Recall that for \LangVar{} we implemented liveness analysis for a single
  5931. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5932. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5933. produces many basic blocks arranged in a control-flow graph. We
  5934. recommend that you create a new auxiliary function named
  5935. \code{uncover-live-CFG} that applies liveness analysis to a
  5936. control-flow graph.
  5937. The first question we is: what order should we process the basic
  5938. blocks in the control-flow graph? Recall that to perform liveness
  5939. analysis on a basic block we need to know its live-after set. If a
  5940. basic block has no successors (i.e. no out-edges in the control flow
  5941. graph), then it has an empty live-after set and we can immediately
  5942. apply liveness analysis to it. If a basic block has some successors,
  5943. then we need to complete liveness analysis on those blocks first. In
  5944. graph theory, a sequence of nodes is in \emph{topological
  5945. order}\index{topological order} if each vertex comes before its
  5946. successors. We need the opposite, so we can transpose the graph
  5947. before computing a topological order.
  5948. %
  5949. Use the \code{tsort} and \code{transpose} functions of the Racket
  5950. \code{graph} package to accomplish this.
  5951. %
  5952. As an aside, a topological ordering is only guaranteed to exist if the
  5953. graph does not contain any cycles. That is indeed the case for the
  5954. control-flow graphs that we generate from \LangIf{} programs.
  5955. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5956. learn how to handle cycles in the control-flow graph.
  5957. You'll need to construct a directed graph to represent the
  5958. control-flow graph. Do not use the \code{directed-graph} of the
  5959. \code{graph} package because that only allows at most one edge between
  5960. each pair of vertices, but a control-flow graph may have multiple
  5961. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5962. the support code implements a graph representation that allows
  5963. multiple edges between a pair of vertices.
  5964. The next question is how to analyze jump instructions. Recall that in
  5965. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5966. \code{label->live} that maps each label to the set of live locations
  5967. at the beginning of its block. We use \code{label->live} to determine
  5968. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5969. that we have many basic blocks, \code{label->live} needs to be updated
  5970. as we process the blocks. In particular, after performing liveness
  5971. analysis on a block, we take the live-before set of its first
  5972. instruction and associate that with the block's label in the
  5973. \code{label->live}.
  5974. In \LangXIfVar{} we also have the conditional jump
  5975. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5976. this instruction is particularly interesting because during
  5977. compilation we do not know which way a conditional jump will go. So
  5978. we do not know whether to use the live-before set for the following
  5979. instruction or the live-before set for the $\itm{label}$. However,
  5980. there is no harm to the correctness of the compiler if we classify
  5981. more locations as live than the ones that are truly live during a
  5982. particular execution of the instruction. Thus, we can take the union
  5983. of the live-before sets from the following instruction and from the
  5984. mapping for $\itm{label}$ in \code{label->live}.
  5985. The auxiliary functions for computing the variables in an
  5986. instruction's argument and for computing the variables read-from ($R$)
  5987. or written-to ($W$) by an instruction need to be updated to handle the
  5988. new kinds of arguments and instructions in \LangXIfVar{}.
  5989. \begin{exercise}\normalfont
  5990. Update the \code{uncover-live} pass and implement the
  5991. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5992. to the control-flow graph. Add the following entry to the list of
  5993. \code{passes} in the \code{run-tests.rkt} script.
  5994. \begin{lstlisting}
  5995. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5996. \end{lstlisting}
  5997. \end{exercise}
  5998. \subsection{Build the Interference Graph}
  5999. \label{sec:build-interference-Rif}
  6000. Many of the new instructions in \LangXIfVar{} can be handled in the
  6001. same way as the instructions in \LangXVar{}. Thus, if your code was
  6002. already quite general, it will not need to be changed to handle the
  6003. new instructions. If you code is not general enough, we recommend that
  6004. you change your code to be more general. For example, you can factor
  6005. out the computing of the the read and write sets for each kind of
  6006. instruction into two auxiliary functions.
  6007. Note that the \key{movzbq} instruction requires some special care,
  6008. similar to the \key{movq} instruction. See rule number 1 in
  6009. Section~\ref{sec:build-interference}.
  6010. \begin{exercise}\normalfont
  6011. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  6012. following entries to the list of \code{passes} in the
  6013. \code{run-tests.rkt} script.
  6014. \begin{lstlisting}
  6015. (list "build-interference" build-interference interp-pseudo-x86-1)
  6016. (list "allocate-registers" allocate-registers interp-x86-1)
  6017. \end{lstlisting}
  6018. Run the script to test your compiler on all the \LangIf{} test
  6019. programs.
  6020. \end{exercise}
  6021. \section{Patch Instructions}
  6022. The second argument of the \key{cmpq} instruction must not be an
  6023. immediate value (such as an integer). So if you are comparing two
  6024. immediates, we recommend inserting a \key{movq} instruction to put the
  6025. second argument in \key{rax}. Also, recall that instructions may have
  6026. at most one memory reference.
  6027. %
  6028. The second argument of the \key{movzbq} must be a register.
  6029. %
  6030. There are no special restrictions on the jump instructions.
  6031. \begin{exercise}\normalfont
  6032. %
  6033. Update \code{patch-instructions} pass for \LangXIfVar{}.
  6034. %
  6035. Add the following entry to the list of \code{passes} in
  6036. \code{run-tests.rkt} and then run this script to test your compiler.
  6037. \begin{lstlisting}
  6038. (list "patch-instructions" patch-instructions interp-x86-1)
  6039. \end{lstlisting}
  6040. \end{exercise}
  6041. the \begin{figure}[tbp]
  6042. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6043. \node (Rif) at (0,2) {\large \LangIf{}};
  6044. \node (Rif-2) at (3,2) {\large \LangIf{}};
  6045. \node (Rif-3) at (6,2) {\large \LangIf{}};
  6046. \node (Rif-4) at (9,2) {\large \LangIf{}};
  6047. \node (Rif-5) at (12,2) {\large \LangIf{}};
  6048. \node (C1-1) at (3,0) {\large \LangCIf{}};
  6049. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  6050. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  6051. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  6052. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  6053. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  6054. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  6055. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  6056. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  6057. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  6058. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  6059. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  6060. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  6061. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6062. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6063. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6064. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6065. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  6066. \end{tikzpicture}
  6067. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  6068. \label{fig:Rif-passes}
  6069. \end{figure}
  6070. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  6071. compilation of \LangIf{}.
  6072. \section{An Example Translation}
  6073. Figure~\ref{fig:if-example-x86} shows a simple example program in
  6074. \LangIf{} translated to x86, showing the results of
  6075. \code{explicate-control}, \code{select-instructions}, and the final
  6076. x86 assembly code.
  6077. \begin{figure}[tbp]
  6078. \begin{tabular}{lll}
  6079. \begin{minipage}{0.4\textwidth}
  6080. % cond_test_20.rkt
  6081. \begin{lstlisting}
  6082. (if (eq? (read) 1) 42 0)
  6083. \end{lstlisting}
  6084. $\Downarrow$
  6085. \begin{lstlisting}
  6086. start:
  6087. tmp7951 = (read);
  6088. if (eq? tmp7951 1)
  6089. goto block7952;
  6090. else
  6091. goto block7953;
  6092. block7952:
  6093. return 42;
  6094. block7953:
  6095. return 0;
  6096. \end{lstlisting}
  6097. $\Downarrow$
  6098. \begin{lstlisting}
  6099. start:
  6100. callq read_int
  6101. movq %rax, tmp7951
  6102. cmpq $1, tmp7951
  6103. je block7952
  6104. jmp block7953
  6105. block7953:
  6106. movq $0, %rax
  6107. jmp conclusion
  6108. block7952:
  6109. movq $42, %rax
  6110. jmp conclusion
  6111. \end{lstlisting}
  6112. \end{minipage}
  6113. &
  6114. $\Rightarrow\qquad$
  6115. \begin{minipage}{0.4\textwidth}
  6116. \begin{lstlisting}
  6117. start:
  6118. callq read_int
  6119. movq %rax, %rcx
  6120. cmpq $1, %rcx
  6121. je block7952
  6122. jmp block7953
  6123. block7953:
  6124. movq $0, %rax
  6125. jmp conclusion
  6126. block7952:
  6127. movq $42, %rax
  6128. jmp conclusion
  6129. .globl main
  6130. main:
  6131. pushq %rbp
  6132. movq %rsp, %rbp
  6133. pushq %r13
  6134. pushq %r12
  6135. pushq %rbx
  6136. pushq %r14
  6137. subq $0, %rsp
  6138. jmp start
  6139. conclusion:
  6140. addq $0, %rsp
  6141. popq %r14
  6142. popq %rbx
  6143. popq %r12
  6144. popq %r13
  6145. popq %rbp
  6146. retq
  6147. \end{lstlisting}
  6148. \end{minipage}
  6149. \end{tabular}
  6150. \caption{Example compilation of an \key{if} expression to x86.}
  6151. \label{fig:if-example-x86}
  6152. \end{figure}
  6153. \section{Challenge: Remove Jumps}
  6154. \label{sec:opt-jumps}
  6155. %% Recall that in the example output of \code{explicate-control} in
  6156. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  6157. %% \code{block60} are trivial blocks, they do nothing but jump to another
  6158. %% block. The first goal of this challenge assignment is to remove those
  6159. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  6160. %% \code{explicate-control} on the left and shows the result of bypassing
  6161. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  6162. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  6163. %% \code{block55}. The optimized code on the right of
  6164. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  6165. %% \code{then} branch jumping directly to \code{block55}. The story is
  6166. %% similar for the \code{else} branch, as well as for the two branches in
  6167. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  6168. %% have been optimized in this way, there are no longer any jumps to
  6169. %% blocks \code{block57} through \code{block60}, so they can be removed.
  6170. %% \begin{figure}[tbp]
  6171. %% \begin{tabular}{lll}
  6172. %% \begin{minipage}{0.4\textwidth}
  6173. %% \begin{lstlisting}
  6174. %% block62:
  6175. %% tmp54 = (read);
  6176. %% if (eq? tmp54 2) then
  6177. %% goto block59;
  6178. %% else
  6179. %% goto block60;
  6180. %% block61:
  6181. %% tmp53 = (read);
  6182. %% if (eq? tmp53 0) then
  6183. %% goto block57;
  6184. %% else
  6185. %% goto block58;
  6186. %% block60:
  6187. %% goto block56;
  6188. %% block59:
  6189. %% goto block55;
  6190. %% block58:
  6191. %% goto block56;
  6192. %% block57:
  6193. %% goto block55;
  6194. %% block56:
  6195. %% return (+ 700 77);
  6196. %% block55:
  6197. %% return (+ 10 32);
  6198. %% start:
  6199. %% tmp52 = (read);
  6200. %% if (eq? tmp52 1) then
  6201. %% goto block61;
  6202. %% else
  6203. %% goto block62;
  6204. %% \end{lstlisting}
  6205. %% \end{minipage}
  6206. %% &
  6207. %% $\Rightarrow$
  6208. %% &
  6209. %% \begin{minipage}{0.55\textwidth}
  6210. %% \begin{lstlisting}
  6211. %% block62:
  6212. %% tmp54 = (read);
  6213. %% if (eq? tmp54 2) then
  6214. %% goto block55;
  6215. %% else
  6216. %% goto block56;
  6217. %% block61:
  6218. %% tmp53 = (read);
  6219. %% if (eq? tmp53 0) then
  6220. %% goto block55;
  6221. %% else
  6222. %% goto block56;
  6223. %% block56:
  6224. %% return (+ 700 77);
  6225. %% block55:
  6226. %% return (+ 10 32);
  6227. %% start:
  6228. %% tmp52 = (read);
  6229. %% if (eq? tmp52 1) then
  6230. %% goto block61;
  6231. %% else
  6232. %% goto block62;
  6233. %% \end{lstlisting}
  6234. %% \end{minipage}
  6235. %% \end{tabular}
  6236. %% \caption{Optimize jumps by removing trivial blocks.}
  6237. %% \label{fig:optimize-jumps}
  6238. %% \end{figure}
  6239. %% The name of this pass is \code{optimize-jumps}. We recommend
  6240. %% implementing this pass in two phases. The first phrase builds a hash
  6241. %% table that maps labels to possibly improved labels. The second phase
  6242. %% changes the target of each \code{goto} to use the improved label. If
  6243. %% the label is for a trivial block, then the hash table should map the
  6244. %% label to the first non-trivial block that can be reached from this
  6245. %% label by jumping through trivial blocks. If the label is for a
  6246. %% non-trivial block, then the hash table should map the label to itself;
  6247. %% we do not want to change jumps to non-trivial blocks.
  6248. %% The first phase can be accomplished by constructing an empty hash
  6249. %% table, call it \code{short-cut}, and then iterating over the control
  6250. %% flow graph. Each time you encouter a block that is just a \code{goto},
  6251. %% then update the hash table, mapping the block's source to the target
  6252. %% of the \code{goto}. Also, the hash table may already have mapped some
  6253. %% labels to the block's source, to you must iterate through the hash
  6254. %% table and update all of those so that they instead map to the target
  6255. %% of the \code{goto}.
  6256. %% For the second phase, we recommend iterating through the $\Tail$ of
  6257. %% each block in the program, updating the target of every \code{goto}
  6258. %% according to the mapping in \code{short-cut}.
  6259. %% \begin{exercise}\normalfont
  6260. %% Implement the \code{optimize-jumps} pass as a transformation from
  6261. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  6262. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  6263. %% example programs. Then check that your compiler still passes all of
  6264. %% your tests.
  6265. %% \end{exercise}
  6266. There is an opportunity for optimizing jumps that is apparent in the
  6267. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  6268. ends with a jump to \code{block7953} and there are no other jumps to
  6269. \code{block7953} in the rest of the program. In this situation we can
  6270. avoid the runtime overhead of this jump by merging \code{block7953}
  6271. into the preceding block, in this case the \code{start} block.
  6272. Figure~\ref{fig:remove-jumps} shows the output of
  6273. \code{select-instructions} on the left and the result of this
  6274. optimization on the right.
  6275. \begin{figure}[tbp]
  6276. \begin{tabular}{lll}
  6277. \begin{minipage}{0.5\textwidth}
  6278. % cond_test_20.rkt
  6279. \begin{lstlisting}
  6280. start:
  6281. callq read_int
  6282. movq %rax, tmp7951
  6283. cmpq $1, tmp7951
  6284. je block7952
  6285. jmp block7953
  6286. block7953:
  6287. movq $0, %rax
  6288. jmp conclusion
  6289. block7952:
  6290. movq $42, %rax
  6291. jmp conclusion
  6292. \end{lstlisting}
  6293. \end{minipage}
  6294. &
  6295. $\Rightarrow\qquad$
  6296. \begin{minipage}{0.4\textwidth}
  6297. \begin{lstlisting}
  6298. start:
  6299. callq read_int
  6300. movq %rax, tmp7951
  6301. cmpq $1, tmp7951
  6302. je block7952
  6303. movq $0, %rax
  6304. jmp conclusion
  6305. block7952:
  6306. movq $42, %rax
  6307. jmp conclusion
  6308. \end{lstlisting}
  6309. \end{minipage}
  6310. \end{tabular}
  6311. \caption{Merging basic blocks by removing unnecessary jumps.}
  6312. \label{fig:remove-jumps}
  6313. \end{figure}
  6314. \begin{exercise}\normalfont
  6315. %
  6316. Implement a pass named \code{remove-jumps} that merges basic blocks
  6317. into their preceding basic block, when there is only one preceding
  6318. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  6319. %
  6320. In the \code{run-tests.rkt} script, add the following entry to the
  6321. list of \code{passes} between \code{allocate-registers}
  6322. and \code{patch-instructions}.
  6323. \begin{lstlisting}
  6324. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  6325. \end{lstlisting}
  6326. Run this script to test your compiler.
  6327. %
  6328. Check that \code{remove-jumps} accomplishes the goal of merging basic
  6329. blocks on several test programs.
  6330. \end{exercise}
  6331. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6332. \chapter{Tuples and Garbage Collection}
  6333. \label{ch:Rvec}
  6334. \index{tuple}
  6335. \index{vector}
  6336. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  6337. all the IR grammars are spelled out! \\ --Jeremy}
  6338. \margincomment{\scriptsize Be more explicit about how to deal with
  6339. the root stack. \\ --Jeremy}
  6340. In this chapter we study the implementation of mutable tuples, called
  6341. vectors in Racket. This language feature is the first to use the
  6342. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  6343. tuple is indefinite, that is, a tuple lives forever from the
  6344. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  6345. is important to reclaim the space associated with a tuple when it is
  6346. no longer needed, which is why we also study \emph{garbage collection}
  6347. \emph{garbage collection} techniques in this chapter.
  6348. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  6349. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  6350. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  6351. \code{void} value. The reason for including the later is that the
  6352. \code{vector-set!} operation returns a value of type
  6353. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  6354. called the \code{Unit} type in the programming languages
  6355. literature. Racket's \code{Void} type is inhabited by a single value
  6356. \code{void} which corresponds to \code{unit} or \code{()} in the
  6357. literature~\citep{Pierce:2002hj}.}.
  6358. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  6359. copying live objects back and forth between two halves of the
  6360. heap. The garbage collector requires coordination with the compiler so
  6361. that it can see all of the \emph{root} pointers, that is, pointers in
  6362. registers or on the procedure call stack.
  6363. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  6364. discuss all the necessary changes and additions to the compiler
  6365. passes, including a new compiler pass named \code{expose-allocation}.
  6366. \section{The \LangVec{} Language}
  6367. \label{sec:r3}
  6368. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  6369. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  6370. \LangVec{} language includes three new forms: \code{vector} for creating a
  6371. tuple, \code{vector-ref} for reading an element of a tuple, and
  6372. \code{vector-set!} for writing to an element of a tuple. The program
  6373. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  6374. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  6375. the 3-tuple, demonstrating that tuples are first-class values. The
  6376. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  6377. of the \key{if} is taken. The element at index $0$ of \code{t} is
  6378. \code{40}, to which we add \code{2}, the element at index $0$ of the
  6379. 1-tuple. So the result of the program is \code{42}.
  6380. \begin{figure}[tbp]
  6381. \centering
  6382. \fbox{
  6383. \begin{minipage}{0.96\textwidth}
  6384. \[
  6385. \begin{array}{lcl}
  6386. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  6387. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  6388. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6389. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6390. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6391. \mid \LP\key{and}\;\Exp\;\Exp\RP
  6392. \mid \LP\key{or}\;\Exp\;\Exp\RP
  6393. \mid \LP\key{not}\;\Exp\RP } \\
  6394. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  6395. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6396. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  6397. \mid \LP\key{vector-length}\;\Exp\RP \\
  6398. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  6399. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  6400. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  6401. \LangVec{} &::=& \Exp
  6402. \end{array}
  6403. \]
  6404. \end{minipage}
  6405. }
  6406. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  6407. (Figure~\ref{fig:Rif-concrete-syntax}).}
  6408. \label{fig:Rvec-concrete-syntax}
  6409. \end{figure}
  6410. \begin{figure}[tbp]
  6411. \begin{lstlisting}
  6412. (let ([t (vector 40 #t (vector 2))])
  6413. (if (vector-ref t 1)
  6414. (+ (vector-ref t 0)
  6415. (vector-ref (vector-ref t 2) 0))
  6416. 44))
  6417. \end{lstlisting}
  6418. \caption{Example program that creates tuples and reads from them.}
  6419. \label{fig:vector-eg}
  6420. \end{figure}
  6421. \begin{figure}[tp]
  6422. \centering
  6423. \fbox{
  6424. \begin{minipage}{0.96\textwidth}
  6425. \[
  6426. \begin{array}{lcl}
  6427. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  6428. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6429. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  6430. \mid \BOOL{\itm{bool}}
  6431. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6432. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  6433. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  6434. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  6435. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  6436. \end{array}
  6437. \]
  6438. \end{minipage}
  6439. }
  6440. \caption{The abstract syntax of \LangVec{}.}
  6441. \label{fig:Rvec-syntax}
  6442. \end{figure}
  6443. \index{allocate}
  6444. \index{heap allocate}
  6445. Tuples are our first encounter with heap-allocated data, which raises
  6446. several interesting issues. First, variable binding performs a
  6447. shallow-copy when dealing with tuples, which means that different
  6448. variables can refer to the same tuple, that is, different variables
  6449. can be \emph{aliases} for the same entity. Consider the following
  6450. example in which both \code{t1} and \code{t2} refer to the same tuple.
  6451. Thus, the mutation through \code{t2} is visible when referencing the
  6452. tuple from \code{t1}, so the result of this program is \code{42}.
  6453. \index{alias}\index{mutation}
  6454. \begin{center}
  6455. \begin{minipage}{0.96\textwidth}
  6456. \begin{lstlisting}
  6457. (let ([t1 (vector 3 7)])
  6458. (let ([t2 t1])
  6459. (let ([_ (vector-set! t2 0 42)])
  6460. (vector-ref t1 0))))
  6461. \end{lstlisting}
  6462. \end{minipage}
  6463. \end{center}
  6464. The next issue concerns the lifetime of tuples. Of course, they are
  6465. created by the \code{vector} form, but when does their lifetime end?
  6466. Notice that \LangVec{} does not include an operation for deleting
  6467. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  6468. of static scoping. For example, the following program returns
  6469. \code{42} even though the variable \code{w} goes out of scope prior to
  6470. the \code{vector-ref} that reads from the vector it was bound to.
  6471. \begin{center}
  6472. \begin{minipage}{0.96\textwidth}
  6473. \begin{lstlisting}
  6474. (let ([v (vector (vector 44))])
  6475. (let ([x (let ([w (vector 42)])
  6476. (let ([_ (vector-set! v 0 w)])
  6477. 0))])
  6478. (+ x (vector-ref (vector-ref v 0) 0))))
  6479. \end{lstlisting}
  6480. \end{minipage}
  6481. \end{center}
  6482. From the perspective of programmer-observable behavior, tuples live
  6483. forever. Of course, if they really lived forever, then many programs
  6484. would run out of memory.\footnote{The \LangVec{} language does not have
  6485. looping or recursive functions, so it is nigh impossible to write a
  6486. program in \LangVec{} that will run out of memory. However, we add
  6487. recursive functions in the next Chapter!} A Racket implementation
  6488. must therefore perform automatic garbage collection.
  6489. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  6490. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  6491. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  6492. terms of the corresponding operations in Racket. One subtle point is
  6493. that the \code{vector-set!} operation returns the \code{\#<void>}
  6494. value. The \code{\#<void>} value can be passed around just like other
  6495. values inside an \LangVec{} program and a \code{\#<void>} value can be
  6496. compared for equality with another \code{\#<void>} value. However,
  6497. there are no other operations specific to the the \code{\#<void>}
  6498. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  6499. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  6500. otherwise.
  6501. \begin{figure}[tbp]
  6502. \begin{lstlisting}
  6503. (define interp-Rvec-class
  6504. (class interp-Rif-class
  6505. (super-new)
  6506. (define/override (interp-op op)
  6507. (match op
  6508. ['eq? (lambda (v1 v2)
  6509. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6510. (and (boolean? v1) (boolean? v2))
  6511. (and (vector? v1) (vector? v2))
  6512. (and (void? v1) (void? v2)))
  6513. (eq? v1 v2)]))]
  6514. ['vector vector]
  6515. ['vector-length vector-length]
  6516. ['vector-ref vector-ref]
  6517. ['vector-set! vector-set!]
  6518. [else (super interp-op op)]
  6519. ))
  6520. (define/override ((interp-exp env) e)
  6521. (define recur (interp-exp env))
  6522. (match e
  6523. [(HasType e t) (recur e)]
  6524. [(Void) (void)]
  6525. [else ((super interp-exp env) e)]
  6526. ))
  6527. ))
  6528. (define (interp-Rvec p)
  6529. (send (new interp-Rvec-class) interp-program p))
  6530. \end{lstlisting}
  6531. \caption{Interpreter for the \LangVec{} language.}
  6532. \label{fig:interp-Rvec}
  6533. \end{figure}
  6534. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  6535. deserves some explanation. When allocating a vector, we need to know
  6536. which elements of the vector are pointers (i.e. are also vectors). We
  6537. can obtain this information during type checking. The type checker in
  6538. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  6539. expression, it also wraps every \key{vector} creation with the form
  6540. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  6541. %
  6542. To create the s-expression for the \code{Vector} type in
  6543. Figure~\ref{fig:type-check-Rvec}, we use the
  6544. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  6545. operator} \code{,@} to insert the list \code{t*} without its usual
  6546. start and end parentheses. \index{unquote-slicing}
  6547. \begin{figure}[tp]
  6548. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6549. (define type-check-Rvec-class
  6550. (class type-check-Rif-class
  6551. (super-new)
  6552. (inherit check-type-equal?)
  6553. (define/override (type-check-exp env)
  6554. (lambda (e)
  6555. (define recur (type-check-exp env))
  6556. (match e
  6557. [(Void) (values (Void) 'Void)]
  6558. [(Prim 'vector es)
  6559. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  6560. (define t `(Vector ,@t*))
  6561. (values (HasType (Prim 'vector e*) t) t)]
  6562. [(Prim 'vector-ref (list e1 (Int i)))
  6563. (define-values (e1^ t) (recur e1))
  6564. (match t
  6565. [`(Vector ,ts ...)
  6566. (unless (and (0 . <= . i) (i . < . (length ts)))
  6567. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6568. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  6569. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6570. [(Prim 'vector-set! (list e1 (Int i) arg) )
  6571. (define-values (e-vec t-vec) (recur e1))
  6572. (define-values (e-arg^ t-arg) (recur arg))
  6573. (match t-vec
  6574. [`(Vector ,ts ...)
  6575. (unless (and (0 . <= . i) (i . < . (length ts)))
  6576. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6577. (check-type-equal? (list-ref ts i) t-arg e)
  6578. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  6579. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  6580. [(Prim 'vector-length (list e))
  6581. (define-values (e^ t) (recur e))
  6582. (match t
  6583. [`(Vector ,ts ...)
  6584. (values (Prim 'vector-length (list e^)) 'Integer)]
  6585. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6586. [(Prim 'eq? (list arg1 arg2))
  6587. (define-values (e1 t1) (recur arg1))
  6588. (define-values (e2 t2) (recur arg2))
  6589. (match* (t1 t2)
  6590. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  6591. [(other wise) (check-type-equal? t1 t2 e)])
  6592. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  6593. [(HasType (Prim 'vector es) t)
  6594. ((type-check-exp env) (Prim 'vector es))]
  6595. [(HasType e1 t)
  6596. (define-values (e1^ t^) (recur e1))
  6597. (check-type-equal? t t^ e)
  6598. (values (HasType e1^ t) t)]
  6599. [else ((super type-check-exp env) e)]
  6600. )))
  6601. ))
  6602. (define (type-check-Rvec p)
  6603. (send (new type-check-Rvec-class) type-check-program p))
  6604. \end{lstlisting}
  6605. \caption{Type checker for the \LangVec{} language.}
  6606. \label{fig:type-check-Rvec}
  6607. \end{figure}
  6608. \section{Garbage Collection}
  6609. \label{sec:GC}
  6610. Here we study a relatively simple algorithm for garbage collection
  6611. that is the basis of state-of-the-art garbage
  6612. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  6613. particular, we describe a two-space copying
  6614. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  6615. perform the
  6616. copy~\citep{Cheney:1970aa}.
  6617. \index{copying collector}
  6618. \index{two-space copying collector}
  6619. Figure~\ref{fig:copying-collector} gives a
  6620. coarse-grained depiction of what happens in a two-space collector,
  6621. showing two time steps, prior to garbage collection (on the top) and
  6622. after garbage collection (on the bottom). In a two-space collector,
  6623. the heap is divided into two parts named the FromSpace and the
  6624. ToSpace. Initially, all allocations go to the FromSpace until there is
  6625. not enough room for the next allocation request. At that point, the
  6626. garbage collector goes to work to make more room.
  6627. \index{ToSpace}
  6628. \index{FromSpace}
  6629. The garbage collector must be careful not to reclaim tuples that will
  6630. be used by the program in the future. Of course, it is impossible in
  6631. general to predict what a program will do, but we can over approximate
  6632. the will-be-used tuples by preserving all tuples that could be
  6633. accessed by \emph{any} program given the current computer state. A
  6634. program could access any tuple whose address is in a register or on
  6635. the procedure call stack. These addresses are called the \emph{root
  6636. set}\index{root set}. In addition, a program could access any tuple that is
  6637. transitively reachable from the root set. Thus, it is safe for the
  6638. garbage collector to reclaim the tuples that are not reachable in this
  6639. way.
  6640. So the goal of the garbage collector is twofold:
  6641. \begin{enumerate}
  6642. \item preserve all tuple that are reachable from the root set via a
  6643. path of pointers, that is, the \emph{live} tuples, and
  6644. \item reclaim the memory of everything else, that is, the
  6645. \emph{garbage}.
  6646. \end{enumerate}
  6647. A copying collector accomplishes this by copying all of the live
  6648. objects from the FromSpace into the ToSpace and then performs a sleight
  6649. of hand, treating the ToSpace as the new FromSpace and the old
  6650. FromSpace as the new ToSpace. In the example of
  6651. Figure~\ref{fig:copying-collector}, there are three pointers in the
  6652. root set, one in a register and two on the stack. All of the live
  6653. objects have been copied to the ToSpace (the right-hand side of
  6654. Figure~\ref{fig:copying-collector}) in a way that preserves the
  6655. pointer relationships. For example, the pointer in the register still
  6656. points to a 2-tuple whose first element is a 3-tuple and whose second
  6657. element is a 2-tuple. There are four tuples that are not reachable
  6658. from the root set and therefore do not get copied into the ToSpace.
  6659. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  6660. created by a well-typed program in \LangVec{} because it contains a
  6661. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  6662. We design the garbage collector to deal with cycles to begin with so
  6663. we will not need to revisit this issue.
  6664. \begin{figure}[tbp]
  6665. \centering
  6666. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  6667. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  6668. \caption{A copying collector in action.}
  6669. \label{fig:copying-collector}
  6670. \end{figure}
  6671. There are many alternatives to copying collectors (and their bigger
  6672. siblings, the generational collectors) when its comes to garbage
  6673. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  6674. reference counting~\citep{Collins:1960aa}. The strengths of copying
  6675. collectors are that allocation is fast (just a comparison and pointer
  6676. increment), there is no fragmentation, cyclic garbage is collected,
  6677. and the time complexity of collection only depends on the amount of
  6678. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  6679. main disadvantages of a two-space copying collector is that it uses a
  6680. lot of space and takes a long time to perform the copy, though these
  6681. problems are ameliorated in generational collectors. Racket and
  6682. Scheme programs tend to allocate many small objects and generate a lot
  6683. of garbage, so copying and generational collectors are a good fit.
  6684. Garbage collection is an active research topic, especially concurrent
  6685. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  6686. developing new techniques and revisiting old
  6687. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  6688. meet every year at the International Symposium on Memory Management to
  6689. present these findings.
  6690. \subsection{Graph Copying via Cheney's Algorithm}
  6691. \label{sec:cheney}
  6692. \index{Cheney's algorithm}
  6693. Let us take a closer look at the copying of the live objects. The
  6694. allocated objects and pointers can be viewed as a graph and we need to
  6695. copy the part of the graph that is reachable from the root set. To
  6696. make sure we copy all of the reachable vertices in the graph, we need
  6697. an exhaustive graph traversal algorithm, such as depth-first search or
  6698. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  6699. such algorithms take into account the possibility of cycles by marking
  6700. which vertices have already been visited, so as to ensure termination
  6701. of the algorithm. These search algorithms also use a data structure
  6702. such as a stack or queue as a to-do list to keep track of the vertices
  6703. that need to be visited. We use breadth-first search and a trick
  6704. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  6705. and copying tuples into the ToSpace.
  6706. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  6707. copy progresses. The queue is represented by a chunk of contiguous
  6708. memory at the beginning of the ToSpace, using two pointers to track
  6709. the front and the back of the queue. The algorithm starts by copying
  6710. all tuples that are immediately reachable from the root set into the
  6711. ToSpace to form the initial queue. When we copy a tuple, we mark the
  6712. old tuple to indicate that it has been visited. We discuss how this
  6713. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  6714. pointers inside the copied tuples in the queue still point back to the
  6715. FromSpace. Once the initial queue has been created, the algorithm
  6716. enters a loop in which it repeatedly processes the tuple at the front
  6717. of the queue and pops it off the queue. To process a tuple, the
  6718. algorithm copies all the tuple that are directly reachable from it to
  6719. the ToSpace, placing them at the back of the queue. The algorithm then
  6720. updates the pointers in the popped tuple so they point to the newly
  6721. copied tuples.
  6722. \begin{figure}[tbp]
  6723. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  6724. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  6725. \label{fig:cheney}
  6726. \end{figure}
  6727. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  6728. tuple whose second element is $42$ to the back of the queue. The other
  6729. pointer goes to a tuple that has already been copied, so we do not
  6730. need to copy it again, but we do need to update the pointer to the new
  6731. location. This can be accomplished by storing a \emph{forwarding
  6732. pointer} to the new location in the old tuple, back when we initially
  6733. copied the tuple into the ToSpace. This completes one step of the
  6734. algorithm. The algorithm continues in this way until the front of the
  6735. queue is empty, that is, until the front catches up with the back.
  6736. \subsection{Data Representation}
  6737. \label{sec:data-rep-gc}
  6738. The garbage collector places some requirements on the data
  6739. representations used by our compiler. First, the garbage collector
  6740. needs to distinguish between pointers and other kinds of data. There
  6741. are several ways to accomplish this.
  6742. \begin{enumerate}
  6743. \item Attached a tag to each object that identifies what type of
  6744. object it is~\citep{McCarthy:1960dz}.
  6745. \item Store different types of objects in different
  6746. regions~\citep{Steele:1977ab}.
  6747. \item Use type information from the program to either generate
  6748. type-specific code for collecting or to generate tables that can
  6749. guide the
  6750. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6751. \end{enumerate}
  6752. Dynamically typed languages, such as Lisp, need to tag objects
  6753. anyways, so option 1 is a natural choice for those languages.
  6754. However, \LangVec{} is a statically typed language, so it would be
  6755. unfortunate to require tags on every object, especially small and
  6756. pervasive objects like integers and Booleans. Option 3 is the
  6757. best-performing choice for statically typed languages, but comes with
  6758. a relatively high implementation complexity. To keep this chapter
  6759. within a 2-week time budget, we recommend a combination of options 1
  6760. and 2, using separate strategies for the stack and the heap.
  6761. Regarding the stack, we recommend using a separate stack for pointers,
  6762. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6763. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6764. is, when a local variable needs to be spilled and is of type
  6765. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6766. stack instead of the normal procedure call stack. Furthermore, we
  6767. always spill vector-typed variables if they are live during a call to
  6768. the collector, thereby ensuring that no pointers are in registers
  6769. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6770. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6771. the data layout using a root stack. The root stack contains the two
  6772. pointers from the regular stack and also the pointer in the second
  6773. register.
  6774. \begin{figure}[tbp]
  6775. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6776. \caption{Maintaining a root stack to facilitate garbage collection.}
  6777. \label{fig:shadow-stack}
  6778. \end{figure}
  6779. The problem of distinguishing between pointers and other kinds of data
  6780. also arises inside of each tuple on the heap. We solve this problem by
  6781. attaching a tag, an extra 64-bits, to each
  6782. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6783. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6784. that we have drawn the bits in a big-endian way, from right-to-left,
  6785. with bit location 0 (the least significant bit) on the far right,
  6786. which corresponds to the direction of the x86 shifting instructions
  6787. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6788. is dedicated to specifying which elements of the tuple are pointers,
  6789. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6790. indicates there is a pointer and a 0 bit indicates some other kind of
  6791. data. The pointer mask starts at bit location 7. We have limited
  6792. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6793. the pointer mask. The tag also contains two other pieces of
  6794. information. The length of the tuple (number of elements) is stored in
  6795. bits location 1 through 6. Finally, the bit at location 0 indicates
  6796. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6797. value 1, then this tuple has not yet been copied. If the bit has
  6798. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6799. of a pointer are always zero anyways because our tuples are 8-byte
  6800. aligned.)
  6801. \begin{figure}[tbp]
  6802. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6803. \caption{Representation of tuples in the heap.}
  6804. \label{fig:tuple-rep}
  6805. \end{figure}
  6806. \subsection{Implementation of the Garbage Collector}
  6807. \label{sec:organize-gz}
  6808. \index{prelude}
  6809. An implementation of the copying collector is provided in the
  6810. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6811. interface to the garbage collector that is used by the compiler. The
  6812. \code{initialize} function creates the FromSpace, ToSpace, and root
  6813. stack and should be called in the prelude of the \code{main}
  6814. function. The arguments of \code{initialize} are the root stack size
  6815. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6816. good choice for both. The \code{initialize} function puts the address
  6817. of the beginning of the FromSpace into the global variable
  6818. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6819. the address that is 1-past the last element of the FromSpace. (We use
  6820. half-open intervals to represent chunks of
  6821. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6822. points to the first element of the root stack.
  6823. As long as there is room left in the FromSpace, your generated code
  6824. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6825. %
  6826. The amount of room left in FromSpace is the difference between the
  6827. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6828. function should be called when there is not enough room left in the
  6829. FromSpace for the next allocation. The \code{collect} function takes
  6830. a pointer to the current top of the root stack (one past the last item
  6831. that was pushed) and the number of bytes that need to be
  6832. allocated. The \code{collect} function performs the copying collection
  6833. and leaves the heap in a state such that the next allocation will
  6834. succeed.
  6835. \begin{figure}[tbp]
  6836. \begin{lstlisting}
  6837. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6838. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6839. int64_t* free_ptr;
  6840. int64_t* fromspace_begin;
  6841. int64_t* fromspace_end;
  6842. int64_t** rootstack_begin;
  6843. \end{lstlisting}
  6844. \caption{The compiler's interface to the garbage collector.}
  6845. \label{fig:gc-header}
  6846. \end{figure}
  6847. %% \begin{exercise}
  6848. %% In the file \code{runtime.c} you will find the implementation of
  6849. %% \code{initialize} and a partial implementation of \code{collect}.
  6850. %% The \code{collect} function calls another function, \code{cheney},
  6851. %% to perform the actual copy, and that function is left to the reader
  6852. %% to implement. The following is the prototype for \code{cheney}.
  6853. %% \begin{lstlisting}
  6854. %% static void cheney(int64_t** rootstack_ptr);
  6855. %% \end{lstlisting}
  6856. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6857. %% rootstack (which is an array of pointers). The \code{cheney} function
  6858. %% also communicates with \code{collect} through the global
  6859. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6860. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6861. %% the ToSpace:
  6862. %% \begin{lstlisting}
  6863. %% static int64_t* tospace_begin;
  6864. %% static int64_t* tospace_end;
  6865. %% \end{lstlisting}
  6866. %% The job of the \code{cheney} function is to copy all the live
  6867. %% objects (reachable from the root stack) into the ToSpace, update
  6868. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6869. %% update the root stack so that it points to the objects in the
  6870. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6871. %% and ToSpace.
  6872. %% \end{exercise}
  6873. %% \section{Compiler Passes}
  6874. %% \label{sec:code-generation-gc}
  6875. The introduction of garbage collection has a non-trivial impact on our
  6876. compiler passes. We introduce a new compiler pass named
  6877. \code{expose-allocation}. We make
  6878. significant changes to \code{select-instructions},
  6879. \code{build-interference}, \code{allocate-registers}, and
  6880. \code{print-x86} and make minor changes in several more passes. The
  6881. following program will serve as our running example. It creates two
  6882. tuples, one nested inside the other. Both tuples have length one. The
  6883. program accesses the element in the inner tuple tuple via two vector
  6884. references.
  6885. % tests/s2_17.rkt
  6886. \begin{lstlisting}
  6887. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6888. \end{lstlisting}
  6889. \section{Shrink}
  6890. \label{sec:shrink-Rvec}
  6891. Recall that the \code{shrink} pass translates the primitives operators
  6892. into a smaller set of primitives. Because this pass comes after type
  6893. checking, but before the passes that require the type information in
  6894. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6895. to wrap \code{HasType} around each AST node that it generates.
  6896. \section{Expose Allocation}
  6897. \label{sec:expose-allocation}
  6898. The pass \code{expose-allocation} lowers the \code{vector} creation
  6899. form into a conditional call to the collector followed by the
  6900. allocation. We choose to place the \code{expose-allocation} pass
  6901. before \code{remove-complex-opera*} because the code generated by
  6902. \code{expose-allocation} contains complex operands. We also place
  6903. \code{expose-allocation} before \code{explicate-control} because
  6904. \code{expose-allocation} introduces new variables using \code{let},
  6905. but \code{let} is gone after \code{explicate-control}.
  6906. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6907. extends \LangVec{} with the three new forms that we use in the translation
  6908. of the \code{vector} form.
  6909. \[
  6910. \begin{array}{lcl}
  6911. \Exp &::=& \cdots
  6912. \mid (\key{collect} \,\itm{int})
  6913. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6914. \mid (\key{global-value} \,\itm{name})
  6915. \end{array}
  6916. \]
  6917. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6918. $n$ bytes. It will become a call to the \code{collect} function in
  6919. \code{runtime.c} in \code{select-instructions}. The
  6920. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6921. \index{allocate}
  6922. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6923. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6924. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6925. a global variable, such as \code{free\_ptr}.
  6926. In the following, we show the transformation for the \code{vector}
  6927. form into 1) a sequence of let-bindings for the initializing
  6928. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6929. \code{allocate}, and 4) the initialization of the vector. In the
  6930. following, \itm{len} refers to the length of the vector and
  6931. \itm{bytes} is how many total bytes need to be allocated for the
  6932. vector, which is 8 for the tag plus \itm{len} times 8.
  6933. \begin{lstlisting}
  6934. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6935. |$\Longrightarrow$|
  6936. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6937. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6938. (global-value fromspace_end))
  6939. (void)
  6940. (collect |\itm{bytes}|))])
  6941. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6942. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6943. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6944. |$v$|) ... )))) ...)
  6945. \end{lstlisting}
  6946. In the above, we suppressed all of the \code{has-type} forms in the
  6947. output for the sake of readability. The placement of the initializing
  6948. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6949. sequence of \code{vector-set!} is important, as those expressions may
  6950. trigger garbage collection and we cannot have an allocated but
  6951. uninitialized tuple on the heap during a collection.
  6952. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6953. \code{expose-allocation} pass on our running example.
  6954. \begin{figure}[tbp]
  6955. % tests/s2_17.rkt
  6956. \begin{lstlisting}
  6957. (vector-ref
  6958. (vector-ref
  6959. (let ([vecinit7976
  6960. (let ([vecinit7972 42])
  6961. (let ([collectret7974
  6962. (if (< (+ (global-value free_ptr) 16)
  6963. (global-value fromspace_end))
  6964. (void)
  6965. (collect 16)
  6966. )])
  6967. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6968. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6969. alloc7971)
  6970. )
  6971. )
  6972. )
  6973. ])
  6974. (let ([collectret7978
  6975. (if (< (+ (global-value free_ptr) 16)
  6976. (global-value fromspace_end))
  6977. (void)
  6978. (collect 16)
  6979. )])
  6980. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6981. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6982. alloc7975)
  6983. )
  6984. )
  6985. )
  6986. 0)
  6987. 0)
  6988. \end{lstlisting}
  6989. \caption{Output of the \code{expose-allocation} pass, minus
  6990. all of the \code{has-type} forms.}
  6991. \label{fig:expose-alloc-output}
  6992. \end{figure}
  6993. \section{Remove Complex Operands}
  6994. \label{sec:remove-complex-opera-Rvec}
  6995. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6996. should all be treated as complex operands.
  6997. %% A new case for
  6998. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6999. %% handled carefully to prevent the \code{Prim} node from being separated
  7000. %% from its enclosing \code{HasType}.
  7001. Figure~\ref{fig:Rvec-anf-syntax}
  7002. shows the grammar for the output language \LangVecANF{} of this
  7003. pass, which is \LangVec{} in administrative normal form.
  7004. \begin{figure}[tp]
  7005. \centering
  7006. \fbox{
  7007. \begin{minipage}{0.96\textwidth}
  7008. \small
  7009. \[
  7010. \begin{array}{rcl}
  7011. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  7012. \mid \VOID{} \\
  7013. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7014. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7015. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7016. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7017. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7018. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7019. \mid \LP\key{GlobalValue}~\Var\RP\\
  7020. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  7021. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  7022. \end{array}
  7023. \]
  7024. \end{minipage}
  7025. }
  7026. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  7027. \label{fig:Rvec-anf-syntax}
  7028. \end{figure}
  7029. \section{Explicate Control and the \LangCVec{} language}
  7030. \label{sec:explicate-control-r3}
  7031. \begin{figure}[tp]
  7032. \fbox{
  7033. \begin{minipage}{0.96\textwidth}
  7034. \small
  7035. \[
  7036. \begin{array}{lcl}
  7037. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7038. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7039. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7040. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7041. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7042. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  7043. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  7044. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  7045. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  7046. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  7047. \mid \LP\key{Collect} \,\itm{int}\RP \\
  7048. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7049. \mid \GOTO{\itm{label}} } \\
  7050. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7051. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  7052. \end{array}
  7053. \]
  7054. \end{minipage}
  7055. }
  7056. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  7057. (Figure~\ref{fig:c1-syntax}).}
  7058. \label{fig:c2-syntax}
  7059. \end{figure}
  7060. The output of \code{explicate-control} is a program in the
  7061. intermediate language \LangCVec{}, whose abstract syntax is defined in
  7062. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  7063. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  7064. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  7065. \key{vector-set!}, and \key{global-value} expressions and the
  7066. \code{collect} statement. The \code{explicate-control} pass can treat
  7067. these new forms much like the other expression forms that we've
  7068. already encoutered.
  7069. \section{Select Instructions and the \LangXGlobal{} Language}
  7070. \label{sec:select-instructions-gc}
  7071. \index{instruction selection}
  7072. %% void (rep as zero)
  7073. %% allocate
  7074. %% collect (callq collect)
  7075. %% vector-ref
  7076. %% vector-set!
  7077. %% global (postpone)
  7078. In this pass we generate x86 code for most of the new operations that
  7079. were needed to compile tuples, including \code{Allocate},
  7080. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  7081. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  7082. the later has a different concrete syntax (see
  7083. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  7084. \index{x86}
  7085. The \code{vector-ref} and \code{vector-set!} forms translate into
  7086. \code{movq} instructions. (The plus one in the offset is to get past
  7087. the tag at the beginning of the tuple representation.)
  7088. \begin{lstlisting}
  7089. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  7090. |$\Longrightarrow$|
  7091. movq |$\itm{vec}'$|, %r11
  7092. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  7093. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  7094. |$\Longrightarrow$|
  7095. movq |$\itm{vec}'$|, %r11
  7096. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  7097. movq $0, |$\itm{lhs'}$|
  7098. \end{lstlisting}
  7099. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  7100. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  7101. register \code{r11} ensures that offset expression
  7102. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  7103. removing \code{r11} from consideration by the register allocating.
  7104. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  7105. \code{rax}. Then the generated code for \code{vector-set!} would be
  7106. \begin{lstlisting}
  7107. movq |$\itm{vec}'$|, %rax
  7108. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  7109. movq $0, |$\itm{lhs}'$|
  7110. \end{lstlisting}
  7111. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  7112. \code{patch-instructions} would insert a move through \code{rax}
  7113. as follows.
  7114. \begin{lstlisting}
  7115. movq |$\itm{vec}'$|, %rax
  7116. movq |$\itm{arg}'$|, %rax
  7117. movq %rax, |$8(n+1)$|(%rax)
  7118. movq $0, |$\itm{lhs}'$|
  7119. \end{lstlisting}
  7120. But the above sequence of instructions does not work because we're
  7121. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  7122. $\itm{arg}'$) at the same time!
  7123. We compile the \code{allocate} form to operations on the
  7124. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  7125. is the next free address in the FromSpace, so we copy it into
  7126. \code{r11} and then move it forward by enough space for the tuple
  7127. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  7128. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  7129. initialize the \itm{tag} and finally copy the address in \code{r11} to
  7130. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  7131. tag is organized. We recommend using the Racket operations
  7132. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  7133. during compilation. The type annotation in the \code{vector} form is
  7134. used to determine the pointer mask region of the tag.
  7135. \begin{lstlisting}
  7136. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  7137. |$\Longrightarrow$|
  7138. movq free_ptr(%rip), %r11
  7139. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  7140. movq $|$\itm{tag}$|, 0(%r11)
  7141. movq %r11, |$\itm{lhs}'$|
  7142. \end{lstlisting}
  7143. The \code{collect} form is compiled to a call to the \code{collect}
  7144. function in the runtime. The arguments to \code{collect} are 1) the
  7145. top of the root stack and 2) the number of bytes that need to be
  7146. allocated. We use another dedicated register, \code{r15}, to
  7147. store the pointer to the top of the root stack. So \code{r15} is not
  7148. available for use by the register allocator.
  7149. \begin{lstlisting}
  7150. (collect |$\itm{bytes}$|)
  7151. |$\Longrightarrow$|
  7152. movq %r15, %rdi
  7153. movq $|\itm{bytes}|, %rsi
  7154. callq collect
  7155. \end{lstlisting}
  7156. \begin{figure}[tp]
  7157. \fbox{
  7158. \begin{minipage}{0.96\textwidth}
  7159. \[
  7160. \begin{array}{lcl}
  7161. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  7162. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  7163. & & \gray{ \key{main:} \; \Instr\ldots }
  7164. \end{array}
  7165. \]
  7166. \end{minipage}
  7167. }
  7168. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  7169. \label{fig:x86-2-concrete}
  7170. \end{figure}
  7171. \begin{figure}[tp]
  7172. \fbox{
  7173. \begin{minipage}{0.96\textwidth}
  7174. \small
  7175. \[
  7176. \begin{array}{lcl}
  7177. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7178. \mid \BYTEREG{\Reg}} \\
  7179. &\mid& (\key{Global}~\Var) \\
  7180. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  7181. \end{array}
  7182. \]
  7183. \end{minipage}
  7184. }
  7185. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  7186. \label{fig:x86-2}
  7187. \end{figure}
  7188. The concrete and abstract syntax of the \LangXGlobal{} language is
  7189. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  7190. differs from \LangXIf{} just in the addition of the form for global
  7191. variables.
  7192. %
  7193. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  7194. \code{select-instructions} pass on the running example.
  7195. \begin{figure}[tbp]
  7196. \centering
  7197. % tests/s2_17.rkt
  7198. \begin{minipage}[t]{0.5\textwidth}
  7199. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7200. block35:
  7201. movq free_ptr(%rip), alloc9024
  7202. addq $16, free_ptr(%rip)
  7203. movq alloc9024, %r11
  7204. movq $131, 0(%r11)
  7205. movq alloc9024, %r11
  7206. movq vecinit9025, 8(%r11)
  7207. movq $0, initret9026
  7208. movq alloc9024, %r11
  7209. movq 8(%r11), tmp9034
  7210. movq tmp9034, %r11
  7211. movq 8(%r11), %rax
  7212. jmp conclusion
  7213. block36:
  7214. movq $0, collectret9027
  7215. jmp block35
  7216. block38:
  7217. movq free_ptr(%rip), alloc9020
  7218. addq $16, free_ptr(%rip)
  7219. movq alloc9020, %r11
  7220. movq $3, 0(%r11)
  7221. movq alloc9020, %r11
  7222. movq vecinit9021, 8(%r11)
  7223. movq $0, initret9022
  7224. movq alloc9020, vecinit9025
  7225. movq free_ptr(%rip), tmp9031
  7226. movq tmp9031, tmp9032
  7227. addq $16, tmp9032
  7228. movq fromspace_end(%rip), tmp9033
  7229. cmpq tmp9033, tmp9032
  7230. jl block36
  7231. jmp block37
  7232. block37:
  7233. movq %r15, %rdi
  7234. movq $16, %rsi
  7235. callq 'collect
  7236. jmp block35
  7237. block39:
  7238. movq $0, collectret9023
  7239. jmp block38
  7240. \end{lstlisting}
  7241. \end{minipage}
  7242. \begin{minipage}[t]{0.45\textwidth}
  7243. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7244. start:
  7245. movq $42, vecinit9021
  7246. movq free_ptr(%rip), tmp9028
  7247. movq tmp9028, tmp9029
  7248. addq $16, tmp9029
  7249. movq fromspace_end(%rip), tmp9030
  7250. cmpq tmp9030, tmp9029
  7251. jl block39
  7252. jmp block40
  7253. block40:
  7254. movq %r15, %rdi
  7255. movq $16, %rsi
  7256. callq 'collect
  7257. jmp block38
  7258. \end{lstlisting}
  7259. \end{minipage}
  7260. \caption{Output of the \code{select-instructions} pass.}
  7261. \label{fig:select-instr-output-gc}
  7262. \end{figure}
  7263. \clearpage
  7264. \section{Register Allocation}
  7265. \label{sec:reg-alloc-gc}
  7266. \index{register allocation}
  7267. As discussed earlier in this chapter, the garbage collector needs to
  7268. access all the pointers in the root set, that is, all variables that
  7269. are vectors. It will be the responsibility of the register allocator
  7270. to make sure that:
  7271. \begin{enumerate}
  7272. \item the root stack is used for spilling vector-typed variables, and
  7273. \item if a vector-typed variable is live during a call to the
  7274. collector, it must be spilled to ensure it is visible to the
  7275. collector.
  7276. \end{enumerate}
  7277. The later responsibility can be handled during construction of the
  7278. interference graph, by adding interference edges between the call-live
  7279. vector-typed variables and all the callee-saved registers. (They
  7280. already interfere with the caller-saved registers.) The type
  7281. information for variables is in the \code{Program} form, so we
  7282. recommend adding another parameter to the \code{build-interference}
  7283. function to communicate this alist.
  7284. The spilling of vector-typed variables to the root stack can be
  7285. handled after graph coloring, when choosing how to assign the colors
  7286. (integers) to registers and stack locations. The \code{Program} output
  7287. of this pass changes to also record the number of spills to the root
  7288. stack.
  7289. % build-interference
  7290. %
  7291. % callq
  7292. % extra parameter for var->type assoc. list
  7293. % update 'program' and 'if'
  7294. % allocate-registers
  7295. % allocate spilled vectors to the rootstack
  7296. % don't change color-graph
  7297. \section{Print x86}
  7298. \label{sec:print-x86-gc}
  7299. \index{prelude}\index{conclusion}
  7300. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  7301. \code{print-x86} pass on the running example. In the prelude and
  7302. conclusion of the \code{main} function, we treat the root stack very
  7303. much like the regular stack in that we move the root stack pointer
  7304. (\code{r15}) to make room for the spills to the root stack, except
  7305. that the root stack grows up instead of down. For the running
  7306. example, there was just one spill so we increment \code{r15} by 8
  7307. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  7308. One issue that deserves special care is that there may be a call to
  7309. \code{collect} prior to the initializing assignments for all the
  7310. variables in the root stack. We do not want the garbage collector to
  7311. accidentally think that some uninitialized variable is a pointer that
  7312. needs to be followed. Thus, we zero-out all locations on the root
  7313. stack in the prelude of \code{main}. In
  7314. Figure~\ref{fig:print-x86-output-gc}, the instruction
  7315. %
  7316. \lstinline{movq $0, (%r15)}
  7317. %
  7318. accomplishes this task. The garbage collector tests each root to see
  7319. if it is null prior to dereferencing it.
  7320. \begin{figure}[htbp]
  7321. \begin{minipage}[t]{0.5\textwidth}
  7322. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7323. block35:
  7324. movq free_ptr(%rip), %rcx
  7325. addq $16, free_ptr(%rip)
  7326. movq %rcx, %r11
  7327. movq $131, 0(%r11)
  7328. movq %rcx, %r11
  7329. movq -8(%r15), %rax
  7330. movq %rax, 8(%r11)
  7331. movq $0, %rdx
  7332. movq %rcx, %r11
  7333. movq 8(%r11), %rcx
  7334. movq %rcx, %r11
  7335. movq 8(%r11), %rax
  7336. jmp conclusion
  7337. block36:
  7338. movq $0, %rcx
  7339. jmp block35
  7340. block38:
  7341. movq free_ptr(%rip), %rcx
  7342. addq $16, free_ptr(%rip)
  7343. movq %rcx, %r11
  7344. movq $3, 0(%r11)
  7345. movq %rcx, %r11
  7346. movq %rbx, 8(%r11)
  7347. movq $0, %rdx
  7348. movq %rcx, -8(%r15)
  7349. movq free_ptr(%rip), %rcx
  7350. addq $16, %rcx
  7351. movq fromspace_end(%rip), %rdx
  7352. cmpq %rdx, %rcx
  7353. jl block36
  7354. movq %r15, %rdi
  7355. movq $16, %rsi
  7356. callq collect
  7357. jmp block35
  7358. block39:
  7359. movq $0, %rcx
  7360. jmp block38
  7361. \end{lstlisting}
  7362. \end{minipage}
  7363. \begin{minipage}[t]{0.45\textwidth}
  7364. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7365. start:
  7366. movq $42, %rbx
  7367. movq free_ptr(%rip), %rdx
  7368. addq $16, %rdx
  7369. movq fromspace_end(%rip), %rcx
  7370. cmpq %rcx, %rdx
  7371. jl block39
  7372. movq %r15, %rdi
  7373. movq $16, %rsi
  7374. callq collect
  7375. jmp block38
  7376. .globl main
  7377. main:
  7378. pushq %rbp
  7379. movq %rsp, %rbp
  7380. pushq %r13
  7381. pushq %r12
  7382. pushq %rbx
  7383. pushq %r14
  7384. subq $0, %rsp
  7385. movq $16384, %rdi
  7386. movq $16384, %rsi
  7387. callq initialize
  7388. movq rootstack_begin(%rip), %r15
  7389. movq $0, (%r15)
  7390. addq $8, %r15
  7391. jmp start
  7392. conclusion:
  7393. subq $8, %r15
  7394. addq $0, %rsp
  7395. popq %r14
  7396. popq %rbx
  7397. popq %r12
  7398. popq %r13
  7399. popq %rbp
  7400. retq
  7401. \end{lstlisting}
  7402. \end{minipage}
  7403. \caption{Output of the \code{print-x86} pass.}
  7404. \label{fig:print-x86-output-gc}
  7405. \end{figure}
  7406. \begin{figure}[p]
  7407. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7408. \node (Rvec) at (0,2) {\large \LangVec{}};
  7409. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  7410. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  7411. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  7412. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  7413. \node (C2-4) at (3,0) {\large \LangCVec{}};
  7414. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  7415. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  7416. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  7417. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  7418. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  7419. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  7420. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  7421. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  7422. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  7423. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  7424. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  7425. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  7426. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  7427. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7428. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7429. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7430. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  7431. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  7432. \end{tikzpicture}
  7433. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  7434. \label{fig:Rvec-passes}
  7435. \end{figure}
  7436. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  7437. for the compilation of \LangVec{}.
  7438. \section{Challenge: Simple Structures}
  7439. \label{sec:simple-structures}
  7440. \index{struct}
  7441. \index{structure}
  7442. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  7443. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  7444. Recall that a \code{struct} in Typed Racket is a user-defined data
  7445. type that contains named fields and that is heap allocated, similar to
  7446. a vector. The following is an example of a structure definition, in
  7447. this case the definition of a \code{point} type.
  7448. \begin{lstlisting}
  7449. (struct point ([x : Integer] [y : Integer]) #:mutable)
  7450. \end{lstlisting}
  7451. \begin{figure}[tbp]
  7452. \centering
  7453. \fbox{
  7454. \begin{minipage}{0.96\textwidth}
  7455. \[
  7456. \begin{array}{lcl}
  7457. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7458. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  7459. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  7460. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  7461. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  7462. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  7463. \mid (\key{and}\;\Exp\;\Exp)
  7464. \mid (\key{or}\;\Exp\;\Exp)
  7465. \mid (\key{not}\;\Exp) } \\
  7466. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  7467. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  7468. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  7469. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  7470. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  7471. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  7472. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  7473. \LangStruct{} &::=& \Def \ldots \; \Exp
  7474. \end{array}
  7475. \]
  7476. \end{minipage}
  7477. }
  7478. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  7479. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7480. \label{fig:r3s-concrete-syntax}
  7481. \end{figure}
  7482. An instance of a structure is created using function call syntax, with
  7483. the name of the structure in the function position:
  7484. \begin{lstlisting}
  7485. (point 7 12)
  7486. \end{lstlisting}
  7487. Function-call syntax is also used to read the value in a field of a
  7488. structure. The function name is formed by the structure name, a dash,
  7489. and the field name. The following example uses \code{point-x} and
  7490. \code{point-y} to access the \code{x} and \code{y} fields of two point
  7491. instances.
  7492. \begin{center}
  7493. \begin{lstlisting}
  7494. (let ([pt1 (point 7 12)])
  7495. (let ([pt2 (point 4 3)])
  7496. (+ (- (point-x pt1) (point-x pt2))
  7497. (- (point-y pt1) (point-y pt2)))))
  7498. \end{lstlisting}
  7499. \end{center}
  7500. Similarly, to write to a field of a structure, use its set function,
  7501. whose name starts with \code{set-}, followed by the structure name,
  7502. then a dash, then the field name, and concluded with an exclamation
  7503. mark. The following example uses \code{set-point-x!} to change the
  7504. \code{x} field from \code{7} to \code{42}.
  7505. \begin{center}
  7506. \begin{lstlisting}
  7507. (let ([pt (point 7 12)])
  7508. (let ([_ (set-point-x! pt 42)])
  7509. (point-x pt)))
  7510. \end{lstlisting}
  7511. \end{center}
  7512. \begin{exercise}\normalfont
  7513. Extend your compiler with support for simple structures, compiling
  7514. \LangStruct{} to x86 assembly code. Create five new test cases that use
  7515. structures and test your compiler.
  7516. \end{exercise}
  7517. \section{Challenge: Generational Collection}
  7518. The copying collector described in Section~\ref{sec:GC} can incur
  7519. significant runtime overhead because the call to \code{collect} takes
  7520. time proportional to all of the live data. One way to reduce this
  7521. overhead is to reduce how much data is inspected in each call to
  7522. \code{collect}. In particular, researchers have observed that recently
  7523. allocated data is more likely to become garbage then data that has
  7524. survived one or more previous calls to \code{collect}. This insight
  7525. motivated the creation of \emph{generational garbage collectors}
  7526. \index{generational garbage collector} that
  7527. 1) segregates data according to its age into two or more generations,
  7528. 2) allocates less space for younger generations, so collecting them is
  7529. faster, and more space for the older generations, and 3) performs
  7530. collection on the younger generations more frequently then for older
  7531. generations~\citep{Wilson:1992fk}.
  7532. For this challenge assignment, the goal is to adapt the copying
  7533. collector implemented in \code{runtime.c} to use two generations, one
  7534. for young data and one for old data. Each generation consists of a
  7535. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  7536. \code{collect} function to use the two generations.
  7537. \begin{enumerate}
  7538. \item Copy the young generation's FromSpace to its ToSpace then switch
  7539. the role of the ToSpace and FromSpace
  7540. \item If there is enough space for the requested number of bytes in
  7541. the young FromSpace, then return from \code{collect}.
  7542. \item If there is not enough space in the young FromSpace for the
  7543. requested bytes, then move the data from the young generation to the
  7544. old one with the following steps:
  7545. \begin{enumerate}
  7546. \item If there is enough room in the old FromSpace, copy the young
  7547. FromSpace to the old FromSpace and then return.
  7548. \item If there is not enough room in the old FromSpace, then collect
  7549. the old generation by copying the old FromSpace to the old ToSpace
  7550. and swap the roles of the old FromSpace and ToSpace.
  7551. \item If there is enough room now, copy the young FromSpace to the
  7552. old FromSpace and return. Otherwise, allocate a larger FromSpace
  7553. and ToSpace for the old generation. Copy the young FromSpace and
  7554. the old FromSpace into the larger FromSpace for the old
  7555. generation and then return.
  7556. \end{enumerate}
  7557. \end{enumerate}
  7558. We recommend that you generalize the \code{cheney} function so that it
  7559. can be used for all the copies mentioned above: between the young
  7560. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  7561. between the young FromSpace and old FromSpace. This can be
  7562. accomplished by adding parameters to \code{cheney} that replace its
  7563. use of the global variables \code{fromspace\_begin},
  7564. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  7565. Note that the collection of the young generation does not traverse the
  7566. old generation. This introduces a potential problem: there may be
  7567. young data that is only reachable through pointers in the old
  7568. generation. If these pointers are not taken into account, the
  7569. collector could throw away young data that is live! One solution,
  7570. called \emph{pointer recording}, is to maintain a set of all the
  7571. pointers from the old generation into the new generation and consider
  7572. this set as part of the root set. To maintain this set, the compiler
  7573. must insert extra instructions around every \code{vector-set!}. If the
  7574. vector being modified is in the old generation, and if the value being
  7575. written is a pointer into the new generation, than that pointer must
  7576. be added to the set. Also, if the value being overwritten was a
  7577. pointer into the new generation, then that pointer should be removed
  7578. from the set.
  7579. \begin{exercise}\normalfont
  7580. Adapt the \code{collect} function in \code{runtime.c} to implement
  7581. generational garbage collection, as outlined in this section.
  7582. Update the code generation for \code{vector-set!} to implement
  7583. pointer recording. Make sure that your new compiler and runtime
  7584. passes your test suite.
  7585. \end{exercise}
  7586. % Further Reading
  7587. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7588. \chapter{Functions}
  7589. \label{ch:Rfun}
  7590. \index{function}
  7591. This chapter studies the compilation of functions similar to those
  7592. found in the C language. This corresponds to a subset of Typed Racket
  7593. in which only top-level function definitions are allowed. This kind of
  7594. function is an important stepping stone to implementing
  7595. lexically-scoped functions, that is, \key{lambda} abstractions, which
  7596. is the topic of Chapter~\ref{ch:Rlam}.
  7597. \section{The \LangFun{} Language}
  7598. The concrete and abstract syntax for function definitions and function
  7599. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  7600. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  7601. \LangFun{} begin with zero or more function definitions. The function
  7602. names from these definitions are in-scope for the entire program,
  7603. including all other function definitions (so the ordering of function
  7604. definitions does not matter). The concrete syntax for function
  7605. application\index{function application} is $(\Exp \; \Exp \ldots)$
  7606. where the first expression must
  7607. evaluate to a function and the rest are the arguments.
  7608. The abstract syntax for function application is
  7609. $\APPLY{\Exp}{\Exp\ldots}$.
  7610. %% The syntax for function application does not include an explicit
  7611. %% keyword, which is error prone when using \code{match}. To alleviate
  7612. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  7613. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  7614. Functions are first-class in the sense that a function pointer
  7615. \index{function pointer} is data and can be stored in memory or passed
  7616. as a parameter to another function. Thus, we introduce a function
  7617. type, written
  7618. \begin{lstlisting}
  7619. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  7620. \end{lstlisting}
  7621. for a function whose $n$ parameters have the types $\Type_1$ through
  7622. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  7623. these functions (with respect to Racket functions) is that they are
  7624. not lexically scoped. That is, the only external entities that can be
  7625. referenced from inside a function body are other globally-defined
  7626. functions. The syntax of \LangFun{} prevents functions from being nested
  7627. inside each other.
  7628. \begin{figure}[tp]
  7629. \centering
  7630. \fbox{
  7631. \begin{minipage}{0.96\textwidth}
  7632. \small
  7633. \[
  7634. \begin{array}{lcl}
  7635. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  7636. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  7637. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  7638. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7639. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7640. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  7641. \mid (\key{and}\;\Exp\;\Exp)
  7642. \mid (\key{or}\;\Exp\;\Exp)
  7643. \mid (\key{not}\;\Exp)} \\
  7644. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7645. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7646. (\key{vector-ref}\;\Exp\;\Int)} \\
  7647. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7648. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  7649. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  7650. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  7651. \LangFun{} &::=& \Def \ldots \; \Exp
  7652. \end{array}
  7653. \]
  7654. \end{minipage}
  7655. }
  7656. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7657. \label{fig:Rfun-concrete-syntax}
  7658. \end{figure}
  7659. \begin{figure}[tp]
  7660. \centering
  7661. \fbox{
  7662. \begin{minipage}{0.96\textwidth}
  7663. \small
  7664. \[
  7665. \begin{array}{lcl}
  7666. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7667. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7668. &\mid& \gray{ \BOOL{\itm{bool}}
  7669. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7670. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  7671. \mid \APPLY{\Exp}{\Exp\ldots}\\
  7672. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  7673. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  7674. \end{array}
  7675. \]
  7676. \end{minipage}
  7677. }
  7678. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  7679. \label{fig:Rfun-syntax}
  7680. \end{figure}
  7681. The program in Figure~\ref{fig:Rfun-function-example} is a
  7682. representative example of defining and using functions in \LangFun{}. We
  7683. define a function \code{map-vec} that applies some other function
  7684. \code{f} to both elements of a vector and returns a new
  7685. vector containing the results. We also define a function \code{add1}.
  7686. The program applies
  7687. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  7688. \code{(vector 1 42)}, from which we return the \code{42}.
  7689. \begin{figure}[tbp]
  7690. \begin{lstlisting}
  7691. (define (map-vec [f : (Integer -> Integer)]
  7692. [v : (Vector Integer Integer)])
  7693. : (Vector Integer Integer)
  7694. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  7695. (define (add1 [x : Integer]) : Integer
  7696. (+ x 1))
  7697. (vector-ref (map-vec add1 (vector 0 41)) 1)
  7698. \end{lstlisting}
  7699. \caption{Example of using functions in \LangFun{}.}
  7700. \label{fig:Rfun-function-example}
  7701. \end{figure}
  7702. The definitional interpreter for \LangFun{} is in
  7703. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  7704. responsible for setting up the mutual recursion between the top-level
  7705. function definitions. We use the classic back-patching \index{back-patching}
  7706. approach that uses mutable variables and makes two passes over the function
  7707. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  7708. top-level environment using a mutable cons cell for each function
  7709. definition. Note that the \code{lambda} value for each function is
  7710. incomplete; it does not yet include the environment. Once the
  7711. top-level environment is constructed, we then iterate over it and
  7712. update the \code{lambda} values to use the top-level environment.
  7713. \begin{figure}[tp]
  7714. \begin{lstlisting}
  7715. (define interp-Rfun-class
  7716. (class interp-Rvec-class
  7717. (super-new)
  7718. (define/override ((interp-exp env) e)
  7719. (define recur (interp-exp env))
  7720. (match e
  7721. [(Var x) (unbox (dict-ref env x))]
  7722. [(Let x e body)
  7723. (define new-env (dict-set env x (box (recur e))))
  7724. ((interp-exp new-env) body)]
  7725. [(Apply fun args)
  7726. (define fun-val (recur fun))
  7727. (define arg-vals (for/list ([e args]) (recur e)))
  7728. (match fun-val
  7729. [`(function (,xs ...) ,body ,fun-env)
  7730. (define params-args (for/list ([x xs] [arg arg-vals])
  7731. (cons x (box arg))))
  7732. (define new-env (append params-args fun-env))
  7733. ((interp-exp new-env) body)]
  7734. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  7735. [else ((super interp-exp env) e)]
  7736. ))
  7737. (define/public (interp-def d)
  7738. (match d
  7739. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  7740. (cons f (box `(function ,xs ,body ())))]))
  7741. (define/override (interp-program p)
  7742. (match p
  7743. [(ProgramDefsExp info ds body)
  7744. (let ([top-level (for/list ([d ds]) (interp-def d))])
  7745. (for/list ([f (in-dict-values top-level)])
  7746. (set-box! f (match (unbox f)
  7747. [`(function ,xs ,body ())
  7748. `(function ,xs ,body ,top-level)])))
  7749. ((interp-exp top-level) body))]))
  7750. ))
  7751. (define (interp-Rfun p)
  7752. (send (new interp-Rfun-class) interp-program p))
  7753. \end{lstlisting}
  7754. \caption{Interpreter for the \LangFun{} language.}
  7755. \label{fig:interp-Rfun}
  7756. \end{figure}
  7757. \margincomment{TODO: explain type checker}
  7758. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  7759. \begin{figure}[tp]
  7760. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7761. (define type-check-Rfun-class
  7762. (class type-check-Rvec-class
  7763. (super-new)
  7764. (inherit check-type-equal?)
  7765. (define/public (type-check-apply env e es)
  7766. (define-values (e^ ty) ((type-check-exp env) e))
  7767. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7768. ((type-check-exp env) e)))
  7769. (match ty
  7770. [`(,ty^* ... -> ,rt)
  7771. (for ([arg-ty ty*] [param-ty ty^*])
  7772. (check-type-equal? arg-ty param-ty (Apply e es)))
  7773. (values e^ e* rt)]))
  7774. (define/override (type-check-exp env)
  7775. (lambda (e)
  7776. (match e
  7777. [(FunRef f)
  7778. (values (FunRef f) (dict-ref env f))]
  7779. [(Apply e es)
  7780. (define-values (e^ es^ rt) (type-check-apply env e es))
  7781. (values (Apply e^ es^) rt)]
  7782. [(Call e es)
  7783. (define-values (e^ es^ rt) (type-check-apply env e es))
  7784. (values (Call e^ es^) rt)]
  7785. [else ((super type-check-exp env) e)])))
  7786. (define/public (type-check-def env)
  7787. (lambda (e)
  7788. (match e
  7789. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7790. (define new-env (append (map cons xs ps) env))
  7791. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7792. (check-type-equal? ty^ rt body)
  7793. (Def f p:t* rt info body^)])))
  7794. (define/public (fun-def-type d)
  7795. (match d
  7796. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7797. (define/override (type-check-program e)
  7798. (match e
  7799. [(ProgramDefsExp info ds body)
  7800. (define new-env (for/list ([d ds])
  7801. (cons (Def-name d) (fun-def-type d))))
  7802. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7803. (define-values (body^ ty) ((type-check-exp new-env) body))
  7804. (check-type-equal? ty 'Integer body)
  7805. (ProgramDefsExp info ds^ body^)]))))
  7806. (define (type-check-Rfun p)
  7807. (send (new type-check-Rfun-class) type-check-program p))
  7808. \end{lstlisting}
  7809. \caption{Type checker for the \LangFun{} language.}
  7810. \label{fig:type-check-Rfun}
  7811. \end{figure}
  7812. \section{Functions in x86}
  7813. \label{sec:fun-x86}
  7814. \margincomment{\tiny Make sure callee-saved registers are discussed
  7815. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7816. \margincomment{\tiny Talk about the return address on the
  7817. stack and what callq and retq does.\\ --Jeremy }
  7818. The x86 architecture provides a few features to support the
  7819. implementation of functions. We have already seen that x86 provides
  7820. labels so that one can refer to the location of an instruction, as is
  7821. needed for jump instructions. Labels can also be used to mark the
  7822. beginning of the instructions for a function. Going further, we can
  7823. obtain the address of a label by using the \key{leaq} instruction and
  7824. PC-relative addressing. For example, the following puts the
  7825. address of the \code{add1} label into the \code{rbx} register.
  7826. \begin{lstlisting}
  7827. leaq add1(%rip), %rbx
  7828. \end{lstlisting}
  7829. The instruction pointer register \key{rip} (aka. the program counter
  7830. \index{program counter}) always points to the next instruction to be
  7831. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7832. linker computes the distance $d$ between the address of \code{add1}
  7833. and where the \code{rip} would be at that moment and then changes
  7834. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7835. the address of \code{add1}.
  7836. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7837. jump to a function whose location is given by a label. To support
  7838. function calls in this chapter we instead will be jumping to a
  7839. function whose location is given by an address in a register, that is,
  7840. we need to make an \emph{indirect function call}. The x86 syntax for
  7841. this is a \code{callq} instruction but with an asterisk before the
  7842. register name.\index{indirect function call}
  7843. \begin{lstlisting}
  7844. callq *%rbx
  7845. \end{lstlisting}
  7846. \subsection{Calling Conventions}
  7847. \index{calling conventions}
  7848. The \code{callq} instruction provides partial support for implementing
  7849. functions: it pushes the return address on the stack and it jumps to
  7850. the target. However, \code{callq} does not handle
  7851. \begin{enumerate}
  7852. \item parameter passing,
  7853. \item pushing frames on the procedure call stack and popping them off,
  7854. or
  7855. \item determining how registers are shared by different functions.
  7856. \end{enumerate}
  7857. Regarding (1) parameter passing, recall that the following six
  7858. registers are used to pass arguments to a function, in this order.
  7859. \begin{lstlisting}
  7860. rdi rsi rdx rcx r8 r9
  7861. \end{lstlisting}
  7862. If there are
  7863. more than six arguments, then the convention is to use space on the
  7864. frame of the caller for the rest of the arguments. However, to ease
  7865. the implementation of efficient tail calls
  7866. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7867. arguments.
  7868. %
  7869. Also recall that the register \code{rax} is for the return value of
  7870. the function.
  7871. \index{prelude}\index{conclusion}
  7872. Regarding (2) frames \index{frame} and the procedure call stack,
  7873. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7874. the stack grows down, with each function call using a chunk of space
  7875. called a frame. The caller sets the stack pointer, register
  7876. \code{rsp}, to the last data item in its frame. The callee must not
  7877. change anything in the caller's frame, that is, anything that is at or
  7878. above the stack pointer. The callee is free to use locations that are
  7879. below the stack pointer.
  7880. Recall that we are storing variables of vector type on the root stack.
  7881. So the prelude needs to move the root stack pointer \code{r15} up and
  7882. the conclusion needs to move the root stack pointer back down. Also,
  7883. the prelude must initialize to \code{0} this frame's slots in the root
  7884. stack to signal to the garbage collector that those slots do not yet
  7885. contain a pointer to a vector. Otherwise the garbage collector will
  7886. interpret the garbage bits in those slots as memory addresses and try
  7887. to traverse them, causing serious mayhem!
  7888. Regarding (3) the sharing of registers between different functions,
  7889. recall from Section~\ref{sec:calling-conventions} that the registers
  7890. are divided into two groups, the caller-saved registers and the
  7891. callee-saved registers. The caller should assume that all the
  7892. caller-saved registers get overwritten with arbitrary values by the
  7893. callee. That is why we recommend in
  7894. Section~\ref{sec:calling-conventions} that variables that are live
  7895. during a function call should not be assigned to caller-saved
  7896. registers.
  7897. On the flip side, if the callee wants to use a callee-saved register,
  7898. the callee must save the contents of those registers on their stack
  7899. frame and then put them back prior to returning to the caller. That
  7900. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7901. the register allocator assigns a variable to a callee-saved register,
  7902. then the prelude of the \code{main} function must save that register
  7903. to the stack and the conclusion of \code{main} must restore it. This
  7904. recommendation now generalizes to all functions.
  7905. Also recall that the base pointer, register \code{rbp}, is used as a
  7906. point-of-reference within a frame, so that each local variable can be
  7907. accessed at a fixed offset from the base pointer
  7908. (Section~\ref{sec:x86}).
  7909. %
  7910. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7911. and callee frames.
  7912. \begin{figure}[tbp]
  7913. \centering
  7914. \begin{tabular}{r|r|l|l} \hline
  7915. Caller View & Callee View & Contents & Frame \\ \hline
  7916. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7917. 0(\key{\%rbp}) & & old \key{rbp} \\
  7918. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7919. \ldots & & \ldots \\
  7920. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7921. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7922. \ldots & & \ldots \\
  7923. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7924. %% & & \\
  7925. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7926. %% & \ldots & \ldots \\
  7927. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7928. \hline
  7929. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7930. & 0(\key{\%rbp}) & old \key{rbp} \\
  7931. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7932. & \ldots & \ldots \\
  7933. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7934. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7935. & \ldots & \ldots \\
  7936. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7937. \end{tabular}
  7938. \caption{Memory layout of caller and callee frames.}
  7939. \label{fig:call-frames}
  7940. \end{figure}
  7941. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7942. %% local variables and for storing the values of callee-saved registers
  7943. %% (we shall refer to all of these collectively as ``locals''), and that
  7944. %% at the beginning of a function we move the stack pointer \code{rsp}
  7945. %% down to make room for them.
  7946. %% We recommend storing the local variables
  7947. %% first and then the callee-saved registers, so that the local variables
  7948. %% can be accessed using \code{rbp} the same as before the addition of
  7949. %% functions.
  7950. %% To make additional room for passing arguments, we shall
  7951. %% move the stack pointer even further down. We count how many stack
  7952. %% arguments are needed for each function call that occurs inside the
  7953. %% body of the function and find their maximum. Adding this number to the
  7954. %% number of locals gives us how much the \code{rsp} should be moved at
  7955. %% the beginning of the function. In preparation for a function call, we
  7956. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7957. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7958. %% so on.
  7959. %% Upon calling the function, the stack arguments are retrieved by the
  7960. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7961. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7962. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7963. %% the layout of the caller and callee frames. Notice how important it is
  7964. %% that we correctly compute the maximum number of arguments needed for
  7965. %% function calls; if that number is too small then the arguments and
  7966. %% local variables will smash into each other!
  7967. \subsection{Efficient Tail Calls}
  7968. \label{sec:tail-call}
  7969. In general, the amount of stack space used by a program is determined
  7970. by the longest chain of nested function calls. That is, if function
  7971. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7972. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7973. $n$ can grow quite large in the case of recursive or mutually
  7974. recursive functions. However, in some cases we can arrange to use only
  7975. constant space, i.e. $O(1)$, instead of $O(n)$.
  7976. If a function call is the last action in a function body, then that
  7977. call is said to be a \emph{tail call}\index{tail call}.
  7978. For example, in the following
  7979. program, the recursive call to \code{tail-sum} is a tail call.
  7980. \begin{center}
  7981. \begin{lstlisting}
  7982. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7983. (if (eq? n 0)
  7984. r
  7985. (tail-sum (- n 1) (+ n r))))
  7986. (+ (tail-sum 5 0) 27)
  7987. \end{lstlisting}
  7988. \end{center}
  7989. At a tail call, the frame of the caller is no longer needed, so we
  7990. can pop the caller's frame before making the tail call. With this
  7991. approach, a recursive function that only makes tail calls will only
  7992. use $O(1)$ stack space. Functional languages like Racket typically
  7993. rely heavily on recursive functions, so they typically guarantee that
  7994. all tail calls will be optimized in this way.
  7995. \index{frame}
  7996. However, some care is needed with regards to argument passing in tail
  7997. calls. As mentioned above, for arguments beyond the sixth, the
  7998. convention is to use space in the caller's frame for passing
  7999. arguments. But for a tail call we pop the caller's frame and can no
  8000. longer use it. Another alternative is to use space in the callee's
  8001. frame for passing arguments. However, this option is also problematic
  8002. because the caller and callee's frame overlap in memory. As we begin
  8003. to copy the arguments from their sources in the caller's frame, the
  8004. target locations in the callee's frame might overlap with the sources
  8005. for later arguments! We solve this problem by not using the stack for
  8006. passing more than six arguments but instead using the heap, as we
  8007. describe in the Section~\ref{sec:limit-functions-r4}.
  8008. As mentioned above, for a tail call we pop the caller's frame prior to
  8009. making the tail call. The instructions for popping a frame are the
  8010. instructions that we usually place in the conclusion of a
  8011. function. Thus, we also need to place such code immediately before
  8012. each tail call. These instructions include restoring the callee-saved
  8013. registers, so it is good that the argument passing registers are all
  8014. caller-saved registers.
  8015. One last note regarding which instruction to use to make the tail
  8016. call. When the callee is finished, it should not return to the current
  8017. function, but it should return to the function that called the current
  8018. one. Thus, the return address that is already on the stack is the
  8019. right one, and we should not use \key{callq} to make the tail call, as
  8020. that would unnecessarily overwrite the return address. Instead we can
  8021. simply use the \key{jmp} instruction. Like the indirect function call,
  8022. we write an \emph{indirect jump}\index{indirect jump} with a register
  8023. prefixed with an asterisk. We recommend using \code{rax} to hold the
  8024. jump target because the preceding conclusion overwrites just about
  8025. everything else.
  8026. \begin{lstlisting}
  8027. jmp *%rax
  8028. \end{lstlisting}
  8029. \section{Shrink \LangFun{}}
  8030. \label{sec:shrink-r4}
  8031. The \code{shrink} pass performs a minor modification to ease the
  8032. later passes. This pass introduces an explicit \code{main} function
  8033. and changes the top \code{ProgramDefsExp} form to
  8034. \code{ProgramDefs} as follows.
  8035. \begin{lstlisting}
  8036. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  8037. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  8038. \end{lstlisting}
  8039. where $\itm{mainDef}$ is
  8040. \begin{lstlisting}
  8041. (Def 'main '() 'Integer '() |$\Exp'$|)
  8042. \end{lstlisting}
  8043. \section{Reveal Functions and the \LangFunRef{} language}
  8044. \label{sec:reveal-functions-r4}
  8045. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  8046. respect: it conflates the use of function names and local
  8047. variables. This is a problem because we need to compile the use of a
  8048. function name differently than the use of a local variable; we need to
  8049. use \code{leaq} to convert the function name (a label in x86) to an
  8050. address in a register. Thus, it is a good idea to create a new pass
  8051. that changes function references from just a symbol $f$ to
  8052. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  8053. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  8054. The concrete syntax for a function reference is $\CFUNREF{f}$.
  8055. \begin{figure}[tp]
  8056. \centering
  8057. \fbox{
  8058. \begin{minipage}{0.96\textwidth}
  8059. \[
  8060. \begin{array}{lcl}
  8061. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  8062. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8063. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  8064. \end{array}
  8065. \]
  8066. \end{minipage}
  8067. }
  8068. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  8069. (Figure~\ref{fig:Rfun-syntax}).}
  8070. \label{fig:f1-syntax}
  8071. \end{figure}
  8072. %% Distinguishing between calls in tail position and non-tail position
  8073. %% requires the pass to have some notion of context. We recommend using
  8074. %% two mutually recursive functions, one for processing expressions in
  8075. %% tail position and another for the rest.
  8076. Placing this pass after \code{uniquify} will make sure that there are
  8077. no local variables and functions that share the same name. On the
  8078. other hand, \code{reveal-functions} needs to come before the
  8079. \code{explicate-control} pass because that pass helps us compile
  8080. \code{FunRef} forms into assignment statements.
  8081. \section{Limit Functions}
  8082. \label{sec:limit-functions-r4}
  8083. Recall that we wish to limit the number of function parameters to six
  8084. so that we do not need to use the stack for argument passing, which
  8085. makes it easier to implement efficient tail calls. However, because
  8086. the input language \LangFun{} supports arbitrary numbers of function
  8087. arguments, we have some work to do!
  8088. This pass transforms functions and function calls that involve more
  8089. than six arguments to pass the first five arguments as usual, but it
  8090. packs the rest of the arguments into a vector and passes it as the
  8091. sixth argument.
  8092. Each function definition with too many parameters is transformed as
  8093. follows.
  8094. \begin{lstlisting}
  8095. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  8096. |$\Rightarrow$|
  8097. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  8098. \end{lstlisting}
  8099. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  8100. the occurrences of the later parameters with vector references.
  8101. \begin{lstlisting}
  8102. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  8103. \end{lstlisting}
  8104. For function calls with too many arguments, the \code{limit-functions}
  8105. pass transforms them in the following way.
  8106. \begin{tabular}{lll}
  8107. \begin{minipage}{0.2\textwidth}
  8108. \begin{lstlisting}
  8109. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  8110. \end{lstlisting}
  8111. \end{minipage}
  8112. &
  8113. $\Rightarrow$
  8114. &
  8115. \begin{minipage}{0.4\textwidth}
  8116. \begin{lstlisting}
  8117. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  8118. \end{lstlisting}
  8119. \end{minipage}
  8120. \end{tabular}
  8121. \section{Remove Complex Operands}
  8122. \label{sec:rco-r4}
  8123. The primary decisions to make for this pass is whether to classify
  8124. \code{FunRef} and \code{Apply} as either atomic or complex
  8125. expressions. Recall that a simple expression will eventually end up as
  8126. just an immediate argument of an x86 instruction. Function
  8127. application will be translated to a sequence of instructions, so
  8128. \code{Apply} must be classified as complex expression.
  8129. On the other hand, the arguments of \code{Apply} should be
  8130. atomic expressions.
  8131. %
  8132. Regarding \code{FunRef}, as discussed above, the function label needs
  8133. to be converted to an address using the \code{leaq} instruction. Thus,
  8134. even though \code{FunRef} seems rather simple, it needs to be
  8135. classified as a complex expression so that we generate an assignment
  8136. statement with a left-hand side that can serve as the target of the
  8137. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  8138. output language \LangFunANF{} of this pass.
  8139. \begin{figure}[tp]
  8140. \centering
  8141. \fbox{
  8142. \begin{minipage}{0.96\textwidth}
  8143. \small
  8144. \[
  8145. \begin{array}{rcl}
  8146. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  8147. \mid \VOID{} } \\
  8148. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  8149. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  8150. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8151. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  8152. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  8153. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  8154. \mid \LP\key{GlobalValue}~\Var\RP }\\
  8155. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  8156. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8157. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8158. \end{array}
  8159. \]
  8160. \end{minipage}
  8161. }
  8162. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  8163. \label{fig:Rfun-anf-syntax}
  8164. \end{figure}
  8165. \section{Explicate Control and the \LangCFun{} language}
  8166. \label{sec:explicate-control-r4}
  8167. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  8168. output of \key{explicate-control}. (The concrete syntax is given in
  8169. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  8170. functions for assignment and tail contexts should be updated with
  8171. cases for \code{Apply} and \code{FunRef} and the function for
  8172. predicate context should be updated for \code{Apply} but not
  8173. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  8174. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  8175. tail position \code{Apply} becomes \code{TailCall}. We recommend
  8176. defining a new auxiliary function for processing function definitions.
  8177. This code is similar to the case for \code{Program} in \LangVec{}. The
  8178. top-level \code{explicate-control} function that handles the
  8179. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  8180. all the function definitions.
  8181. \begin{figure}[tp]
  8182. \fbox{
  8183. \begin{minipage}{0.96\textwidth}
  8184. \small
  8185. \[
  8186. \begin{array}{lcl}
  8187. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  8188. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  8189. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  8190. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  8191. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  8192. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  8193. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  8194. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  8195. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  8196. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  8197. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8198. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8199. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8200. \mid \GOTO{\itm{label}} } \\
  8201. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8202. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  8203. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  8204. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8205. \end{array}
  8206. \]
  8207. \end{minipage}
  8208. }
  8209. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  8210. \label{fig:c3-syntax}
  8211. \end{figure}
  8212. \section{Select Instructions and the \LangXIndCall{} Language}
  8213. \label{sec:select-r4}
  8214. \index{instruction selection}
  8215. The output of select instructions is a program in the \LangXIndCall{}
  8216. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  8217. \index{x86}
  8218. \begin{figure}[tp]
  8219. \fbox{
  8220. \begin{minipage}{0.96\textwidth}
  8221. \small
  8222. \[
  8223. \begin{array}{lcl}
  8224. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  8225. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  8226. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  8227. \Instr &::=& \ldots
  8228. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  8229. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  8230. \Block &::= & \Instr\ldots \\
  8231. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  8232. \LangXIndCall{} &::= & \Def\ldots
  8233. \end{array}
  8234. \]
  8235. \end{minipage}
  8236. }
  8237. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  8238. \label{fig:x86-3-concrete}
  8239. \end{figure}
  8240. \begin{figure}[tp]
  8241. \fbox{
  8242. \begin{minipage}{0.96\textwidth}
  8243. \small
  8244. \[
  8245. \begin{array}{lcl}
  8246. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  8247. \mid \BYTEREG{\Reg} } \\
  8248. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  8249. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  8250. \mid \TAILJMP{\Arg}{\itm{int}}\\
  8251. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  8252. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  8253. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  8254. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8255. \end{array}
  8256. \]
  8257. \end{minipage}
  8258. }
  8259. \caption{The abstract syntax of \LangXIndCall{} (extends
  8260. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  8261. \label{fig:x86-3}
  8262. \end{figure}
  8263. An assignment of a function reference to a variable becomes a
  8264. load-effective-address instruction as follows: \\
  8265. \begin{tabular}{lcl}
  8266. \begin{minipage}{0.35\textwidth}
  8267. \begin{lstlisting}
  8268. |$\itm{lhs}$| = (fun-ref |$f$|);
  8269. \end{lstlisting}
  8270. \end{minipage}
  8271. &
  8272. $\Rightarrow$\qquad\qquad
  8273. &
  8274. \begin{minipage}{0.3\textwidth}
  8275. \begin{lstlisting}
  8276. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  8277. \end{lstlisting}
  8278. \end{minipage}
  8279. \end{tabular} \\
  8280. Regarding function definitions, we need to remove the parameters and
  8281. instead perform parameter passing using the conventions discussed in
  8282. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  8283. registers. We recommend turning the parameters into local variables
  8284. and generating instructions at the beginning of the function to move
  8285. from the argument passing registers to these local variables.
  8286. \begin{lstlisting}
  8287. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  8288. |$\Rightarrow$|
  8289. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  8290. \end{lstlisting}
  8291. The $G'$ control-flow graph is the same as $G$ except that the
  8292. \code{start} block is modified to add the instructions for moving from
  8293. the argument registers to the parameter variables. So the \code{start}
  8294. block of $G$ shown on the left is changed to the code on the right.
  8295. \begin{center}
  8296. \begin{minipage}{0.3\textwidth}
  8297. \begin{lstlisting}
  8298. start:
  8299. |$\itm{instr}_1$|
  8300. |$\vdots$|
  8301. |$\itm{instr}_n$|
  8302. \end{lstlisting}
  8303. \end{minipage}
  8304. $\Rightarrow$
  8305. \begin{minipage}{0.3\textwidth}
  8306. \begin{lstlisting}
  8307. start:
  8308. movq %rdi, |$x_1$|
  8309. movq %rsi, |$x_2$|
  8310. |$\vdots$|
  8311. |$\itm{instr}_1$|
  8312. |$\vdots$|
  8313. |$\itm{instr}_n$|
  8314. \end{lstlisting}
  8315. \end{minipage}
  8316. \end{center}
  8317. By changing the parameters to local variables, we are giving the
  8318. register allocator control over which registers or stack locations to
  8319. use for them. If you implemented the move-biasing challenge
  8320. (Section~\ref{sec:move-biasing}), the register allocator will try to
  8321. assign the parameter variables to the corresponding argument register,
  8322. in which case the \code{patch-instructions} pass will remove the
  8323. \code{movq} instruction. This happens in the example translation in
  8324. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  8325. the \code{add} function.
  8326. %
  8327. Also, note that the register allocator will perform liveness analysis
  8328. on this sequence of move instructions and build the interference
  8329. graph. So, for example, $x_1$ will be marked as interfering with
  8330. \code{rsi} and that will prevent the assignment of $x_1$ to
  8331. \code{rsi}, which is good, because that would overwrite the argument
  8332. that needs to move into $x_2$.
  8333. Next, consider the compilation of function calls. In the mirror image
  8334. of handling the parameters of function definitions, the arguments need
  8335. to be moved to the argument passing registers. The function call
  8336. itself is performed with an indirect function call. The return value
  8337. from the function is stored in \code{rax}, so it needs to be moved
  8338. into the \itm{lhs}.
  8339. \begin{lstlisting}
  8340. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  8341. |$\Rightarrow$|
  8342. movq |$\itm{arg}_1$|, %rdi
  8343. movq |$\itm{arg}_2$|, %rsi
  8344. |$\vdots$|
  8345. callq *|\itm{fun}|
  8346. movq %rax, |\itm{lhs}|
  8347. \end{lstlisting}
  8348. The \code{IndirectCallq} AST node includes an integer for the arity of
  8349. the function, i.e., the number of parameters. That information is
  8350. useful in the \code{uncover-live} pass for determining which
  8351. argument-passing registers are potentially read during the call.
  8352. For tail calls, the parameter passing is the same as non-tail calls:
  8353. generate instructions to move the arguments into to the argument
  8354. passing registers. After that we need to pop the frame from the
  8355. procedure call stack. However, we do not yet know how big the frame
  8356. is; that gets determined during register allocation. So instead of
  8357. generating those instructions here, we invent a new instruction that
  8358. means ``pop the frame and then do an indirect jump'', which we name
  8359. \code{TailJmp}. The abstract syntax for this instruction includes an
  8360. argument that specifies where to jump and an integer that represents
  8361. the arity of the function being called.
  8362. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  8363. using the label \code{start} for the initial block of a program, and
  8364. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  8365. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  8366. can be compiled to an assignment to \code{rax} followed by a jump to
  8367. \code{conclusion}. With the addition of function definitions, we will
  8368. have a starting block and conclusion for each function, but their
  8369. labels need to be unique. We recommend prepending the function's name
  8370. to \code{start} and \code{conclusion}, respectively, to obtain unique
  8371. labels. (Alternatively, one could \code{gensym} labels for the start
  8372. and conclusion and store them in the $\itm{info}$ field of the
  8373. function definition.)
  8374. \section{Register Allocation}
  8375. \label{sec:register-allocation-r4}
  8376. \subsection{Liveness Analysis}
  8377. \label{sec:liveness-analysis-r4}
  8378. \index{liveness analysis}
  8379. %% The rest of the passes need only minor modifications to handle the new
  8380. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  8381. %% \code{leaq}.
  8382. The \code{IndirectCallq} instruction should be treated like
  8383. \code{Callq} regarding its written locations $W$, in that they should
  8384. include all the caller-saved registers. Recall that the reason for
  8385. that is to force call-live variables to be assigned to callee-saved
  8386. registers or to be spilled to the stack.
  8387. Regarding the set of read locations $R$ the arity field of
  8388. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  8389. argument-passing registers should be considered as read by those
  8390. instructions.
  8391. \subsection{Build Interference Graph}
  8392. \label{sec:build-interference-r4}
  8393. With the addition of function definitions, we compute an interference
  8394. graph for each function (not just one for the whole program).
  8395. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  8396. spill vector-typed variables that are live during a call to the
  8397. \code{collect}. With the addition of functions to our language, we
  8398. need to revisit this issue. Many functions perform allocation and
  8399. therefore have calls to the collector inside of them. Thus, we should
  8400. not only spill a vector-typed variable when it is live during a call
  8401. to \code{collect}, but we should spill the variable if it is live
  8402. during any function call. Thus, in the \code{build-interference} pass,
  8403. we recommend adding interference edges between call-live vector-typed
  8404. variables and the callee-saved registers (in addition to the usual
  8405. addition of edges between call-live variables and the caller-saved
  8406. registers).
  8407. \subsection{Allocate Registers}
  8408. The primary change to the \code{allocate-registers} pass is adding an
  8409. auxiliary function for handling definitions (the \Def{} non-terminal
  8410. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  8411. logic is the same as described in
  8412. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  8413. allocation is performed many times, once for each function definition,
  8414. instead of just once for the whole program.
  8415. \section{Patch Instructions}
  8416. In \code{patch-instructions}, you should deal with the x86
  8417. idiosyncrasy that the destination argument of \code{leaq} must be a
  8418. register. Additionally, you should ensure that the argument of
  8419. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  8420. code generation more convenient, because we trample many registers
  8421. before the tail call (as explained in the next section).
  8422. \section{Print x86}
  8423. For the \code{print-x86} pass, the cases for \code{FunRef} and
  8424. \code{IndirectCallq} are straightforward: output their concrete
  8425. syntax.
  8426. \begin{lstlisting}
  8427. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  8428. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  8429. \end{lstlisting}
  8430. The \code{TailJmp} node requires a bit work. A straightforward
  8431. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  8432. before the jump we need to pop the current frame. This sequence of
  8433. instructions is the same as the code for the conclusion of a function,
  8434. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  8435. Regarding function definitions, you will need to generate a prelude
  8436. and conclusion for each one. This code is similar to the prelude and
  8437. conclusion that you generated for the \code{main} function in
  8438. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  8439. should carry out the following steps.
  8440. \begin{enumerate}
  8441. \item Start with \code{.global} and \code{.align} directives followed
  8442. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  8443. example.)
  8444. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  8445. pointer.
  8446. \item Push to the stack all of the callee-saved registers that were
  8447. used for register allocation.
  8448. \item Move the stack pointer \code{rsp} down by the size of the stack
  8449. frame for this function, which depends on the number of regular
  8450. spills. (Aligned to 16 bytes.)
  8451. \item Move the root stack pointer \code{r15} up by the size of the
  8452. root-stack frame for this function, which depends on the number of
  8453. spilled vectors. \label{root-stack-init}
  8454. \item Initialize to zero all of the entries in the root-stack frame.
  8455. \item Jump to the start block.
  8456. \end{enumerate}
  8457. The prelude of the \code{main} function has one additional task: call
  8458. the \code{initialize} function to set up the garbage collector and
  8459. move the value of the global \code{rootstack\_begin} in
  8460. \code{r15}. This should happen before step \ref{root-stack-init}
  8461. above, which depends on \code{r15}.
  8462. The conclusion of every function should do the following.
  8463. \begin{enumerate}
  8464. \item Move the stack pointer back up by the size of the stack frame
  8465. for this function.
  8466. \item Restore the callee-saved registers by popping them from the
  8467. stack.
  8468. \item Move the root stack pointer back down by the size of the
  8469. root-stack frame for this function.
  8470. \item Restore \code{rbp} by popping it from the stack.
  8471. \item Return to the caller with the \code{retq} instruction.
  8472. \end{enumerate}
  8473. \begin{exercise}\normalfont
  8474. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  8475. Create 5 new programs that use functions, including examples that pass
  8476. functions and return functions from other functions, recursive
  8477. functions, functions that create vectors, and functions that make tail
  8478. calls. Test your compiler on these new programs and all of your
  8479. previously created test programs.
  8480. \end{exercise}
  8481. \begin{figure}[tbp]
  8482. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8483. \node (Rfun) at (0,2) {\large \LangFun{}};
  8484. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  8485. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  8486. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8487. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8488. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  8489. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  8490. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8491. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8492. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8493. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8494. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8495. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8496. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8497. \path[->,bend left=15] (Rfun) edge [above] node
  8498. {\ttfamily\footnotesize shrink} (Rfun-1);
  8499. \path[->,bend left=15] (Rfun-1) edge [above] node
  8500. {\ttfamily\footnotesize uniquify} (Rfun-2);
  8501. \path[->,bend left=15] (Rfun-2) edge [right] node
  8502. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  8503. \path[->,bend left=15] (F1-1) edge [below] node
  8504. {\ttfamily\footnotesize limit-functions} (F1-2);
  8505. \path[->,bend right=15] (F1-2) edge [above] node
  8506. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  8507. \path[->,bend right=15] (F1-3) edge [above] node
  8508. {\ttfamily\footnotesize remove-complex.} (F1-4);
  8509. \path[->,bend left=15] (F1-4) edge [right] node
  8510. {\ttfamily\footnotesize explicate-control} (C3-2);
  8511. \path[->,bend right=15] (C3-2) edge [left] node
  8512. {\ttfamily\footnotesize select-instr.} (x86-2);
  8513. \path[->,bend left=15] (x86-2) edge [left] node
  8514. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8515. \path[->,bend right=15] (x86-2-1) edge [below] node
  8516. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8517. \path[->,bend right=15] (x86-2-2) edge [left] node
  8518. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8519. \path[->,bend left=15] (x86-3) edge [above] node
  8520. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8521. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  8522. \end{tikzpicture}
  8523. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  8524. \label{fig:Rfun-passes}
  8525. \end{figure}
  8526. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  8527. compiling \LangFun{} to x86.
  8528. \section{An Example Translation}
  8529. \label{sec:functions-example}
  8530. Figure~\ref{fig:add-fun} shows an example translation of a simple
  8531. function in \LangFun{} to x86. The figure also includes the results of the
  8532. \code{explicate-control} and \code{select-instructions} passes.
  8533. \begin{figure}[htbp]
  8534. \begin{tabular}{ll}
  8535. \begin{minipage}{0.5\textwidth}
  8536. % s3_2.rkt
  8537. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8538. (define (add [x : Integer] [y : Integer])
  8539. : Integer
  8540. (+ x y))
  8541. (add 40 2)
  8542. \end{lstlisting}
  8543. $\Downarrow$
  8544. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8545. (define (add86 [x87 : Integer]
  8546. [y88 : Integer]) : Integer
  8547. add86start:
  8548. return (+ x87 y88);
  8549. )
  8550. (define (main) : Integer ()
  8551. mainstart:
  8552. tmp89 = (fun-ref add86);
  8553. (tail-call tmp89 40 2)
  8554. )
  8555. \end{lstlisting}
  8556. \end{minipage}
  8557. &
  8558. $\Rightarrow$
  8559. \begin{minipage}{0.5\textwidth}
  8560. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8561. (define (add86) : Integer
  8562. add86start:
  8563. movq %rdi, x87
  8564. movq %rsi, y88
  8565. movq x87, %rax
  8566. addq y88, %rax
  8567. jmp add11389conclusion
  8568. )
  8569. (define (main) : Integer
  8570. mainstart:
  8571. leaq (fun-ref add86), tmp89
  8572. movq $40, %rdi
  8573. movq $2, %rsi
  8574. tail-jmp tmp89
  8575. )
  8576. \end{lstlisting}
  8577. $\Downarrow$
  8578. \end{minipage}
  8579. \end{tabular}
  8580. \begin{tabular}{ll}
  8581. \begin{minipage}{0.3\textwidth}
  8582. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8583. .globl add86
  8584. .align 16
  8585. add86:
  8586. pushq %rbp
  8587. movq %rsp, %rbp
  8588. jmp add86start
  8589. add86start:
  8590. movq %rdi, %rax
  8591. addq %rsi, %rax
  8592. jmp add86conclusion
  8593. add86conclusion:
  8594. popq %rbp
  8595. retq
  8596. \end{lstlisting}
  8597. \end{minipage}
  8598. &
  8599. \begin{minipage}{0.5\textwidth}
  8600. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8601. .globl main
  8602. .align 16
  8603. main:
  8604. pushq %rbp
  8605. movq %rsp, %rbp
  8606. movq $16384, %rdi
  8607. movq $16384, %rsi
  8608. callq initialize
  8609. movq rootstack_begin(%rip), %r15
  8610. jmp mainstart
  8611. mainstart:
  8612. leaq add86(%rip), %rcx
  8613. movq $40, %rdi
  8614. movq $2, %rsi
  8615. movq %rcx, %rax
  8616. popq %rbp
  8617. jmp *%rax
  8618. mainconclusion:
  8619. popq %rbp
  8620. retq
  8621. \end{lstlisting}
  8622. \end{minipage}
  8623. \end{tabular}
  8624. \caption{Example compilation of a simple function to x86.}
  8625. \label{fig:add-fun}
  8626. \end{figure}
  8627. % Challenge idea: inlining! (simple version)
  8628. % Further Reading
  8629. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8630. \chapter{Lexically Scoped Functions}
  8631. \label{ch:Rlam}
  8632. \index{lambda}
  8633. \index{lexical scoping}
  8634. This chapter studies lexically scoped functions as they appear in
  8635. functional languages such as Racket. By lexical scoping we mean that a
  8636. function's body may refer to variables whose binding site is outside
  8637. of the function, in an enclosing scope.
  8638. %
  8639. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  8640. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  8641. \key{lambda} form. The body of the \key{lambda}, refers to three
  8642. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  8643. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  8644. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  8645. parameter of function \code{f}. The \key{lambda} is returned from the
  8646. function \code{f}. The main expression of the program includes two
  8647. calls to \code{f} with different arguments for \code{x}, first
  8648. \code{5} then \code{3}. The functions returned from \code{f} are bound
  8649. to variables \code{g} and \code{h}. Even though these two functions
  8650. were created by the same \code{lambda}, they are really different
  8651. functions because they use different values for \code{x}. Applying
  8652. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  8653. \code{15} produces \code{22}. The result of this program is \code{42}.
  8654. \begin{figure}[btp]
  8655. % s4_6.rkt
  8656. \begin{lstlisting}
  8657. (define (f [x : Integer]) : (Integer -> Integer)
  8658. (let ([y 4])
  8659. (lambda: ([z : Integer]) : Integer
  8660. (+ x (+ y z)))))
  8661. (let ([g (f 5)])
  8662. (let ([h (f 3)])
  8663. (+ (g 11) (h 15))))
  8664. \end{lstlisting}
  8665. \caption{Example of a lexically scoped function.}
  8666. \label{fig:lexical-scoping}
  8667. \end{figure}
  8668. The approach that we take for implementing lexically scoped
  8669. functions is to compile them into top-level function definitions,
  8670. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  8671. provide special treatment for variable occurrences such as \code{x}
  8672. and \code{y} in the body of the \code{lambda} of
  8673. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  8674. refer to variables defined outside of it. To identify such variable
  8675. occurrences, we review the standard notion of free variable.
  8676. \begin{definition}
  8677. A variable is \emph{free in expression} $e$ if the variable occurs
  8678. inside $e$ but does not have an enclosing binding in $e$.\index{free
  8679. variable}
  8680. \end{definition}
  8681. For example, in the expression \code{(+ x (+ y z))} the variables
  8682. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  8683. only \code{x} and \code{y} are free in the following expression
  8684. because \code{z} is bound by the \code{lambda}.
  8685. \begin{lstlisting}
  8686. (lambda: ([z : Integer]) : Integer
  8687. (+ x (+ y z)))
  8688. \end{lstlisting}
  8689. So the free variables of a \code{lambda} are the ones that will need
  8690. special treatment. We need to arrange for some way to transport, at
  8691. runtime, the values of those variables from the point where the
  8692. \code{lambda} was created to the point where the \code{lambda} is
  8693. applied. An efficient solution to the problem, due to
  8694. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  8695. free variables together with the function pointer for the lambda's
  8696. code, an arrangement called a \emph{flat closure} (which we shorten to
  8697. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  8698. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  8699. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  8700. pointers. The function pointer resides at index $0$ and the
  8701. values for the free variables will fill in the rest of the vector.
  8702. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  8703. how closures work. It's a three-step dance. The program first calls
  8704. function \code{f}, which creates a closure for the \code{lambda}. The
  8705. closure is a vector whose first element is a pointer to the top-level
  8706. function that we will generate for the \code{lambda}, the second
  8707. element is the value of \code{x}, which is \code{5}, and the third
  8708. element is \code{4}, the value of \code{y}. The closure does not
  8709. contain an element for \code{z} because \code{z} is not a free
  8710. variable of the \code{lambda}. Creating the closure is step 1 of the
  8711. dance. The closure is returned from \code{f} and bound to \code{g}, as
  8712. shown in Figure~\ref{fig:closures}.
  8713. %
  8714. The second call to \code{f} creates another closure, this time with
  8715. \code{3} in the second slot (for \code{x}). This closure is also
  8716. returned from \code{f} but bound to \code{h}, which is also shown in
  8717. Figure~\ref{fig:closures}.
  8718. \begin{figure}[tbp]
  8719. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  8720. \caption{Example closure representation for the \key{lambda}'s
  8721. in Figure~\ref{fig:lexical-scoping}.}
  8722. \label{fig:closures}
  8723. \end{figure}
  8724. Continuing with the example, consider the application of \code{g} to
  8725. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  8726. obtain the function pointer in the first element of the closure and
  8727. call it, passing in the closure itself and then the regular arguments,
  8728. in this case \code{11}. This technique for applying a closure is step
  8729. 2 of the dance.
  8730. %
  8731. But doesn't this \code{lambda} only take 1 argument, for parameter
  8732. \code{z}? The third and final step of the dance is generating a
  8733. top-level function for a \code{lambda}. We add an additional
  8734. parameter for the closure and we insert a \code{let} at the beginning
  8735. of the function for each free variable, to bind those variables to the
  8736. appropriate elements from the closure parameter.
  8737. %
  8738. This three-step dance is known as \emph{closure conversion}. We
  8739. discuss the details of closure conversion in
  8740. Section~\ref{sec:closure-conversion} and the code generated from the
  8741. example in Section~\ref{sec:example-lambda}. But first we define the
  8742. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  8743. \section{The \LangLam{} Language}
  8744. \label{sec:r5}
  8745. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8746. functions and lexical scoping, is defined in
  8747. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8748. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8749. syntax for function application.
  8750. \begin{figure}[tp]
  8751. \centering
  8752. \fbox{
  8753. \begin{minipage}{0.96\textwidth}
  8754. \small
  8755. \[
  8756. \begin{array}{lcl}
  8757. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  8758. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  8759. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  8760. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8761. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8762. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8763. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8764. \mid (\key{and}\;\Exp\;\Exp)
  8765. \mid (\key{or}\;\Exp\;\Exp)
  8766. \mid (\key{not}\;\Exp) } \\
  8767. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8768. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8769. (\key{vector-ref}\;\Exp\;\Int)} \\
  8770. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8771. \mid (\Exp \; \Exp\ldots) } \\
  8772. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8773. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8774. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8775. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8776. \end{array}
  8777. \]
  8778. \end{minipage}
  8779. }
  8780. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8781. with \key{lambda}.}
  8782. \label{fig:Rlam-concrete-syntax}
  8783. \end{figure}
  8784. \begin{figure}[tp]
  8785. \centering
  8786. \fbox{
  8787. \begin{minipage}{0.96\textwidth}
  8788. \small
  8789. \[
  8790. \begin{array}{lcl}
  8791. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8792. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8793. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8794. &\mid& \gray{ \BOOL{\itm{bool}}
  8795. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8796. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8797. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8798. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8799. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8800. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8801. \end{array}
  8802. \]
  8803. \end{minipage}
  8804. }
  8805. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8806. \label{fig:Rlam-syntax}
  8807. \end{figure}
  8808. \index{interpreter}
  8809. \label{sec:interp-Rlambda}
  8810. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8811. \LangLam{}. The case for \key{lambda} saves the current environment
  8812. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8813. the environment from the \key{lambda}, the \code{lam-env}, when
  8814. interpreting the body of the \key{lambda}. The \code{lam-env}
  8815. environment is extended with the mapping of parameters to argument
  8816. values.
  8817. \begin{figure}[tbp]
  8818. \begin{lstlisting}
  8819. (define interp-Rlambda-class
  8820. (class interp-Rfun-class
  8821. (super-new)
  8822. (define/override (interp-op op)
  8823. (match op
  8824. ['procedure-arity
  8825. (lambda (v)
  8826. (match v
  8827. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8828. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8829. [else (super interp-op op)]))
  8830. (define/override ((interp-exp env) e)
  8831. (define recur (interp-exp env))
  8832. (match e
  8833. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8834. `(function ,xs ,body ,env)]
  8835. [else ((super interp-exp env) e)]))
  8836. ))
  8837. (define (interp-Rlambda p)
  8838. (send (new interp-Rlambda-class) interp-program p))
  8839. \end{lstlisting}
  8840. \caption{Interpreter for \LangLam{}.}
  8841. \label{fig:interp-Rlambda}
  8842. \end{figure}
  8843. \label{sec:type-check-r5}
  8844. \index{type checking}
  8845. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8846. \key{lambda} form. The body of the \key{lambda} is checked in an
  8847. environment that includes the current environment (because it is
  8848. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8849. require the body's type to match the declared return type.
  8850. \begin{figure}[tbp]
  8851. \begin{lstlisting}
  8852. (define (type-check-Rlambda env)
  8853. (lambda (e)
  8854. (match e
  8855. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8856. (define-values (new-body bodyT)
  8857. ((type-check-exp (append (map cons xs Ts) env)) body))
  8858. (define ty `(,@Ts -> ,rT))
  8859. (cond
  8860. [(equal? rT bodyT)
  8861. (values (HasType (Lambda params rT new-body) ty) ty)]
  8862. [else
  8863. (error "mismatch in return type" bodyT rT)])]
  8864. ...
  8865. )))
  8866. \end{lstlisting}
  8867. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8868. \label{fig:type-check-Rlambda}
  8869. \end{figure}
  8870. \section{Reveal Functions and the $F_2$ language}
  8871. \label{sec:reveal-functions-r5}
  8872. To support the \code{procedure-arity} operator we need to communicate
  8873. the arity of a function to the point of closure creation. We can
  8874. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8875. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8876. output of this pass is the language $F_2$, whose syntax is defined in
  8877. Figure~\ref{fig:f2-syntax}.
  8878. \begin{figure}[tp]
  8879. \centering
  8880. \fbox{
  8881. \begin{minipage}{0.96\textwidth}
  8882. \[
  8883. \begin{array}{lcl}
  8884. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8885. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8886. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8887. \end{array}
  8888. \]
  8889. \end{minipage}
  8890. }
  8891. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8892. (Figure~\ref{fig:Rlam-syntax}).}
  8893. \label{fig:f2-syntax}
  8894. \end{figure}
  8895. \section{Closure Conversion}
  8896. \label{sec:closure-conversion}
  8897. \index{closure conversion}
  8898. The compiling of lexically-scoped functions into top-level function
  8899. definitions is accomplished in the pass \code{convert-to-closures}
  8900. that comes after \code{reveal-functions} and before
  8901. \code{limit-functions}.
  8902. As usual, we implement the pass as a recursive function over the
  8903. AST. All of the action is in the cases for \key{Lambda} and
  8904. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8905. that creates a closure, that is, a vector whose first element is a
  8906. function pointer and the rest of the elements are the free variables
  8907. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8908. using \code{vector} so that we can distinguish closures from vectors
  8909. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8910. the generated code below, the \itm{name} is a unique symbol generated
  8911. to identify the function and the \itm{arity} is the number of
  8912. parameters (the length of \itm{ps}).
  8913. \begin{lstlisting}
  8914. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8915. |$\Rightarrow$|
  8916. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8917. \end{lstlisting}
  8918. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8919. create a top-level function definition for each \key{Lambda}, as
  8920. shown below.\\
  8921. \begin{minipage}{0.8\textwidth}
  8922. \begin{lstlisting}
  8923. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8924. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8925. ...
  8926. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8927. |\itm{body'}|)...))
  8928. \end{lstlisting}
  8929. \end{minipage}\\
  8930. The \code{clos} parameter refers to the closure. Translate the type
  8931. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8932. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8933. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8934. underscore \code{\_} is a dummy type that we use because it is rather
  8935. difficult to give a type to the function in the closure's
  8936. type.\footnote{To give an accurate type to a closure, we would need to
  8937. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8938. The dummy type is considered to be equal to any other type during type
  8939. checking. The sequence of \key{Let} forms bind the free variables to
  8940. their values obtained from the closure.
  8941. Closure conversion turns functions into vectors, so the type
  8942. annotations in the program must also be translated. We recommend
  8943. defining a auxiliary recursive function for this purpose. Function
  8944. types should be translated as follows.
  8945. \begin{lstlisting}
  8946. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8947. |$\Rightarrow$|
  8948. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8949. \end{lstlisting}
  8950. The above type says that the first thing in the vector is a function
  8951. pointer. The first parameter of the function pointer is a vector (a
  8952. closure) and the rest of the parameters are the ones from the original
  8953. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8954. the closure omits the types of the free variables because 1) those
  8955. types are not available in this context and 2) we do not need them in
  8956. the code that is generated for function application.
  8957. We transform function application into code that retrieves the
  8958. function pointer from the closure and then calls the function, passing
  8959. in the closure as the first argument. We bind $e'$ to a temporary
  8960. variable to avoid code duplication.
  8961. \begin{lstlisting}
  8962. (Apply |$e$| |\itm{es}|)
  8963. |$\Rightarrow$|
  8964. (Let |\itm{tmp}| |$e'$|
  8965. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8966. \end{lstlisting}
  8967. There is also the question of what to do with references top-level
  8968. function definitions. To maintain a uniform translation of function
  8969. application, we turn function references into closures.
  8970. \begin{tabular}{lll}
  8971. \begin{minipage}{0.3\textwidth}
  8972. \begin{lstlisting}
  8973. (FunRefArity |$f$| |$n$|)
  8974. \end{lstlisting}
  8975. \end{minipage}
  8976. &
  8977. $\Rightarrow$
  8978. &
  8979. \begin{minipage}{0.5\textwidth}
  8980. \begin{lstlisting}
  8981. (Closure |$n$| (FunRef |$f$|) '())
  8982. \end{lstlisting}
  8983. \end{minipage}
  8984. \end{tabular} \\
  8985. %
  8986. The top-level function definitions need to be updated as well to take
  8987. an extra closure parameter.
  8988. \section{An Example Translation}
  8989. \label{sec:example-lambda}
  8990. Figure~\ref{fig:lexical-functions-example} shows the result of
  8991. \code{reveal-functions} and \code{convert-to-closures} for the example
  8992. program demonstrating lexical scoping that we discussed at the
  8993. beginning of this chapter.
  8994. \begin{figure}[tbp]
  8995. \begin{minipage}{0.8\textwidth}
  8996. % tests/lambda_test_6.rkt
  8997. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8998. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8999. (let ([y8 4])
  9000. (lambda: ([z9 : Integer]) : Integer
  9001. (+ x7 (+ y8 z9)))))
  9002. (define (main) : Integer
  9003. (let ([g0 ((fun-ref-arity f6 1) 5)])
  9004. (let ([h1 ((fun-ref-arity f6 1) 3)])
  9005. (+ (g0 11) (h1 15)))))
  9006. \end{lstlisting}
  9007. $\Rightarrow$
  9008. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9009. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  9010. (let ([y8 4])
  9011. (closure 1 (list (fun-ref lambda2) x7 y8))))
  9012. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  9013. (let ([x7 (vector-ref fvs3 1)])
  9014. (let ([y8 (vector-ref fvs3 2)])
  9015. (+ x7 (+ y8 z9)))))
  9016. (define (main) : Integer
  9017. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  9018. ((vector-ref clos5 0) clos5 5))])
  9019. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  9020. ((vector-ref clos6 0) clos6 3))])
  9021. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  9022. \end{lstlisting}
  9023. \end{minipage}
  9024. \caption{Example of closure conversion.}
  9025. \label{fig:lexical-functions-example}
  9026. \end{figure}
  9027. \begin{exercise}\normalfont
  9028. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  9029. Create 5 new programs that use \key{lambda} functions and make use of
  9030. lexical scoping. Test your compiler on these new programs and all of
  9031. your previously created test programs.
  9032. \end{exercise}
  9033. \section{Expose Allocation}
  9034. \label{sec:expose-allocation-r5}
  9035. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  9036. that allocates and initializes a vector, similar to the translation of
  9037. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  9038. The only difference is replacing the use of
  9039. \ALLOC{\itm{len}}{\itm{type}} with
  9040. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  9041. \section{Explicate Control and \LangCLam{}}
  9042. \label{sec:explicate-r5}
  9043. The output language of \code{explicate-control} is \LangCLam{} whose
  9044. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  9045. difference with respect to \LangCFun{} is the addition of the
  9046. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  9047. of \code{AllocateClosure} in the \code{explicate-control} pass is
  9048. similar to the handling of other expressions such as primitive
  9049. operators.
  9050. \begin{figure}[tp]
  9051. \fbox{
  9052. \begin{minipage}{0.96\textwidth}
  9053. \small
  9054. \[
  9055. \begin{array}{lcl}
  9056. \Exp &::= & \ldots
  9057. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  9058. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9059. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  9060. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9061. \mid \GOTO{\itm{label}} } \\
  9062. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9063. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  9064. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9065. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9066. \end{array}
  9067. \]
  9068. \end{minipage}
  9069. }
  9070. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  9071. \label{fig:c4-syntax}
  9072. \end{figure}
  9073. \section{Select Instructions}
  9074. \label{sec:select-instructions-Rlambda}
  9075. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  9076. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  9077. (Section~\ref{sec:select-instructions-gc}). The only difference is
  9078. that you should place the \itm{arity} in the tag that is stored at
  9079. position $0$ of the vector. Recall that in
  9080. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  9081. was not used. We store the arity in the $5$ bits starting at position
  9082. $58$.
  9083. Compile the \code{procedure-arity} operator into a sequence of
  9084. instructions that access the tag from position $0$ of the vector and
  9085. extract the $5$-bits starting at position $58$ from the tag.
  9086. \begin{figure}[p]
  9087. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9088. \node (Rfun) at (0,2) {\large \LangFun{}};
  9089. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  9090. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  9091. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  9092. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  9093. \node (F1-3) at (6,0) {\large $F_1$};
  9094. \node (F1-4) at (3,0) {\large $F_1$};
  9095. \node (F1-5) at (0,0) {\large $F_1$};
  9096. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  9097. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9098. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9099. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9100. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9101. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9102. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9103. \path[->,bend left=15] (Rfun) edge [above] node
  9104. {\ttfamily\footnotesize shrink} (Rfun-2);
  9105. \path[->,bend left=15] (Rfun-2) edge [above] node
  9106. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9107. \path[->,bend left=15] (Rfun-3) edge [right] node
  9108. {\ttfamily\footnotesize reveal-functions} (F1-1);
  9109. \path[->,bend left=15] (F1-1) edge [below] node
  9110. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9111. \path[->,bend right=15] (F1-2) edge [above] node
  9112. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9113. \path[->,bend right=15] (F1-3) edge [above] node
  9114. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9115. \path[->,bend right=15] (F1-4) edge [above] node
  9116. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9117. \path[->,bend right=15] (F1-5) edge [right] node
  9118. {\ttfamily\footnotesize explicate-control} (C3-2);
  9119. \path[->,bend left=15] (C3-2) edge [left] node
  9120. {\ttfamily\footnotesize select-instr.} (x86-2);
  9121. \path[->,bend right=15] (x86-2) edge [left] node
  9122. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9123. \path[->,bend right=15] (x86-2-1) edge [below] node
  9124. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9125. \path[->,bend right=15] (x86-2-2) edge [left] node
  9126. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9127. \path[->,bend left=15] (x86-3) edge [above] node
  9128. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9129. \path[->,bend left=15] (x86-4) edge [right] node
  9130. {\ttfamily\footnotesize print-x86} (x86-5);
  9131. \end{tikzpicture}
  9132. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  9133. functions.}
  9134. \label{fig:Rlambda-passes}
  9135. \end{figure}
  9136. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  9137. for the compilation of \LangLam{}.
  9138. \clearpage
  9139. \section{Challenge: Optimize Closures}
  9140. \label{sec:optimize-closures}
  9141. In this chapter we compiled lexically-scoped functions into a
  9142. relatively efficient representation: flat closures. However, even this
  9143. representation comes with some overhead. For example, consider the
  9144. following program with a function \code{tail-sum} that does not have
  9145. any free variables and where all the uses of \code{tail-sum} are in
  9146. applications where we know that only \code{tail-sum} is being applied
  9147. (and not any other functions).
  9148. \begin{center}
  9149. \begin{minipage}{0.95\textwidth}
  9150. \begin{lstlisting}
  9151. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  9152. (if (eq? n 0)
  9153. r
  9154. (tail-sum (- n 1) (+ n r))))
  9155. (+ (tail-sum 5 0) 27)
  9156. \end{lstlisting}
  9157. \end{minipage}
  9158. \end{center}
  9159. As described in this chapter, we uniformly apply closure conversion to
  9160. all functions, obtaining the following output for this program.
  9161. \begin{center}
  9162. \begin{minipage}{0.95\textwidth}
  9163. \begin{lstlisting}
  9164. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  9165. (if (eq? n2 0)
  9166. r3
  9167. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  9168. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  9169. (define (main) : Integer
  9170. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  9171. ((vector-ref clos6 0) clos6 5 0)) 27))
  9172. \end{lstlisting}
  9173. \end{minipage}
  9174. \end{center}
  9175. In the previous Chapter, there would be no allocation in the program
  9176. and the calls to \code{tail-sum} would be direct calls. In contrast,
  9177. the above program allocates memory for each \code{closure} and the
  9178. calls to \code{tail-sum} are indirect. These two differences incur
  9179. considerable overhead in a program such as this one, where the
  9180. allocations and indirect calls occur inside a tight loop.
  9181. One might think that this problem is trivial to solve: can't we just
  9182. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  9183. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  9184. e'_n$)} instead of treating it like a call to a closure? We would
  9185. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  9186. %
  9187. However, this problem is not so trivial because a global function may
  9188. ``escape'' and become involved in applications that also involve
  9189. closures. Consider the following example in which the application
  9190. \code{(f 41)} needs to be compiled into a closure application, because
  9191. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  9192. function might also get bound to \code{f}.
  9193. \begin{lstlisting}
  9194. (define (add1 [x : Integer]) : Integer
  9195. (+ x 1))
  9196. (let ([y (read)])
  9197. (let ([f (if (eq? (read) 0)
  9198. add1
  9199. (lambda: ([x : Integer]) : Integer (- x y)))])
  9200. (f 41)))
  9201. \end{lstlisting}
  9202. If a global function name is used in any way other than as the
  9203. operator in a direct call, then we say that the function
  9204. \emph{escapes}. If a global function does not escape, then we do not
  9205. need to perform closure conversion on the function.
  9206. \begin{exercise}\normalfont
  9207. Implement an auxiliary function for detecting which global
  9208. functions escape. Using that function, implement an improved version
  9209. of closure conversion that does not apply closure conversion to
  9210. global functions that do not escape but instead compiles them as
  9211. regular functions. Create several new test cases that check whether
  9212. you properly detect whether global functions escape or not.
  9213. \end{exercise}
  9214. So far we have reduced the overhead of calling global functions, but
  9215. it would also be nice to reduce the overhead of calling a
  9216. \code{lambda} when we can determine at compile time which
  9217. \code{lambda} will be called. We refer to such calls as \emph{known
  9218. calls}. Consider the following example in which a \code{lambda} is
  9219. bound to \code{f} and then applied.
  9220. \begin{lstlisting}
  9221. (let ([y (read)])
  9222. (let ([f (lambda: ([x : Integer]) : Integer
  9223. (+ x y))])
  9224. (f 21)))
  9225. \end{lstlisting}
  9226. Closure conversion compiles \code{(f 21)} into an indirect call:
  9227. \begin{lstlisting}
  9228. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  9229. (let ([y2 (vector-ref fvs6 1)])
  9230. (+ x3 y2)))
  9231. (define (main) : Integer
  9232. (let ([y2 (read)])
  9233. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  9234. ((vector-ref f4 0) f4 21))))
  9235. \end{lstlisting}
  9236. but we can instead compile the application \code{(f 21)} into a direct call
  9237. to \code{lambda5}:
  9238. \begin{lstlisting}
  9239. (define (main) : Integer
  9240. (let ([y2 (read)])
  9241. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  9242. ((fun-ref lambda5) f4 21))))
  9243. \end{lstlisting}
  9244. The problem of determining which lambda will be called from a
  9245. particular application is quite challenging in general and the topic
  9246. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  9247. following exercise we recommend that you compile an application to a
  9248. direct call when the operator is a variable and the variable is
  9249. \code{let}-bound to a closure. This can be accomplished by maintaining
  9250. an environment mapping \code{let}-bound variables to function names.
  9251. Extend the environment whenever you encounter a closure on the
  9252. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  9253. to the name of the global function for the closure. This pass should
  9254. come after closure conversion.
  9255. \begin{exercise}\normalfont
  9256. Implement a compiler pass, named \code{optimize-known-calls}, that
  9257. compiles known calls into direct calls. Verify that your compiler is
  9258. successful in this regard on several example programs.
  9259. \end{exercise}
  9260. These exercises only scratches the surface of optimizing of
  9261. closures. A good next step for the interested reader is to look at the
  9262. work of \citet{Keep:2012ab}.
  9263. \section{Further Reading}
  9264. The notion of lexically scoped anonymous functions predates modern
  9265. computers by about a decade. They were invented by
  9266. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  9267. foundation for logic. Anonymous functions were included in the
  9268. LISP~\citep{McCarthy:1960dz} programming language but were initially
  9269. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  9270. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  9271. compile Scheme programs. However, environments were represented as
  9272. linked lists, so variable lookup was linear in the size of the
  9273. environment. In this chapter we represent environments using flat
  9274. closures, which were invented by
  9275. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  9276. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  9277. closures, variable lookup is constant time but the time to create a
  9278. closure is proportional to the number of its free variables. Flat
  9279. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  9280. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  9281. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9282. \chapter{Dynamic Typing}
  9283. \label{ch:Rdyn}
  9284. \index{dynamic typing}
  9285. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  9286. typed language that is a subset of Racket. This is in contrast to the
  9287. previous chapters, which have studied the compilation of Typed
  9288. Racket. In dynamically typed languages such as \LangDyn{}, a given
  9289. expression may produce a value of a different type each time it is
  9290. executed. Consider the following example with a conditional \code{if}
  9291. expression that may return a Boolean or an integer depending on the
  9292. input to the program.
  9293. % part of dynamic_test_25.rkt
  9294. \begin{lstlisting}
  9295. (not (if (eq? (read) 1) #f 0))
  9296. \end{lstlisting}
  9297. Languages that allow expressions to produce different kinds of values
  9298. are called \emph{polymorphic}, a word composed of the Greek roots
  9299. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  9300. are several kinds of polymorphism in programming languages, such as
  9301. subtype polymorphism and parametric
  9302. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  9303. study in this chapter does not have a special name but it is the kind
  9304. that arises in dynamically typed languages.
  9305. Another characteristic of dynamically typed languages is that
  9306. primitive operations, such as \code{not}, are often defined to operate
  9307. on many different types of values. In fact, in Racket, the \code{not}
  9308. operator produces a result for any kind of value: given \code{\#f} it
  9309. returns \code{\#t} and given anything else it returns \code{\#f}.
  9310. Furthermore, even when primitive operations restrict their inputs to
  9311. values of a certain type, this restriction is enforced at runtime
  9312. instead of during compilation. For example, the following vector
  9313. reference results in a run-time contract violation because the index
  9314. must be in integer, not a Boolean such as \code{\#t}.
  9315. \begin{lstlisting}
  9316. (vector-ref (vector 42) #t)
  9317. \end{lstlisting}
  9318. \begin{figure}[tp]
  9319. \centering
  9320. \fbox{
  9321. \begin{minipage}{0.97\textwidth}
  9322. \[
  9323. \begin{array}{rcl}
  9324. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  9325. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9326. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  9327. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  9328. &\mid& \key{\#t} \mid \key{\#f}
  9329. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  9330. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  9331. \mid \CUNIOP{\key{not}}{\Exp} \\
  9332. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  9333. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  9334. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  9335. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  9336. &\mid& \LP\Exp \; \Exp\ldots\RP
  9337. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  9338. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  9339. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  9340. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  9341. \LangDyn{} &::=& \Def\ldots\; \Exp
  9342. \end{array}
  9343. \]
  9344. \end{minipage}
  9345. }
  9346. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  9347. \label{fig:r7-concrete-syntax}
  9348. \end{figure}
  9349. \begin{figure}[tp]
  9350. \centering
  9351. \fbox{
  9352. \begin{minipage}{0.96\textwidth}
  9353. \small
  9354. \[
  9355. \begin{array}{lcl}
  9356. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  9357. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  9358. &\mid& \BOOL{\itm{bool}}
  9359. \mid \IF{\Exp}{\Exp}{\Exp} \\
  9360. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  9361. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  9362. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  9363. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  9364. \end{array}
  9365. \]
  9366. \end{minipage}
  9367. }
  9368. \caption{The abstract syntax of \LangDyn{}.}
  9369. \label{fig:r7-syntax}
  9370. \end{figure}
  9371. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  9372. defined in Figures~\ref{fig:r7-concrete-syntax} and
  9373. \ref{fig:r7-syntax}.
  9374. %
  9375. There is no type checker for \LangDyn{} because it is not a statically
  9376. typed language (it's dynamically typed!).
  9377. The definitional interpreter for \LangDyn{} is presented in
  9378. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  9379. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  9380. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  9381. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  9382. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  9383. value} that combines an underlying value with a tag that identifies
  9384. what kind of value it is. We define the following struct
  9385. to represented tagged values.
  9386. \begin{lstlisting}
  9387. (struct Tagged (value tag) #:transparent)
  9388. \end{lstlisting}
  9389. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  9390. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  9391. but don't always capture all the information that a type does. For
  9392. example, a vector of type \code{(Vector Any Any)} is tagged with
  9393. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  9394. is tagged with \code{Procedure}.
  9395. Next consider the match case for \code{vector-ref}. The
  9396. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  9397. is used to ensure that the first argument is a vector and the second
  9398. is an integer. If they are not, a \code{trapped-error} is raised.
  9399. Recall from Section~\ref{sec:interp-Rint} that when a definition
  9400. interpreter raises a \code{trapped-error} error, the compiled code
  9401. must also signal an error by exiting with return code \code{255}. A
  9402. \code{trapped-error} is also raised if the index is not less than
  9403. length of the vector.
  9404. \begin{figure}[tbp]
  9405. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9406. (define ((interp-Rdyn-exp env) ast)
  9407. (define recur (interp-Rdyn-exp env))
  9408. (match ast
  9409. [(Var x) (lookup x env)]
  9410. [(Int n) (Tagged n 'Integer)]
  9411. [(Bool b) (Tagged b 'Boolean)]
  9412. [(Lambda xs rt body)
  9413. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  9414. [(Prim 'vector es)
  9415. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  9416. [(Prim 'vector-ref (list e1 e2))
  9417. (define vec (recur e1)) (define i (recur e2))
  9418. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  9419. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  9420. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  9421. (vector-ref (Tagged-value vec) (Tagged-value i))]
  9422. [(Prim 'vector-set! (list e1 e2 e3))
  9423. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  9424. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  9425. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  9426. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  9427. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  9428. (Tagged (void) 'Void)]
  9429. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  9430. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  9431. [(Prim 'or (list e1 e2))
  9432. (define v1 (recur e1))
  9433. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  9434. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  9435. [(Prim op (list e1))
  9436. #:when (set-member? type-predicates op)
  9437. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  9438. [(Prim op es)
  9439. (define args (map recur es))
  9440. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  9441. (unless (for/or ([expected-tags (op-tags op)])
  9442. (equal? expected-tags tags))
  9443. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  9444. (tag-value
  9445. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  9446. [(If q t f)
  9447. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  9448. [(Apply f es)
  9449. (define new-f (recur f)) (define args (map recur es))
  9450. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  9451. (match f-val
  9452. [`(function ,xs ,body ,lam-env)
  9453. (unless (eq? (length xs) (length args))
  9454. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  9455. (define new-env (append (map cons xs args) lam-env))
  9456. ((interp-Rdyn-exp new-env) body)]
  9457. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  9458. \end{lstlisting}
  9459. \caption{Interpreter for the \LangDyn{} language.}
  9460. \label{fig:interp-Rdyn}
  9461. \end{figure}
  9462. \begin{figure}[tbp]
  9463. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9464. (define (interp-op op)
  9465. (match op
  9466. ['+ fx+]
  9467. ['- fx-]
  9468. ['read read-fixnum]
  9469. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  9470. ['< (lambda (v1 v2)
  9471. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  9472. ['<= (lambda (v1 v2)
  9473. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  9474. ['> (lambda (v1 v2)
  9475. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  9476. ['>= (lambda (v1 v2)
  9477. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  9478. ['boolean? boolean?]
  9479. ['integer? fixnum?]
  9480. ['void? void?]
  9481. ['vector? vector?]
  9482. ['vector-length vector-length]
  9483. ['procedure? (match-lambda
  9484. [`(functions ,xs ,body ,env) #t] [else #f])]
  9485. [else (error 'interp-op "unknown operator" op)]))
  9486. (define (op-tags op)
  9487. (match op
  9488. ['+ '((Integer Integer))]
  9489. ['- '((Integer Integer) (Integer))]
  9490. ['read '(())]
  9491. ['not '((Boolean))]
  9492. ['< '((Integer Integer))]
  9493. ['<= '((Integer Integer))]
  9494. ['> '((Integer Integer))]
  9495. ['>= '((Integer Integer))]
  9496. ['vector-length '((Vector))]))
  9497. (define type-predicates
  9498. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9499. (define (tag-value v)
  9500. (cond [(boolean? v) (Tagged v 'Boolean)]
  9501. [(fixnum? v) (Tagged v 'Integer)]
  9502. [(procedure? v) (Tagged v 'Procedure)]
  9503. [(vector? v) (Tagged v 'Vector)]
  9504. [(void? v) (Tagged v 'Void)]
  9505. [else (error 'tag-value "unidentified value ~a" v)]))
  9506. (define (check-tag val expected ast)
  9507. (define tag (Tagged-tag val))
  9508. (unless (eq? tag expected)
  9509. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  9510. \end{lstlisting}
  9511. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  9512. \label{fig:interp-Rdyn-aux}
  9513. \end{figure}
  9514. \clearpage
  9515. \section{Representation of Tagged Values}
  9516. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  9517. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  9518. values at the bit level. Because almost every operation in \LangDyn{}
  9519. involves manipulating tagged values, the representation must be
  9520. efficient. Recall that all of our values are 64 bits. We shall steal
  9521. the 3 right-most bits to encode the tag. We use $001$ to identify
  9522. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  9523. and $101$ for the void value. We define the following auxiliary
  9524. function for mapping types to tag codes.
  9525. \begin{align*}
  9526. \itm{tagof}(\key{Integer}) &= 001 \\
  9527. \itm{tagof}(\key{Boolean}) &= 100 \\
  9528. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  9529. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  9530. \itm{tagof}(\key{Void}) &= 101
  9531. \end{align*}
  9532. This stealing of 3 bits comes at some price: our integers are reduced
  9533. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  9534. affect vectors and procedures because those values are addresses, and
  9535. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  9536. they are always $000$. Thus, we do not lose information by overwriting
  9537. the rightmost 3 bits with the tag and we can simply zero-out the tag
  9538. to recover the original address.
  9539. To make tagged values into first-class entities, we can give them a
  9540. type, called \code{Any}, and define operations such as \code{Inject}
  9541. and \code{Project} for creating and using them, yielding the \LangAny{}
  9542. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  9543. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  9544. in greater detail.
  9545. \section{The \LangAny{} Language}
  9546. \label{sec:Rany-lang}
  9547. \begin{figure}[tp]
  9548. \centering
  9549. \fbox{
  9550. \begin{minipage}{0.96\textwidth}
  9551. \small
  9552. \[
  9553. \begin{array}{lcl}
  9554. \Type &::= & \ldots \mid \key{Any} \\
  9555. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  9556. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  9557. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  9558. \mid \code{procedure?} \mid \code{void?} \\
  9559. \Exp &::=& \ldots
  9560. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  9561. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  9562. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9563. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9564. \end{array}
  9565. \]
  9566. \end{minipage}
  9567. }
  9568. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  9569. \label{fig:Rany-syntax}
  9570. \end{figure}
  9571. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  9572. (The concrete syntax of \LangAny{} is in the Appendix,
  9573. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  9574. converts the value produced by expression $e$ of type $T$ into a
  9575. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  9576. produced by expression $e$ into a value of type $T$ or else halts the
  9577. program if the type tag is not equivalent to $T$.
  9578. %
  9579. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  9580. restricted to a flat type $\FType$, which simplifies the
  9581. implementation and corresponds with what is needed for compiling \LangDyn{}.
  9582. The \code{any-vector} operators adapt the vector operations so that
  9583. they can be applied to a value of type \code{Any}. They also
  9584. generalize the vector operations in that the index is not restricted
  9585. to be a literal integer in the grammar but is allowed to be any
  9586. expression.
  9587. The type predicates such as \key{boolean?} expect their argument to
  9588. produce a tagged value; they return \key{\#t} if the tag corresponds
  9589. to the predicate and they return \key{\#f} otherwise.
  9590. The type checker for \LangAny{} is shown in
  9591. Figures~\ref{fig:type-check-Rany-part-1} and
  9592. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  9593. Figure~\ref{fig:type-check-Rany-aux}.
  9594. %
  9595. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  9596. auxiliary functions \code{apply-inject} and \code{apply-project} are
  9597. in Figure~\ref{fig:apply-project}.
  9598. \begin{figure}[btp]
  9599. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9600. (define type-check-Rany-class
  9601. (class type-check-Rlambda-class
  9602. (super-new)
  9603. (inherit check-type-equal?)
  9604. (define/override (type-check-exp env)
  9605. (lambda (e)
  9606. (define recur (type-check-exp env))
  9607. (match e
  9608. [(Inject e1 ty)
  9609. (unless (flat-ty? ty)
  9610. (error 'type-check "may only inject from flat type, not ~a" ty))
  9611. (define-values (new-e1 e-ty) (recur e1))
  9612. (check-type-equal? e-ty ty e)
  9613. (values (Inject new-e1 ty) 'Any)]
  9614. [(Project e1 ty)
  9615. (unless (flat-ty? ty)
  9616. (error 'type-check "may only project to flat type, not ~a" ty))
  9617. (define-values (new-e1 e-ty) (recur e1))
  9618. (check-type-equal? e-ty 'Any e)
  9619. (values (Project new-e1 ty) ty)]
  9620. [(Prim 'any-vector-length (list e1))
  9621. (define-values (e1^ t1) (recur e1))
  9622. (check-type-equal? t1 'Any e)
  9623. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  9624. [(Prim 'any-vector-ref (list e1 e2))
  9625. (define-values (e1^ t1) (recur e1))
  9626. (define-values (e2^ t2) (recur e2))
  9627. (check-type-equal? t1 'Any e)
  9628. (check-type-equal? t2 'Integer e)
  9629. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  9630. [(Prim 'any-vector-set! (list e1 e2 e3))
  9631. (define-values (e1^ t1) (recur e1))
  9632. (define-values (e2^ t2) (recur e2))
  9633. (define-values (e3^ t3) (recur e3))
  9634. (check-type-equal? t1 'Any e)
  9635. (check-type-equal? t2 'Integer e)
  9636. (check-type-equal? t3 'Any e)
  9637. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  9638. \end{lstlisting}
  9639. \caption{Type checker for the \LangAny{} language, part 1.}
  9640. \label{fig:type-check-Rany-part-1}
  9641. \end{figure}
  9642. \begin{figure}[btp]
  9643. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9644. [(ValueOf e ty)
  9645. (define-values (new-e e-ty) (recur e))
  9646. (values (ValueOf new-e ty) ty)]
  9647. [(Prim pred (list e1))
  9648. #:when (set-member? (type-predicates) pred)
  9649. (define-values (new-e1 e-ty) (recur e1))
  9650. (check-type-equal? e-ty 'Any e)
  9651. (values (Prim pred (list new-e1)) 'Boolean)]
  9652. [(If cnd thn els)
  9653. (define-values (cnd^ Tc) (recur cnd))
  9654. (define-values (thn^ Tt) (recur thn))
  9655. (define-values (els^ Te) (recur els))
  9656. (check-type-equal? Tc 'Boolean cnd)
  9657. (check-type-equal? Tt Te e)
  9658. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  9659. [(Exit) (values (Exit) '_)]
  9660. [(Prim 'eq? (list arg1 arg2))
  9661. (define-values (e1 t1) (recur arg1))
  9662. (define-values (e2 t2) (recur arg2))
  9663. (match* (t1 t2)
  9664. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9665. [(other wise) (check-type-equal? t1 t2 e)])
  9666. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9667. [else ((super type-check-exp env) e)])))
  9668. ))
  9669. \end{lstlisting}
  9670. \caption{Type checker for the \LangAny{} language, part 2.}
  9671. \label{fig:type-check-Rany-part-2}
  9672. \end{figure}
  9673. \begin{figure}[tbp]
  9674. \begin{lstlisting}
  9675. (define/override (operator-types)
  9676. (append
  9677. '((integer? . ((Any) . Boolean))
  9678. (vector? . ((Any) . Boolean))
  9679. (procedure? . ((Any) . Boolean))
  9680. (void? . ((Any) . Boolean))
  9681. (tag-of-any . ((Any) . Integer))
  9682. (make-any . ((_ Integer) . Any))
  9683. )
  9684. (super operator-types)))
  9685. (define/public (type-predicates)
  9686. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9687. (define/public (combine-types t1 t2)
  9688. (match (list t1 t2)
  9689. [(list '_ t2) t2]
  9690. [(list t1 '_) t1]
  9691. [(list `(Vector ,ts1 ...)
  9692. `(Vector ,ts2 ...))
  9693. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  9694. (combine-types t1 t2)))]
  9695. [(list `(,ts1 ... -> ,rt1)
  9696. `(,ts2 ... -> ,rt2))
  9697. `(,@(for/list ([t1 ts1] [t2 ts2])
  9698. (combine-types t1 t2))
  9699. -> ,(combine-types rt1 rt2))]
  9700. [else t1]))
  9701. (define/public (flat-ty? ty)
  9702. (match ty
  9703. [(or `Integer `Boolean '_ `Void) #t]
  9704. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  9705. [`(,ts ... -> ,rt)
  9706. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  9707. [else #f]))
  9708. \end{lstlisting}
  9709. \caption{Auxiliary methods for type checking \LangAny{}.}
  9710. \label{fig:type-check-Rany-aux}
  9711. \end{figure}
  9712. \begin{figure}[btp]
  9713. \begin{lstlisting}
  9714. (define interp-Rany-class
  9715. (class interp-Rlambda-class
  9716. (super-new)
  9717. (define/override (interp-op op)
  9718. (match op
  9719. ['boolean? (match-lambda
  9720. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  9721. [else #f])]
  9722. ['integer? (match-lambda
  9723. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  9724. [else #f])]
  9725. ['vector? (match-lambda
  9726. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  9727. [else #f])]
  9728. ['procedure? (match-lambda
  9729. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  9730. [else #f])]
  9731. ['eq? (match-lambda*
  9732. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  9733. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  9734. [ls (apply (super interp-op op) ls)])]
  9735. ['any-vector-ref (lambda (v i)
  9736. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  9737. ['any-vector-set! (lambda (v i a)
  9738. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  9739. ['any-vector-length (lambda (v)
  9740. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  9741. [else (super interp-op op)]))
  9742. (define/override ((interp-exp env) e)
  9743. (define recur (interp-exp env))
  9744. (match e
  9745. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9746. [(Project e ty2) (apply-project (recur e) ty2)]
  9747. [else ((super interp-exp env) e)]))
  9748. ))
  9749. (define (interp-Rany p)
  9750. (send (new interp-Rany-class) interp-program p))
  9751. \end{lstlisting}
  9752. \caption{Interpreter for \LangAny{}.}
  9753. \label{fig:interp-Rany}
  9754. \end{figure}
  9755. \begin{figure}[tbp]
  9756. \begin{lstlisting}
  9757. (define/public (apply-inject v tg) (Tagged v tg))
  9758. (define/public (apply-project v ty2)
  9759. (define tag2 (any-tag ty2))
  9760. (match v
  9761. [(Tagged v1 tag1)
  9762. (cond
  9763. [(eq? tag1 tag2)
  9764. (match ty2
  9765. [`(Vector ,ts ...)
  9766. (define l1 ((interp-op 'vector-length) v1))
  9767. (cond
  9768. [(eq? l1 (length ts)) v1]
  9769. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9770. l1 (length ts))])]
  9771. [`(,ts ... -> ,rt)
  9772. (match v1
  9773. [`(function ,xs ,body ,env)
  9774. (cond [(eq? (length xs) (length ts)) v1]
  9775. [else
  9776. (error 'apply-project "arity mismatch ~a != ~a"
  9777. (length xs) (length ts))])]
  9778. [else (error 'apply-project "expected function not ~a" v1)])]
  9779. [else v1])]
  9780. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9781. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9782. \end{lstlisting}
  9783. \caption{Auxiliary functions for injection and projection.}
  9784. \label{fig:apply-project}
  9785. \end{figure}
  9786. \clearpage
  9787. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9788. \label{sec:compile-r7}
  9789. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9790. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9791. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9792. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9793. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9794. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9795. the Boolean \code{\#t}, which must be injected to produce an
  9796. expression of type \key{Any}.
  9797. %
  9798. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9799. addition, is representative of compilation for many primitive
  9800. operations: the arguments have type \key{Any} and must be projected to
  9801. \key{Integer} before the addition can be performed.
  9802. The compilation of \key{lambda} (third row of
  9803. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9804. produce type annotations: we simply use \key{Any}.
  9805. %
  9806. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9807. has to account for some differences in behavior between \LangDyn{} and
  9808. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9809. kind of values can be used in various places. For example, the
  9810. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9811. the arguments need not be of the same type (in that case the
  9812. result is \code{\#f}).
  9813. \begin{figure}[btp]
  9814. \centering
  9815. \begin{tabular}{|lll|} \hline
  9816. \begin{minipage}{0.27\textwidth}
  9817. \begin{lstlisting}
  9818. #t
  9819. \end{lstlisting}
  9820. \end{minipage}
  9821. &
  9822. $\Rightarrow$
  9823. &
  9824. \begin{minipage}{0.65\textwidth}
  9825. \begin{lstlisting}
  9826. (inject #t Boolean)
  9827. \end{lstlisting}
  9828. \end{minipage}
  9829. \\[2ex]\hline
  9830. \begin{minipage}{0.27\textwidth}
  9831. \begin{lstlisting}
  9832. (+ |$e_1$| |$e_2$|)
  9833. \end{lstlisting}
  9834. \end{minipage}
  9835. &
  9836. $\Rightarrow$
  9837. &
  9838. \begin{minipage}{0.65\textwidth}
  9839. \begin{lstlisting}
  9840. (inject
  9841. (+ (project |$e'_1$| Integer)
  9842. (project |$e'_2$| Integer))
  9843. Integer)
  9844. \end{lstlisting}
  9845. \end{minipage}
  9846. \\[2ex]\hline
  9847. \begin{minipage}{0.27\textwidth}
  9848. \begin{lstlisting}
  9849. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9850. \end{lstlisting}
  9851. \end{minipage}
  9852. &
  9853. $\Rightarrow$
  9854. &
  9855. \begin{minipage}{0.65\textwidth}
  9856. \begin{lstlisting}
  9857. (inject
  9858. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9859. (Any|$\ldots$|Any -> Any))
  9860. \end{lstlisting}
  9861. \end{minipage}
  9862. \\[2ex]\hline
  9863. \begin{minipage}{0.27\textwidth}
  9864. \begin{lstlisting}
  9865. (|$e_0$| |$e_1 \ldots e_n$|)
  9866. \end{lstlisting}
  9867. \end{minipage}
  9868. &
  9869. $\Rightarrow$
  9870. &
  9871. \begin{minipage}{0.65\textwidth}
  9872. \begin{lstlisting}
  9873. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9874. \end{lstlisting}
  9875. \end{minipage}
  9876. \\[2ex]\hline
  9877. \begin{minipage}{0.27\textwidth}
  9878. \begin{lstlisting}
  9879. (vector-ref |$e_1$| |$e_2$|)
  9880. \end{lstlisting}
  9881. \end{minipage}
  9882. &
  9883. $\Rightarrow$
  9884. &
  9885. \begin{minipage}{0.65\textwidth}
  9886. \begin{lstlisting}
  9887. (any-vector-ref |$e_1'$| |$e_2'$|)
  9888. \end{lstlisting}
  9889. \end{minipage}
  9890. \\[2ex]\hline
  9891. \begin{minipage}{0.27\textwidth}
  9892. \begin{lstlisting}
  9893. (if |$e_1$| |$e_2$| |$e_3$|)
  9894. \end{lstlisting}
  9895. \end{minipage}
  9896. &
  9897. $\Rightarrow$
  9898. &
  9899. \begin{minipage}{0.65\textwidth}
  9900. \begin{lstlisting}
  9901. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9902. \end{lstlisting}
  9903. \end{minipage}
  9904. \\[2ex]\hline
  9905. \begin{minipage}{0.27\textwidth}
  9906. \begin{lstlisting}
  9907. (eq? |$e_1$| |$e_2$|)
  9908. \end{lstlisting}
  9909. \end{minipage}
  9910. &
  9911. $\Rightarrow$
  9912. &
  9913. \begin{minipage}{0.65\textwidth}
  9914. \begin{lstlisting}
  9915. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9916. \end{lstlisting}
  9917. \end{minipage}
  9918. \\[2ex]\hline
  9919. \begin{minipage}{0.27\textwidth}
  9920. \begin{lstlisting}
  9921. (not |$e_1$|)
  9922. \end{lstlisting}
  9923. \end{minipage}
  9924. &
  9925. $\Rightarrow$
  9926. &
  9927. \begin{minipage}{0.65\textwidth}
  9928. \begin{lstlisting}
  9929. (if (eq? |$e'_1$| (inject #f Boolean))
  9930. (inject #t Boolean) (inject #f Boolean))
  9931. \end{lstlisting}
  9932. \end{minipage}
  9933. \\[2ex]\hline
  9934. \end{tabular}
  9935. \caption{Cast Insertion}
  9936. \label{fig:compile-r7-Rany}
  9937. \end{figure}
  9938. \section{Reveal Casts}
  9939. \label{sec:reveal-casts-Rany}
  9940. % TODO: define R'_6
  9941. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9942. into an \code{if} expression that checks whether the value's tag
  9943. matches the target type; if it does, the value is converted to a value
  9944. of the target type by removing the tag; if it does not, the program
  9945. exits. To perform these actions we need a new primitive operation,
  9946. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9947. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9948. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9949. underlying value from a tagged value. The \code{ValueOf} form
  9950. includes the type for the underlying value which is used by the type
  9951. checker. Finally, the \code{Exit} form ends the execution of the
  9952. program.
  9953. If the target type of the projection is \code{Boolean} or
  9954. \code{Integer}, then \code{Project} can be translated as follows.
  9955. \begin{center}
  9956. \begin{minipage}{1.0\textwidth}
  9957. \begin{lstlisting}
  9958. (Project |$e$| |$\FType$|)
  9959. |$\Rightarrow$|
  9960. (Let |$\itm{tmp}$| |$e'$|
  9961. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9962. (Int |$\itm{tagof}(\FType)$|)))
  9963. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9964. (Exit)))
  9965. \end{lstlisting}
  9966. \end{minipage}
  9967. \end{center}
  9968. If the target type of the projection is a vector or function type,
  9969. then there is a bit more work to do. For vectors, check that the
  9970. length of the vector type matches the length of the vector (using the
  9971. \code{vector-length} primitive). For functions, check that the number
  9972. of parameters in the function type matches the function's arity (using
  9973. \code{procedure-arity}).
  9974. Regarding \code{inject}, we recommend compiling it to a slightly
  9975. lower-level primitive operation named \code{make-any}. This operation
  9976. takes a tag instead of a type.
  9977. \begin{center}
  9978. \begin{minipage}{1.0\textwidth}
  9979. \begin{lstlisting}
  9980. (Inject |$e$| |$\FType$|)
  9981. |$\Rightarrow$|
  9982. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9983. \end{lstlisting}
  9984. \end{minipage}
  9985. \end{center}
  9986. The type predicates (\code{boolean?}, etc.) can be translated into
  9987. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9988. translation of \code{Project}.
  9989. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9990. combine the projection action with the vector operation. Also, the
  9991. read and write operations allow arbitrary expressions for the index so
  9992. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9993. cannot guarantee that the index is within bounds. Thus, we insert code
  9994. to perform bounds checking at runtime. The translation for
  9995. \code{any-vector-ref} is as follows and the other two operations are
  9996. translated in a similar way.
  9997. \begin{lstlisting}
  9998. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9999. |$\Rightarrow$|
  10000. (Let |$v$| |$e'_1$|
  10001. (Let |$i$| |$e'_2$|
  10002. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  10003. (If (Prim '< (list (Var |$i$|)
  10004. (Prim 'any-vector-length (list (Var |$v$|)))))
  10005. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  10006. (Exit))))
  10007. \end{lstlisting}
  10008. \section{Remove Complex Operands}
  10009. \label{sec:rco-Rany}
  10010. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  10011. The subexpression of \code{ValueOf} must be atomic.
  10012. \section{Explicate Control and \LangCAny{}}
  10013. \label{sec:explicate-Rany}
  10014. The output of \code{explicate-control} is the \LangCAny{} language whose
  10015. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  10016. form that we added to \LangAny{} remains an expression and the \code{Exit}
  10017. expression becomes a $\Tail$. Also, note that the index argument of
  10018. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  10019. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  10020. \begin{figure}[tp]
  10021. \fbox{
  10022. \begin{minipage}{0.96\textwidth}
  10023. \small
  10024. \[
  10025. \begin{array}{lcl}
  10026. \Exp &::= & \ldots
  10027. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  10028. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  10029. &\mid& \VALUEOF{\Exp}{\FType} \\
  10030. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10031. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  10032. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  10033. \mid \GOTO{\itm{label}} } \\
  10034. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10035. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  10036. \mid \LP\key{Exit}\RP \\
  10037. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  10038. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  10039. \end{array}
  10040. \]
  10041. \end{minipage}
  10042. }
  10043. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10044. \label{fig:c5-syntax}
  10045. \end{figure}
  10046. \section{Select Instructions}
  10047. \label{sec:select-Rany}
  10048. In the \code{select-instructions} pass we translate the primitive
  10049. operations on the \code{Any} type to x86 instructions that involve
  10050. manipulating the 3 tag bits of the tagged value.
  10051. \paragraph{Make-any}
  10052. We recommend compiling the \key{make-any} primitive as follows if the
  10053. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  10054. shifts the destination to the left by the number of bits specified its
  10055. source argument (in this case $3$, the length of the tag) and it
  10056. preserves the sign of the integer. We use the \key{orq} instruction to
  10057. combine the tag and the value to form the tagged value. \\
  10058. \begin{lstlisting}
  10059. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  10060. |$\Rightarrow$|
  10061. movq |$e'$|, |\itm{lhs'}|
  10062. salq $3, |\itm{lhs'}|
  10063. orq $|$\itm{tag}$|, |\itm{lhs'}|
  10064. \end{lstlisting}
  10065. The instruction selection for vectors and procedures is different
  10066. because their is no need to shift them to the left. The rightmost 3
  10067. bits are already zeros as described at the beginning of this
  10068. chapter. So we just combine the value and the tag using \key{orq}. \\
  10069. \begin{lstlisting}
  10070. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  10071. |$\Rightarrow$|
  10072. movq |$e'$|, |\itm{lhs'}|
  10073. orq $|$\itm{tag}$|, |\itm{lhs'}|
  10074. \end{lstlisting}
  10075. \paragraph{Tag-of-any}
  10076. Recall that the \code{tag-of-any} operation extracts the type tag from
  10077. a value of type \code{Any}. The type tag is the bottom three bits, so
  10078. we obtain the tag by taking the bitwise-and of the value with $111$
  10079. ($7$ in decimal).
  10080. \begin{lstlisting}
  10081. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  10082. |$\Rightarrow$|
  10083. movq |$e'$|, |\itm{lhs'}|
  10084. andq $7, |\itm{lhs'}|
  10085. \end{lstlisting}
  10086. \paragraph{ValueOf}
  10087. Like \key{make-any}, the instructions for \key{ValueOf} are different
  10088. depending on whether the type $T$ is a pointer (vector or procedure)
  10089. or not (Integer or Boolean). The following shows the instruction
  10090. selection for Integer and Boolean. We produce an untagged value by
  10091. shifting it to the right by 3 bits.
  10092. \begin{lstlisting}
  10093. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  10094. |$\Rightarrow$|
  10095. movq |$e'$|, |\itm{lhs'}|
  10096. sarq $3, |\itm{lhs'}|
  10097. \end{lstlisting}
  10098. %
  10099. In the case for vectors and procedures, there is no need to
  10100. shift. Instead we just need to zero-out the rightmost 3 bits. We
  10101. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  10102. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  10103. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  10104. then apply \code{andq} with the tagged value to get the desired
  10105. result. \\
  10106. \begin{lstlisting}
  10107. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  10108. |$\Rightarrow$|
  10109. movq $|$-8$|, |\itm{lhs'}|
  10110. andq |$e'$|, |\itm{lhs'}|
  10111. \end{lstlisting}
  10112. %% \paragraph{Type Predicates} We leave it to the reader to
  10113. %% devise a sequence of instructions to implement the type predicates
  10114. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  10115. \paragraph{Any-vector-length}
  10116. \begin{lstlisting}
  10117. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  10118. |$\Longrightarrow$|
  10119. movq |$\neg 111$|, %r11
  10120. andq |$a_1'$|, %r11
  10121. movq 0(%r11), %r11
  10122. andq $126, %r11
  10123. sarq $1, %r11
  10124. movq %r11, |$\itm{lhs'}$|
  10125. \end{lstlisting}
  10126. \paragraph{Any-vector-ref}
  10127. The index may be an arbitrary atom so instead of computing the offset
  10128. at compile time, instructions need to be generated to compute the
  10129. offset at runtime as follows. Note the use of the new instruction
  10130. \code{imulq}.
  10131. \begin{center}
  10132. \begin{minipage}{0.96\textwidth}
  10133. \begin{lstlisting}
  10134. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  10135. |$\Longrightarrow$|
  10136. movq |$\neg 111$|, %r11
  10137. andq |$a_1'$|, %r11
  10138. movq |$a_2'$|, %rax
  10139. addq $1, %rax
  10140. imulq $8, %rax
  10141. addq %rax, %r11
  10142. movq 0(%r11) |$\itm{lhs'}$|
  10143. \end{lstlisting}
  10144. \end{minipage}
  10145. \end{center}
  10146. \paragraph{Any-vector-set!}
  10147. The code generation for \code{any-vector-set!} is similar to the other
  10148. \code{any-vector} operations.
  10149. \section{Register Allocation for \LangAny{}}
  10150. \label{sec:register-allocation-Rany}
  10151. \index{register allocation}
  10152. There is an interesting interaction between tagged values and garbage
  10153. collection that has an impact on register allocation. A variable of
  10154. type \code{Any} might refer to a vector and therefore it might be a
  10155. root that needs to be inspected and copied during garbage
  10156. collection. Thus, we need to treat variables of type \code{Any} in a
  10157. similar way to variables of type \code{Vector} for purposes of
  10158. register allocation. In particular,
  10159. \begin{itemize}
  10160. \item If a variable of type \code{Any} is live during a function call,
  10161. then it must be spilled. This can be accomplished by changing
  10162. \code{build-interference} to mark all variables of type \code{Any}
  10163. that are live after a \code{callq} as interfering with all the
  10164. registers.
  10165. \item If a variable of type \code{Any} is spilled, it must be spilled
  10166. to the root stack instead of the normal procedure call stack.
  10167. \end{itemize}
  10168. Another concern regarding the root stack is that the garbage collector
  10169. needs to differentiate between (1) plain old pointers to tuples, (2) a
  10170. tagged value that points to a tuple, and (3) a tagged value that is
  10171. not a tuple. We enable this differentiation by choosing not to use the
  10172. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  10173. reserved for identifying plain old pointers to tuples. That way, if
  10174. one of the first three bits is set, then we have a tagged value and
  10175. inspecting the tag can differentiation between vectors ($010$) and the
  10176. other kinds of values.
  10177. \begin{exercise}\normalfont
  10178. Expand your compiler to handle \LangAny{} as discussed in the last few
  10179. sections. Create 5 new programs that use the \code{Any} type and the
  10180. new operations (\code{inject}, \code{project}, \code{boolean?},
  10181. etc.). Test your compiler on these new programs and all of your
  10182. previously created test programs.
  10183. \end{exercise}
  10184. \begin{exercise}\normalfont
  10185. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  10186. Create tests for \LangDyn{} by adapting ten of your previous test programs
  10187. by removing type annotations. Add 5 more tests programs that
  10188. specifically rely on the language being dynamically typed. That is,
  10189. they should not be legal programs in a statically typed language, but
  10190. nevertheless, they should be valid \LangDyn{} programs that run to
  10191. completion without error.
  10192. \end{exercise}
  10193. \begin{figure}[p]
  10194. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10195. \node (Rfun) at (0,4) {\large \LangDyn{}};
  10196. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  10197. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  10198. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  10199. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  10200. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  10201. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  10202. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  10203. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  10204. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  10205. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  10206. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  10207. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10208. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10209. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10210. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10211. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10212. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10213. \path[->,bend left=15] (Rfun) edge [above] node
  10214. {\ttfamily\footnotesize shrink} (Rfun-2);
  10215. \path[->,bend left=15] (Rfun-2) edge [above] node
  10216. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10217. \path[->,bend left=15] (Rfun-3) edge [above] node
  10218. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10219. \path[->,bend right=15] (Rfun-4) edge [left] node
  10220. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  10221. \path[->,bend left=15] (Rfun-5) edge [above] node
  10222. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  10223. \path[->,bend left=15] (Rfun-6) edge [left] node
  10224. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  10225. \path[->,bend left=15] (Rfun-7) edge [below] node
  10226. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10227. \path[->,bend right=15] (F1-2) edge [above] node
  10228. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10229. \path[->,bend right=15] (F1-3) edge [above] node
  10230. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10231. \path[->,bend right=15] (F1-4) edge [above] node
  10232. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10233. \path[->,bend right=15] (F1-5) edge [right] node
  10234. {\ttfamily\footnotesize explicate-control} (C3-2);
  10235. \path[->,bend left=15] (C3-2) edge [left] node
  10236. {\ttfamily\footnotesize select-instr.} (x86-2);
  10237. \path[->,bend right=15] (x86-2) edge [left] node
  10238. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10239. \path[->,bend right=15] (x86-2-1) edge [below] node
  10240. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10241. \path[->,bend right=15] (x86-2-2) edge [left] node
  10242. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10243. \path[->,bend left=15] (x86-3) edge [above] node
  10244. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10245. \path[->,bend left=15] (x86-4) edge [right] node
  10246. {\ttfamily\footnotesize print-x86} (x86-5);
  10247. \end{tikzpicture}
  10248. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  10249. \label{fig:Rdyn-passes}
  10250. \end{figure}
  10251. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  10252. for the compilation of \LangDyn{}.
  10253. % Further Reading
  10254. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10255. \chapter{Loops and Assignment}
  10256. \label{ch:Rwhile}
  10257. % TODO: define R'_8
  10258. % TODO: multi-graph
  10259. In this chapter we study two features that are the hallmarks of
  10260. imperative programming languages: loops and assignments to local
  10261. variables. The following example demonstrates these new features by
  10262. computing the sum of the first five positive integers.
  10263. % similar to loop_test_1.rkt
  10264. \begin{lstlisting}
  10265. (let ([sum 0])
  10266. (let ([i 5])
  10267. (begin
  10268. (while (> i 0)
  10269. (begin
  10270. (set! sum (+ sum i))
  10271. (set! i (- i 1))))
  10272. sum)))
  10273. \end{lstlisting}
  10274. The \code{while} loop consists of a condition and a body.
  10275. %
  10276. The \code{set!} consists of a variable and a right-hand-side expression.
  10277. %
  10278. The primary purpose of both the \code{while} loop and \code{set!} is
  10279. to cause side effects, so it is convenient to also include in a
  10280. language feature for sequencing side effects: the \code{begin}
  10281. expression. It consists of one or more subexpressions that are
  10282. evaluated left-to-right.
  10283. \section{The \LangLoop{} Language}
  10284. \begin{figure}[tp]
  10285. \centering
  10286. \fbox{
  10287. \begin{minipage}{0.96\textwidth}
  10288. \small
  10289. \[
  10290. \begin{array}{lcl}
  10291. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10292. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10293. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10294. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10295. \mid (\key{and}\;\Exp\;\Exp)
  10296. \mid (\key{or}\;\Exp\;\Exp)
  10297. \mid (\key{not}\;\Exp) } \\
  10298. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10299. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10300. (\key{vector-ref}\;\Exp\;\Int)} \\
  10301. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10302. \mid (\Exp \; \Exp\ldots) } \\
  10303. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10304. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10305. &\mid& \CSETBANG{\Var}{\Exp}
  10306. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10307. \mid \CWHILE{\Exp}{\Exp} \\
  10308. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10309. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  10310. \end{array}
  10311. \]
  10312. \end{minipage}
  10313. }
  10314. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  10315. \label{fig:Rwhile-concrete-syntax}
  10316. \end{figure}
  10317. \begin{figure}[tp]
  10318. \centering
  10319. \fbox{
  10320. \begin{minipage}{0.96\textwidth}
  10321. \small
  10322. \[
  10323. \begin{array}{lcl}
  10324. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10325. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10326. &\mid& \gray{ \BOOL{\itm{bool}}
  10327. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10328. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10329. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10330. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  10331. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  10332. \mid \WHILE{\Exp}{\Exp} \\
  10333. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  10334. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10335. \end{array}
  10336. \]
  10337. \end{minipage}
  10338. }
  10339. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  10340. \label{fig:Rwhile-syntax}
  10341. \end{figure}
  10342. The concrete syntax of \LangLoop{} is defined in
  10343. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  10344. in Figure~\ref{fig:Rwhile-syntax}.
  10345. %
  10346. The definitional interpreter for \LangLoop{} is shown in
  10347. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  10348. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  10349. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  10350. support assignment to variables and to make their lifetimes indefinite
  10351. (see the second example in Section~\ref{sec:assignment-scoping}), we
  10352. box the value that is bound to each variable (in \code{Let}) and
  10353. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  10354. the value.
  10355. %
  10356. Now to discuss the new cases. For \code{SetBang}, we lookup the
  10357. variable in the environment to obtain a boxed value and then we change
  10358. it using \code{set-box!} to the result of evaluating the right-hand
  10359. side. The result value of a \code{SetBang} is \code{void}.
  10360. %
  10361. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  10362. if the result is true, 2) evaluate the body.
  10363. The result value of a \code{while} loop is also \code{void}.
  10364. %
  10365. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10366. subexpressions \itm{es} for their effects and then evaluates
  10367. and returns the result from \itm{body}.
  10368. \begin{figure}[tbp]
  10369. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10370. (define interp-Rwhile-class
  10371. (class interp-Rany-class
  10372. (super-new)
  10373. (define/override ((interp-exp env) e)
  10374. (define recur (interp-exp env))
  10375. (match e
  10376. [(SetBang x rhs)
  10377. (set-box! (lookup x env) (recur rhs))]
  10378. [(WhileLoop cnd body)
  10379. (define (loop)
  10380. (cond [(recur cnd) (recur body) (loop)]
  10381. [else (void)]))
  10382. (loop)]
  10383. [(Begin es body)
  10384. (for ([e es]) (recur e))
  10385. (recur body)]
  10386. [else ((super interp-exp env) e)]))
  10387. ))
  10388. (define (interp-Rwhile p)
  10389. (send (new interp-Rwhile-class) interp-program p))
  10390. \end{lstlisting}
  10391. \caption{Interpreter for \LangLoop{}.}
  10392. \label{fig:interp-Rwhile}
  10393. \end{figure}
  10394. The type checker for \LangLoop{} is define in
  10395. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  10396. variable and the right-hand-side must agree. The result type is
  10397. \code{Void}. For the \code{WhileLoop}, the condition must be a
  10398. \code{Boolean}. The result type is also \code{Void}. For
  10399. \code{Begin}, the result type is the type of its last subexpression.
  10400. \begin{figure}[tbp]
  10401. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10402. (define type-check-Rwhile-class
  10403. (class type-check-Rany-class
  10404. (super-new)
  10405. (inherit check-type-equal?)
  10406. (define/override (type-check-exp env)
  10407. (lambda (e)
  10408. (define recur (type-check-exp env))
  10409. (match e
  10410. [(SetBang x rhs)
  10411. (define-values (rhs^ rhsT) (recur rhs))
  10412. (define varT (dict-ref env x))
  10413. (check-type-equal? rhsT varT e)
  10414. (values (SetBang x rhs^) 'Void)]
  10415. [(WhileLoop cnd body)
  10416. (define-values (cnd^ Tc) (recur cnd))
  10417. (check-type-equal? Tc 'Boolean e)
  10418. (define-values (body^ Tbody) ((type-check-exp env) body))
  10419. (values (WhileLoop cnd^ body^) 'Void)]
  10420. [(Begin es body)
  10421. (define-values (es^ ts)
  10422. (for/lists (l1 l2) ([e es]) (recur e)))
  10423. (define-values (body^ Tbody) (recur body))
  10424. (values (Begin es^ body^) Tbody)]
  10425. [else ((super type-check-exp env) e)])))
  10426. ))
  10427. (define (type-check-Rwhile p)
  10428. (send (new type-check-Rwhile-class) type-check-program p))
  10429. \end{lstlisting}
  10430. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  10431. and \code{Begin} in \LangLoop{}.}
  10432. \label{fig:type-check-Rwhile}
  10433. \end{figure}
  10434. At first glance, the translation of these language features to x86
  10435. seems straightforward because the \LangCFun{} intermediate language already
  10436. supports all of the ingredients that we need: assignment, \code{goto},
  10437. conditional branching, and sequencing. However, there are two
  10438. complications that arise which we discuss in the next two
  10439. sections. After that we introduce one new compiler pass and the
  10440. changes necessary to the existing passes.
  10441. \section{Assignment and Lexically Scoped Functions}
  10442. \label{sec:assignment-scoping}
  10443. The addition of assignment raises a problem with our approach to
  10444. implementing lexically-scoped functions. Consider the following
  10445. example in which function \code{f} has a free variable \code{x} that
  10446. is changed after \code{f} is created but before the call to \code{f}.
  10447. % loop_test_11.rkt
  10448. \begin{lstlisting}
  10449. (let ([x 0])
  10450. (let ([y 0])
  10451. (let ([z 20])
  10452. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10453. (begin
  10454. (set! x 10)
  10455. (set! y 12)
  10456. (f y))))))
  10457. \end{lstlisting}
  10458. The correct output for this example is \code{42} because the call to
  10459. \code{f} is required to use the current value of \code{x} (which is
  10460. \code{10}). Unfortunately, the closure conversion pass
  10461. (Section~\ref{sec:closure-conversion}) generates code for the
  10462. \code{lambda} that copies the old value of \code{x} into a
  10463. closure. Thus, if we naively add support for assignment to our current
  10464. compiler, the output of this program would be \code{32}.
  10465. A first attempt at solving this problem would be to save a pointer to
  10466. \code{x} in the closure and change the occurrences of \code{x} inside
  10467. the lambda to dereference the pointer. Of course, this would require
  10468. assigning \code{x} to the stack and not to a register. However, the
  10469. problem goes a bit deeper. Consider the following example in which we
  10470. create a counter abstraction by creating a pair of functions that
  10471. share the free variable \code{x}.
  10472. % similar to loop_test_10.rkt
  10473. \begin{lstlisting}
  10474. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  10475. (vector
  10476. (lambda: () : Integer x)
  10477. (lambda: () : Void (set! x (+ 1 x)))))
  10478. (let ([counter (f 0)])
  10479. (let ([get (vector-ref counter 0)])
  10480. (let ([inc (vector-ref counter 1)])
  10481. (begin
  10482. (inc)
  10483. (get)))))
  10484. \end{lstlisting}
  10485. In this example, the lifetime of \code{x} extends beyond the lifetime
  10486. of the call to \code{f}. Thus, if we were to store \code{x} on the
  10487. stack frame for the call to \code{f}, it would be gone by the time we
  10488. call \code{inc} and \code{get}, leaving us with dangling pointers for
  10489. \code{x}. This example demonstrates that when a variable occurs free
  10490. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  10491. value of the variable needs to live on the heap. The verb ``box'' is
  10492. often used for allocating a single value on the heap, producing a
  10493. pointer, and ``unbox'' for dereferencing the pointer.
  10494. We recommend solving these problems by ``boxing'' the local variables
  10495. that are in the intersection of 1) variables that appear on the
  10496. left-hand-side of a \code{set!} and 2) variables that occur free
  10497. inside a \code{lambda}. We shall introduce a new pass named
  10498. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  10499. perform this translation. But before diving into the compiler passes,
  10500. we one more problem to discuss.
  10501. \section{Cyclic Control Flow and Dataflow Analysis}
  10502. \label{sec:dataflow-analysis}
  10503. Up until this point the control-flow graphs generated in
  10504. \code{explicate-control} were guaranteed to be acyclic. However, each
  10505. \code{while} loop introduces a cycle in the control-flow graph.
  10506. But does that matter?
  10507. %
  10508. Indeed it does. Recall that for register allocation, the compiler
  10509. performs liveness analysis to determine which variables can share the
  10510. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  10511. the control-flow graph in reverse topological order, but topological
  10512. order is only well-defined for acyclic graphs.
  10513. Let us return to the example of computing the sum of the first five
  10514. positive integers. Here is the program after instruction selection but
  10515. before register allocation.
  10516. \begin{center}
  10517. \begin{minipage}{0.45\textwidth}
  10518. \begin{lstlisting}
  10519. (define (main) : Integer
  10520. mainstart:
  10521. movq $0, sum1
  10522. movq $5, i2
  10523. jmp block5
  10524. block5:
  10525. movq i2, tmp3
  10526. cmpq tmp3, $0
  10527. jl block7
  10528. jmp block8
  10529. \end{lstlisting}
  10530. \end{minipage}
  10531. \begin{minipage}{0.45\textwidth}
  10532. \begin{lstlisting}
  10533. block7:
  10534. addq i2, sum1
  10535. movq $1, tmp4
  10536. negq tmp4
  10537. addq tmp4, i2
  10538. jmp block5
  10539. block8:
  10540. movq $27, %rax
  10541. addq sum1, %rax
  10542. jmp mainconclusion
  10543. )
  10544. \end{lstlisting}
  10545. \end{minipage}
  10546. \end{center}
  10547. Recall that liveness analysis works backwards, starting at the end
  10548. of each function. For this example we could start with \code{block8}
  10549. because we know what is live at the beginning of the conclusion,
  10550. just \code{rax} and \code{rsp}. So the live-before set
  10551. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  10552. %
  10553. Next we might try to analyze \code{block5} or \code{block7}, but
  10554. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10555. we are stuck.
  10556. The way out of this impasse comes from the realization that one can
  10557. perform liveness analysis starting with an empty live-after set to
  10558. compute an under-approximation of the live-before set. By
  10559. \emph{under-approximation}, we mean that the set only contains
  10560. variables that are really live, but it may be missing some. Next, the
  10561. under-approximations for each block can be improved by 1) updating the
  10562. live-after set for each block using the approximate live-before sets
  10563. from the other blocks and 2) perform liveness analysis again on each
  10564. block. In fact, by iterating this process, the under-approximations
  10565. eventually become the correct solutions!
  10566. %
  10567. This approach of iteratively analyzing a control-flow graph is
  10568. applicable to many static analysis problems and goes by the name
  10569. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  10570. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  10571. Washington.
  10572. Let us apply this approach to the above example. We use the empty set
  10573. for the initial live-before set for each block. Let $m_0$ be the
  10574. following mapping from label names to sets of locations (variables and
  10575. registers).
  10576. \begin{center}
  10577. \begin{lstlisting}
  10578. mainstart: {}
  10579. block5: {}
  10580. block7: {}
  10581. block8: {}
  10582. \end{lstlisting}
  10583. \end{center}
  10584. Using the above live-before approximations, we determine the
  10585. live-after for each block and then apply liveness analysis to each
  10586. block. This produces our next approximation $m_1$ of the live-before
  10587. sets.
  10588. \begin{center}
  10589. \begin{lstlisting}
  10590. mainstart: {}
  10591. block5: {i2}
  10592. block7: {i2, sum1}
  10593. block8: {rsp, sum1}
  10594. \end{lstlisting}
  10595. \end{center}
  10596. For the second round, the live-after for \code{mainstart} is the
  10597. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  10598. liveness analysis for \code{mainstart} computes the empty set. The
  10599. live-after for \code{block5} is the union of the live-before sets for
  10600. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  10601. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  10602. sum1\}}. The live-after for \code{block7} is the live-before for
  10603. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  10604. So the liveness analysis for \code{block7} remains \code{\{i2,
  10605. sum1\}}. Together these yield the following approximation $m_2$ of
  10606. the live-before sets.
  10607. \begin{center}
  10608. \begin{lstlisting}
  10609. mainstart: {}
  10610. block5: {i2, rsp, sum1}
  10611. block7: {i2, sum1}
  10612. block8: {rsp, sum1}
  10613. \end{lstlisting}
  10614. \end{center}
  10615. In the preceding iteration, only \code{block5} changed, so we can
  10616. limit our attention to \code{mainstart} and \code{block7}, the two
  10617. blocks that jump to \code{block5}. As a result, the live-before sets
  10618. for \code{mainstart} and \code{block7} are updated to include
  10619. \code{rsp}, yielding the following approximation $m_3$.
  10620. \begin{center}
  10621. \begin{lstlisting}
  10622. mainstart: {rsp}
  10623. block5: {i2, rsp, sum1}
  10624. block7: {i2, rsp, sum1}
  10625. block8: {rsp, sum1}
  10626. \end{lstlisting}
  10627. \end{center}
  10628. Because \code{block7} changed, we analyze \code{block5} once more, but
  10629. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  10630. our approximations have converged, so $m_3$ is the solution.
  10631. This iteration process is guaranteed to converge to a solution by the
  10632. Kleene Fixed-Point Theorem, a general theorem about functions on
  10633. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10634. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10635. elements, a least element $\bot$ (pronounced bottom), and a join
  10636. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  10637. ordering}\index{join}\footnote{Technically speaking, we will be
  10638. working with join semi-lattices.} When two elements are ordered $m_i
  10639. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  10640. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  10641. approximation than $m_i$. The bottom element $\bot$ represents the
  10642. complete lack of information, i.e., the worst approximation. The join
  10643. operator takes two lattice elements and combines their information,
  10644. i.e., it produces the least upper bound of the two.\index{least upper
  10645. bound}
  10646. A dataflow analysis typically involves two lattices: one lattice to
  10647. represent abstract states and another lattice that aggregates the
  10648. abstract states of all the blocks in the control-flow graph. For
  10649. liveness analysis, an abstract state is a set of locations. We form
  10650. the lattice $L$ by taking its elements to be sets of locations, the
  10651. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10652. set, and the join operator to be set union.
  10653. %
  10654. We form a second lattice $M$ by taking its elements to be mappings
  10655. from the block labels to sets of locations (elements of $L$). We
  10656. order the mappings point-wise, using the ordering of $L$. So given any
  10657. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10658. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10659. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10660. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  10661. We can think of one iteration of liveness analysis as being a function
  10662. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  10663. mapping.
  10664. \[
  10665. f(m_i) = m_{i+1}
  10666. \]
  10667. Next let us think for a moment about what a final solution $m_s$
  10668. should look like. If we perform liveness analysis using the solution
  10669. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10670. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  10671. \[
  10672. f(m_s) = m_s
  10673. \]
  10674. Furthermore, the solution should only include locations that are
  10675. forced to be there by performing liveness analysis on the program, so
  10676. the solution should be the \emph{least} fixed point.\index{least fixed point}
  10677. The Kleene Fixed-Point Theorem states that if a function $f$ is
  10678. monotone (better inputs produce better outputs), then the least fixed
  10679. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10680. chain} obtained by starting at $\bot$ and iterating $f$ as
  10681. follows.\index{Kleene Fixed-Point Theorem}
  10682. \[
  10683. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10684. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10685. \]
  10686. When a lattice contains only finitely-long ascending chains, then
  10687. every Kleene chain tops out at some fixed point after a number of
  10688. iterations of $f$. So that fixed point is also a least upper
  10689. bound of the chain.
  10690. \[
  10691. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10692. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10693. \]
  10694. The liveness analysis is indeed a monotone function and the lattice
  10695. $M$ only has finitely-long ascending chains because there are only a
  10696. finite number of variables and blocks in the program. Thus we are
  10697. guaranteed that iteratively applying liveness analysis to all blocks
  10698. in the program will eventually produce the least fixed point solution.
  10699. Next let us consider dataflow analysis in general and discuss the
  10700. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  10701. %
  10702. The algorithm has four parameters: the control-flow graph \code{G}, a
  10703. function \code{transfer} that applies the analysis to one block, the
  10704. \code{bottom} and \code{join} operator for the lattice of abstract
  10705. states. The algorithm begins by creating the bottom mapping,
  10706. represented by a hash table. It then pushes all of the nodes in the
  10707. control-flow graph onto the work list (a queue). The algorithm repeats
  10708. the \code{while} loop as long as there are items in the work list. In
  10709. each iteration, a node is popped from the work list and processed. The
  10710. \code{input} for the node is computed by taking the join of the
  10711. abstract states of all the predecessor nodes. The \code{transfer}
  10712. function is then applied to obtain the \code{output} abstract
  10713. state. If the output differs from the previous state for this block,
  10714. the mapping for this block is updated and its successor nodes are
  10715. pushed onto the work list.
  10716. \begin{figure}[tb]
  10717. \begin{lstlisting}
  10718. (define (analyze-dataflow G transfer bottom join)
  10719. (define mapping (make-hash))
  10720. (for ([v (in-vertices G)])
  10721. (dict-set! mapping v bottom))
  10722. (define worklist (make-queue))
  10723. (for ([v (in-vertices G)])
  10724. (enqueue! worklist v))
  10725. (define trans-G (transpose G))
  10726. (while (not (queue-empty? worklist))
  10727. (define node (dequeue! worklist))
  10728. (define input (for/fold ([state bottom])
  10729. ([pred (in-neighbors trans-G node)])
  10730. (join state (dict-ref mapping pred))))
  10731. (define output (transfer node input))
  10732. (cond [(not (equal? output (dict-ref mapping node)))
  10733. (dict-set! mapping node output)
  10734. (for ([v (in-neighbors G node)])
  10735. (enqueue! worklist v))]))
  10736. mapping)
  10737. \end{lstlisting}
  10738. \caption{Generic work list algorithm for dataflow analysis}
  10739. \label{fig:generic-dataflow}
  10740. \end{figure}
  10741. Having discussed the two complications that arise from adding support
  10742. for assignment and loops, we turn to discussing the one new compiler
  10743. pass and the significant changes to existing passes.
  10744. \section{Convert Assignments}
  10745. \label{sec:convert-assignments}
  10746. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10747. the combination of assignments and lexically-scoped functions requires
  10748. that we box those variables that are both assigned-to and that appear
  10749. free inside a \code{lambda}. The purpose of the
  10750. \code{convert-assignments} pass is to carry out that transformation.
  10751. We recommend placing this pass after \code{uniquify} but before
  10752. \code{reveal-functions}.
  10753. Consider again the first example from
  10754. Section~\ref{sec:assignment-scoping}:
  10755. \begin{lstlisting}
  10756. (let ([x 0])
  10757. (let ([y 0])
  10758. (let ([z 20])
  10759. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10760. (begin
  10761. (set! x 10)
  10762. (set! y 12)
  10763. (f y))))))
  10764. \end{lstlisting}
  10765. The variables \code{x} and \code{y} are assigned-to. The variables
  10766. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10767. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10768. The boxing of \code{x} consists of three transformations: initialize
  10769. \code{x} with a vector, replace reads from \code{x} with
  10770. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10771. \code{vector-set!}. The output of \code{convert-assignments} for this
  10772. example is as follows.
  10773. \begin{lstlisting}
  10774. (define (main) : Integer
  10775. (let ([x0 (vector 0)])
  10776. (let ([y1 0])
  10777. (let ([z2 20])
  10778. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10779. (+ a3 (+ (vector-ref x0 0) z2)))])
  10780. (begin
  10781. (vector-set! x0 0 10)
  10782. (set! y1 12)
  10783. (f4 y1)))))))
  10784. \end{lstlisting}
  10785. \paragraph{Assigned \& Free}
  10786. We recommend defining an auxiliary function named
  10787. \code{assigned\&free} that takes an expression and simultaneously
  10788. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10789. that occur free within lambda's, and 3) a new version of the
  10790. expression that records which bound variables occurred in the
  10791. intersection of $A$ and $F$. You can use the struct
  10792. \code{AssignedFree} to do this. Consider the case for
  10793. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10794. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10795. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10796. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10797. \begin{lstlisting}
  10798. (Let |$x$| |$rhs$| |$body$|)
  10799. |$\Rightarrow$|
  10800. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10801. \end{lstlisting}
  10802. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10803. The set of assigned variables for this \code{Let} is
  10804. $A_r \cup (A_b - \{x\})$
  10805. and the set of variables free in lambda's is
  10806. $F_r \cup (F_b - \{x\})$.
  10807. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10808. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10809. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10810. and $F_r$.
  10811. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10812. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10813. recursively processing \itm{body}. Wrap each of parameter that occurs
  10814. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10815. Let $P$ be the set of parameter names in \itm{params}. The result is
  10816. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10817. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10818. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10819. \paragraph{Convert Assignments}
  10820. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10821. functions for expressions and definitions. The function for
  10822. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10823. set of assigned-and-free variables (obtained from the result of
  10824. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10825. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10826. \code{vector-ref}.
  10827. \begin{lstlisting}
  10828. (Var |$x$|)
  10829. |$\Rightarrow$|
  10830. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10831. \end{lstlisting}
  10832. %
  10833. In the case for $\LET{\LP\code{AssignedFree}\,
  10834. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10835. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10836. \itm{body'} but with $x$ added to the set of assigned-and-free
  10837. variables. Translate the let-expression as follows to bind $x$ to a
  10838. boxed value.
  10839. \begin{lstlisting}
  10840. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10841. |$\Rightarrow$|
  10842. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10843. \end{lstlisting}
  10844. %
  10845. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10846. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10847. variables, translate the \code{set!} into a \code{vector-set!}
  10848. as follows.
  10849. \begin{lstlisting}
  10850. (SetBang |$x$| |$\itm{rhs}$|)
  10851. |$\Rightarrow$|
  10852. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10853. \end{lstlisting}
  10854. %
  10855. The case for \code{Lambda} is non-trivial, but it is similar to the
  10856. case for function definitions, which we discuss next.
  10857. The auxiliary function for definitions, \code{cnvt-assign-def},
  10858. applies assignment conversion to function definitions.
  10859. We translate a function definition as follows.
  10860. \begin{lstlisting}
  10861. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10862. |$\Rightarrow$|
  10863. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10864. \end{lstlisting}
  10865. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10866. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10867. \code{assigned\&free} on $\itm{body_1}$.
  10868. Let $P$ be the parameter names in \itm{params}.
  10869. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10870. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10871. as the set of assigned-and-free variables.
  10872. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10873. in a sequence of let-expressions that box the parameters
  10874. that are in $A_b \cap F_b$.
  10875. %
  10876. Regarding \itm{params'}, change the names of the parameters that are
  10877. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10878. variables can retain the original names). Recall the second example in
  10879. Section~\ref{sec:assignment-scoping} involving a counter
  10880. abstraction. The following is the output of assignment version for
  10881. function \code{f}.
  10882. \begin{lstlisting}
  10883. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10884. (vector
  10885. (lambda: () : Integer x1)
  10886. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10887. |$\Rightarrow$|
  10888. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10889. (let ([x1 (vector param_x1)])
  10890. (vector (lambda: () : Integer (vector-ref x1 0))
  10891. (lambda: () : Void
  10892. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10893. \end{lstlisting}
  10894. \section{Remove Complex Operands}
  10895. \label{sec:rco-loop}
  10896. The three new language forms, \code{while}, \code{set!}, and
  10897. \code{begin} are all complex expressions and their subexpressions are
  10898. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10899. output language \LangFunANF{} of this pass.
  10900. \begin{figure}[tp]
  10901. \centering
  10902. \fbox{
  10903. \begin{minipage}{0.96\textwidth}
  10904. \small
  10905. \[
  10906. \begin{array}{rcl}
  10907. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10908. \mid \VOID{} } \\
  10909. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10910. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10911. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10912. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10913. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10914. \end{array}
  10915. \]
  10916. \end{minipage}
  10917. }
  10918. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10919. \label{fig:Rwhile-anf-syntax}
  10920. \end{figure}
  10921. As usual, when a complex expression appears in a grammar position that
  10922. needs to be atomic, such as the argument of a primitive operator, we
  10923. must introduce a temporary variable and bind it to the complex
  10924. expression. This approach applies, unchanged, to handle the new
  10925. language forms. For example, in the following code there are two
  10926. \code{begin} expressions appearing as arguments to \code{+}. The
  10927. output of \code{rco-exp} is shown below, in which the \code{begin}
  10928. expressions have been bound to temporary variables. Recall that
  10929. \code{let} expressions in \LangLoopANF{} are allowed to have
  10930. arbitrary expressions in their right-hand-side expression, so it is
  10931. fine to place \code{begin} there.
  10932. \begin{lstlisting}
  10933. (let ([x0 10])
  10934. (let ([y1 0])
  10935. (+ (+ (begin (set! y1 (read)) x0)
  10936. (begin (set! x0 (read)) y1))
  10937. x0)))
  10938. |$\Rightarrow$|
  10939. (let ([x0 10])
  10940. (let ([y1 0])
  10941. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10942. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10943. (let ([tmp4 (+ tmp2 tmp3)])
  10944. (+ tmp4 x0))))))
  10945. \end{lstlisting}
  10946. \section{Explicate Control and \LangCLoop{}}
  10947. \label{sec:explicate-loop}
  10948. Recall that in the \code{explicate-control} pass we define one helper
  10949. function for each kind of position in the program. For the \LangVar{}
  10950. language of integers and variables we needed kinds of positions:
  10951. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10952. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10953. yet another kind of position: effect position. Except for the last
  10954. subexpression, the subexpressions inside a \code{begin} are evaluated
  10955. only for their effect. Their result values are discarded. We can
  10956. generate better code by taking this fact into account.
  10957. The output language of \code{explicate-control} is \LangCLoop{}
  10958. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10959. \LangCLam{}. The only syntactic difference is that \code{Call},
  10960. \code{vector-set!}, and \code{read} may also appear as statements.
  10961. The most significant difference between \LangCLam{} and \LangCLoop{}
  10962. is that the control-flow graphs of the later may contain cycles.
  10963. \begin{figure}[tp]
  10964. \fbox{
  10965. \begin{minipage}{0.96\textwidth}
  10966. \small
  10967. \[
  10968. \begin{array}{lcl}
  10969. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10970. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10971. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10972. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10973. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10974. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10975. \end{array}
  10976. \]
  10977. \end{minipage}
  10978. }
  10979. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10980. \label{fig:c7-syntax}
  10981. \end{figure}
  10982. The new auxiliary function \code{explicate-effect} takes an expression
  10983. (in an effect position) and a promise of a continuation block. The
  10984. function returns a promise for a $\Tail$ that includes the generated
  10985. code for the input expression followed by the continuation block. If
  10986. the expression is obviously pure, that is, never causes side effects,
  10987. then the expression can be removed, so the result is just the
  10988. continuation block.
  10989. %
  10990. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10991. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10992. the loop. Recursively process the \itm{body} (in effect position)
  10993. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10994. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10995. \itm{body'} as the then-branch and the continuation block as the
  10996. else-branch. The result should be added to the control-flow graph with
  10997. the label \itm{loop}. The result for the whole \code{while} loop is a
  10998. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10999. added to the control-flow graph if the loop is indeed used, which can
  11000. be accomplished using \code{delay}.
  11001. The auxiliary functions for tail, assignment, and predicate positions
  11002. need to be updated. The three new language forms, \code{while},
  11003. \code{set!}, and \code{begin}, can appear in assignment and tail
  11004. positions. Only \code{begin} may appear in predicate positions; the
  11005. other two have result type \code{Void}.
  11006. \section{Select Instructions}
  11007. \label{sec:select-instructions-loop}
  11008. Only three small additions are needed in the
  11009. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  11010. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  11011. stand-alone statements instead of only appearing on the right-hand
  11012. side of an assignment statement. The code generation is nearly
  11013. identical; just leave off the instruction for moving the result into
  11014. the left-hand side.
  11015. \section{Register Allocation}
  11016. \label{sec:register-allocation-loop}
  11017. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  11018. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11019. which complicates the liveness analysis needed for register
  11020. allocation.
  11021. \subsection{Liveness Analysis}
  11022. \label{sec:liveness-analysis-r8}
  11023. We recommend using the generic \code{analyze-dataflow} function that
  11024. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  11025. perform liveness analysis, replacing the code in
  11026. \code{uncover-live-CFG} that processed the basic blocks in topological
  11027. order (Section~\ref{sec:liveness-analysis-Rif}).
  11028. The \code{analyze-dataflow} function has four parameters.
  11029. \begin{enumerate}
  11030. \item The first parameter \code{G} should be a directed graph from the
  11031. \code{racket/graph} package (see the sidebar in
  11032. Section~\ref{sec:build-interference}) that represents the
  11033. control-flow graph.
  11034. \item The second parameter \code{transfer} is a function that applies
  11035. liveness analysis to a basic block. It takes two parameters: the
  11036. label for the block to analyze and the live-after set for that
  11037. block. The transfer function should return the live-before set for
  11038. the block. Also, as a side-effect, it should update the block's
  11039. $\itm{info}$ with the liveness information for each instruction. To
  11040. implement the \code{transfer} function, you should be able to reuse
  11041. the code you already have for analyzing basic blocks.
  11042. \item The third and fourth parameters of \code{analyze-dataflow} are
  11043. \code{bottom} and \code{join} for the lattice of abstract states,
  11044. i.e. sets of locations. The bottom of the lattice is the empty set
  11045. \code{(set)} and the join operator is \code{set-union}.
  11046. \end{enumerate}
  11047. \begin{figure}[p]
  11048. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11049. \node (Rfun) at (0,2) {\large \LangLoop{}};
  11050. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  11051. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  11052. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  11053. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  11054. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  11055. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  11056. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  11057. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  11058. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  11059. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11060. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11061. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11062. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11063. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11064. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11065. %% \path[->,bend left=15] (Rfun) edge [above] node
  11066. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  11067. \path[->,bend left=15] (Rfun) edge [above] node
  11068. {\ttfamily\footnotesize shrink} (Rfun-2);
  11069. \path[->,bend left=15] (Rfun-2) edge [above] node
  11070. {\ttfamily\footnotesize uniquify} (Rfun-3);
  11071. \path[->,bend left=15] (Rfun-3) edge [above] node
  11072. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  11073. \path[->,bend left=15] (Rfun-4) edge [right] node
  11074. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11075. \path[->,bend left=15] (F1-1) edge [below] node
  11076. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11077. \path[->,bend right=15] (F1-2) edge [above] node
  11078. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11079. \path[->,bend right=15] (F1-3) edge [above] node
  11080. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11081. \path[->,bend right=15] (F1-4) edge [above] node
  11082. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11083. \path[->,bend right=15] (F1-5) edge [right] node
  11084. {\ttfamily\footnotesize explicate-control} (C3-2);
  11085. \path[->,bend left=15] (C3-2) edge [left] node
  11086. {\ttfamily\footnotesize select-instr.} (x86-2);
  11087. \path[->,bend right=15] (x86-2) edge [left] node
  11088. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11089. \path[->,bend right=15] (x86-2-1) edge [below] node
  11090. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11091. \path[->,bend right=15] (x86-2-2) edge [left] node
  11092. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11093. \path[->,bend left=15] (x86-3) edge [above] node
  11094. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11095. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11096. \end{tikzpicture}
  11097. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  11098. \label{fig:Rwhile-passes}
  11099. \end{figure}
  11100. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  11101. for the compilation of \LangLoop{}.
  11102. \section{Challenge: Arrays}
  11103. \label{sec:arrays}
  11104. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  11105. elements whose length is determined at compile-time and where each
  11106. element of a tuple may have a different type (they are
  11107. heterogeous). This challenge is also about sequences, but this time
  11108. the length is determined at run-time and all the elements have the same
  11109. type (they are homogeneous). We use the term ``array'' for this later
  11110. kind of sequence.
  11111. The Racket language does not distinguish between tuples and arrays,
  11112. they are both represented by vectors. However, Typed Racket
  11113. distinguishes between tuples and arrays: the \code{Vector} type is for
  11114. tuples and the \code{Vectorof} type is for arrays.
  11115. %
  11116. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  11117. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11118. and the \code{make-vector} primitive operator for creating an array,
  11119. whose arguments are the length of the array and an initial value for
  11120. all the elements in the array. The \code{vector-length},
  11121. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11122. for tuples become overloaded for use with arrays.
  11123. %
  11124. We also include integer multiplication in \LangArray{}, as it is
  11125. useful in many examples involving arrays such as computing the
  11126. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11127. \begin{figure}[tp]
  11128. \centering
  11129. \fbox{
  11130. \begin{minipage}{0.96\textwidth}
  11131. \small
  11132. \[
  11133. \begin{array}{lcl}
  11134. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  11135. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  11136. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  11137. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  11138. &\mid& \gray{\key{\#t} \mid \key{\#f}
  11139. \mid \LP\key{and}\;\Exp\;\Exp\RP
  11140. \mid \LP\key{or}\;\Exp\;\Exp\RP
  11141. \mid \LP\key{not}\;\Exp\RP } \\
  11142. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  11143. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  11144. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11145. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  11146. \mid \LP\Exp \; \Exp\ldots\RP } \\
  11147. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11148. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11149. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  11150. \mid \CBEGIN{\Exp\ldots}{\Exp}
  11151. \mid \CWHILE{\Exp}{\Exp} } \\
  11152. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  11153. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11154. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11155. \end{array}
  11156. \]
  11157. \end{minipage}
  11158. }
  11159. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11160. \label{fig:Rvecof-concrete-syntax}
  11161. \end{figure}
  11162. \begin{figure}[tp]
  11163. \begin{lstlisting}
  11164. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11165. [n : Integer]) : Integer
  11166. (let ([i 0])
  11167. (let ([prod 0])
  11168. (begin
  11169. (while (< i n)
  11170. (begin
  11171. (set! prod (+ prod (* (vector-ref A i)
  11172. (vector-ref B i))))
  11173. (set! i (+ i 1))
  11174. ))
  11175. prod))))
  11176. (let ([A (make-vector 2 2)])
  11177. (let ([B (make-vector 2 3)])
  11178. (+ (inner-product A B 2)
  11179. 30)))
  11180. \end{lstlisting}
  11181. \caption{Example program that computes the inner-product.}
  11182. \label{fig:inner-product}
  11183. \end{figure}
  11184. The type checker for \LangArray{} is define in
  11185. Figure~\ref{fig:type-check-Rvecof}. The result type of
  11186. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11187. of the intializing expression. The length expression is required to
  11188. have type \code{Integer}. The type checking of the operators
  11189. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11190. updated to handle the situation where the vector has type
  11191. \code{Vectorof}. In these cases we translate the operators to their
  11192. \code{vectorof} form so that later passes can easily distinguish
  11193. between operations on tuples versus arrays. We override the
  11194. \code{operator-types} method to provide the type signature for
  11195. multiplication: it takes two integers and returns an integer. To
  11196. support injection and projection of arrays to the \code{Any} type
  11197. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11198. predicate.
  11199. \begin{figure}[tbp]
  11200. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11201. (define type-check-Rvecof-class
  11202. (class type-check-Rwhile-class
  11203. (super-new)
  11204. (inherit check-type-equal?)
  11205. (define/override (flat-ty? ty)
  11206. (match ty
  11207. ['(Vectorof Any) #t]
  11208. [else (super flat-ty? ty)]))
  11209. (define/override (operator-types)
  11210. (append '((* . ((Integer Integer) . Integer)))
  11211. (super operator-types)))
  11212. (define/override (type-check-exp env)
  11213. (lambda (e)
  11214. (define recur (type-check-exp env))
  11215. (match e
  11216. [(Prim 'make-vector (list e1 e2))
  11217. (define-values (e1^ t1) (recur e1))
  11218. (define-values (e2^ elt-type) (recur e2))
  11219. (define vec-type `(Vectorof ,elt-type))
  11220. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11221. vec-type)]
  11222. [(Prim 'vector-ref (list e1 e2))
  11223. (define-values (e1^ t1) (recur e1))
  11224. (define-values (e2^ t2) (recur e2))
  11225. (match* (t1 t2)
  11226. [(`(Vectorof ,elt-type) 'Integer)
  11227. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11228. [(other wise) ((super type-check-exp env) e)])]
  11229. [(Prim 'vector-set! (list e1 e2 e3) )
  11230. (define-values (e-vec t-vec) (recur e1))
  11231. (define-values (e2^ t2) (recur e2))
  11232. (define-values (e-arg^ t-arg) (recur e3))
  11233. (match t-vec
  11234. [`(Vectorof ,elt-type)
  11235. (check-type-equal? elt-type t-arg e)
  11236. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11237. [else ((super type-check-exp env) e)])]
  11238. [(Prim 'vector-length (list e1))
  11239. (define-values (e1^ t1) (recur e1))
  11240. (match t1
  11241. [`(Vectorof ,t)
  11242. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11243. [else ((super type-check-exp env) e)])]
  11244. [else ((super type-check-exp env) e)])))
  11245. ))
  11246. (define (type-check-Rvecof p)
  11247. (send (new type-check-Rvecof-class) type-check-program p))
  11248. \end{lstlisting}
  11249. \caption{Type checker for the \LangArray{} language.}
  11250. \label{fig:type-check-Rvecof}
  11251. \end{figure}
  11252. The interpreter for \LangArray{} is defined in
  11253. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  11254. implemented with Racket's \code{make-vector} function and
  11255. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11256. integers.
  11257. \begin{figure}[tbp]
  11258. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11259. (define interp-Rvecof-class
  11260. (class interp-Rwhile-class
  11261. (super-new)
  11262. (define/override (interp-op op)
  11263. (verbose "Rvecof/interp-op" op)
  11264. (match op
  11265. ['make-vector make-vector]
  11266. ['* fx*]
  11267. [else (super interp-op op)]))
  11268. ))
  11269. (define (interp-Rvecof p)
  11270. (send (new interp-Rvecof-class) interp-program p))
  11271. \end{lstlisting}
  11272. \caption{Interpreter for \LangArray{}.}
  11273. \label{fig:interp-Rvecof}
  11274. \end{figure}
  11275. \subsection{Data Representation}
  11276. \label{sec:array-rep}
  11277. Just like tuples, we store arrays on the heap which means that the
  11278. garbage collector will need to inspect arrays. An immediate thought is
  11279. to use the same representation for arrays that we use for tuples.
  11280. However, we limit tuples to a length of $50$ so that their length and
  11281. pointer mask can fit into the 64-bit tag at the beginning of each
  11282. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11283. millions of elements, so we need more bits to store the length.
  11284. However, because arrays are homogeneous, we only need $1$ bit for the
  11285. pointer mask instead of one bit per array elements. Finally, the
  11286. garbage collector will need to be able to distinguish between tuples
  11287. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11288. arrive at the following layout for the 64-bit tag at the beginning of
  11289. an array:
  11290. \begin{itemize}
  11291. \item The right-most bit is the forwarding bit, just like in a tuple.
  11292. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11293. it is not.
  11294. \item The next bit to the left is the pointer mask. A $0$ indicates
  11295. that none of the elements are pointers to the heap and a $1$
  11296. indicates that all of the elements are pointers.
  11297. \item The next $61$ bits store the length of the array.
  11298. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11299. array ($1$).
  11300. \end{itemize}
  11301. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11302. differentiate the kinds of values that have been injected into the
  11303. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11304. to indicate that the value is an array.
  11305. In the following subsections we provide hints regarding how to update
  11306. the passes to handle arrays.
  11307. \subsection{Reveal Casts}
  11308. The array-access operators \code{vectorof-ref} and
  11309. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11310. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11311. that the type checker cannot tell whether the index will be in bounds,
  11312. so the bounds check must be performed at run time. Recall that the
  11313. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11314. an \code{If} arround a vector reference for update to check whether
  11315. the index is less than the length. You should do the same for
  11316. \code{vectorof-ref} and \code{vectorof-set!} .
  11317. In addition, the handling of the \code{any-vector} operators in
  11318. \code{reveal-casts} needs to be updated to account for arrays that are
  11319. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11320. generated code should test whether the tag is for tuples (\code{010})
  11321. or arrays (\code{110}) and then dispatch to either
  11322. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11323. we add a case in \code{select-instructions} to generate the
  11324. appropriate instructions for accessing the array length from the
  11325. header of an array.
  11326. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11327. the generated code needs to check that the index is less than the
  11328. vector length, so like the code for \code{any-vector-length}, check
  11329. the tag to determine whether to use \code{any-vector-length} or
  11330. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11331. is complete, the generated code can use \code{any-vector-ref} and
  11332. \code{any-vector-set!} for both tuples and arrays because the
  11333. instructions used for those operators do not look at the tag at the
  11334. front of the tuple or array.
  11335. \subsection{Expose Allocation}
  11336. This pass should translate the \code{make-vector} operator into
  11337. lower-level operations. In particular, the new AST node
  11338. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11339. length specified by the $\Exp$, but does not initialize the elements
  11340. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11341. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11342. element type for the array. Regarding the initialization of the array,
  11343. we recommend generated a \code{while} loop that uses
  11344. \code{vector-set!} to put the initializing value into every element of
  11345. the array.
  11346. \subsection{Remove Complex Operands}
  11347. Add cases in the \code{rco-atom} and \code{rco-exp} for
  11348. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11349. complex and its subexpression must be atomic.
  11350. \subsection{Explicate Control}
  11351. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  11352. \code{explicate-assign}.
  11353. \subsection{Select Instructions}
  11354. Generate instructions for \code{AllocateArray} similar to those for
  11355. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11356. that the tag at the front of the array should instead use the
  11357. representation discussed in Section~\ref{sec:array-rep}.
  11358. Regarding \code{vectorof-length}, extract the length from the tag
  11359. according to the representation discussed in
  11360. Section~\ref{sec:array-rep}.
  11361. The instructions generated for \code{vectorof-ref} differ from those
  11362. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11363. that the index is not a constant so the offset must be computed at
  11364. runtime, similar to the instructions generated for
  11365. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11366. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11367. appear in an assignment and as a stand-alone statement, so make sure
  11368. to handle both situations in this pass.
  11369. Finally, the instructions for \code{any-vectorof-length} should be
  11370. similar to those for \code{vectorof-length}, except that one must
  11371. first project the array by writing zeroes into the $3$-bit tag
  11372. \begin{exercise}\normalfont
  11373. Implement a compiler for the \LangArray{} language by extending your
  11374. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11375. programs, including the one in Figure~\ref{fig:inner-product} and also
  11376. a program that multiplies two matrices. Note that matrices are
  11377. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11378. arrays by laying out each row in the array, one after the next.
  11379. \end{exercise}
  11380. % Further Reading: dataflow analysis
  11381. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11382. \chapter{Gradual Typing}
  11383. \label{ch:Rgrad}
  11384. \index{gradual typing}
  11385. This chapter studies a language, \LangGrad{}, in which the programmer
  11386. can choose between static and dynamic type checking in different parts
  11387. of a program, thereby mixing the statically typed \LangLoop{} language
  11388. with the dynamically typed \LangDyn{}. There are several approaches to
  11389. mixing static and dynamic typing, including multi-language
  11390. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  11391. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  11392. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  11393. programmer controls the amount of static versus dynamic checking by
  11394. adding or removing type annotations on parameters and
  11395. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  11396. %
  11397. The concrete syntax of \LangGrad{} is defined in
  11398. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  11399. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  11400. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  11401. non-terminals that make type annotations optional. The return types
  11402. are not optional in the abstract syntax; the parser fills in
  11403. \code{Any} when the return type is not specified in the concrete
  11404. syntax.
  11405. \begin{figure}[tp]
  11406. \centering
  11407. \fbox{
  11408. \begin{minipage}{0.96\textwidth}
  11409. \small
  11410. \[
  11411. \begin{array}{lcl}
  11412. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  11413. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  11414. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  11415. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  11416. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  11417. &\mid& \gray{\key{\#t} \mid \key{\#f}
  11418. \mid (\key{and}\;\Exp\;\Exp)
  11419. \mid (\key{or}\;\Exp\;\Exp)
  11420. \mid (\key{not}\;\Exp) } \\
  11421. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  11422. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  11423. (\key{vector-ref}\;\Exp\;\Int)} \\
  11424. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  11425. \mid (\Exp \; \Exp\ldots) } \\
  11426. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  11427. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  11428. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  11429. \mid \CBEGIN{\Exp\ldots}{\Exp}
  11430. \mid \CWHILE{\Exp}{\Exp} } \\
  11431. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  11432. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  11433. \end{array}
  11434. \]
  11435. \end{minipage}
  11436. }
  11437. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11438. \label{fig:Rgrad-concrete-syntax}
  11439. \end{figure}
  11440. \begin{figure}[tp]
  11441. \centering
  11442. \fbox{
  11443. \begin{minipage}{0.96\textwidth}
  11444. \small
  11445. \[
  11446. \begin{array}{lcl}
  11447. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  11448. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  11449. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11450. &\mid& \gray{ \BOOL{\itm{bool}}
  11451. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  11452. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  11453. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  11454. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  11455. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  11456. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  11457. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  11458. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11459. \end{array}
  11460. \]
  11461. \end{minipage}
  11462. }
  11463. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11464. \label{fig:Rgrad-syntax}
  11465. \end{figure}
  11466. Both the type checker and the interpreter for \LangGrad{} require some
  11467. interesting changes to enable gradual typing, which we discuss in the
  11468. next two sections in the context of the \code{map-vec} example from
  11469. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  11470. revised the \code{map-vec} example, omitting the type annotations from
  11471. the \code{add1} function.
  11472. \begin{figure}[btp]
  11473. % gradual_test_9.rkt
  11474. \begin{lstlisting}
  11475. (define (map-vec [f : (Integer -> Integer)]
  11476. [v : (Vector Integer Integer)])
  11477. : (Vector Integer Integer)
  11478. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11479. (define (add1 x) (+ x 1))
  11480. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11481. \end{lstlisting}
  11482. \caption{A partially-typed version of the \code{map-vec} example.}
  11483. \label{fig:gradual-map-vec}
  11484. \end{figure}
  11485. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  11486. \label{sec:gradual-type-check}
  11487. The type checker for \LangGrad{} uses the \code{Any} type for missing
  11488. parameter and return types. For example, the \code{x} parameter of
  11489. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  11490. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  11491. consider the \code{+} operator inside \code{add1}. It expects both
  11492. arguments to have type \code{Integer}, but its first argument \code{x}
  11493. has type \code{Any}. In a gradually typed language, such differences
  11494. are allowed so long as the types are \emph{consistent}, that is, they
  11495. are equal except in places where there is an \code{Any} type. The type
  11496. \code{Any} is consistent with every other type.
  11497. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  11498. \begin{figure}[tbp]
  11499. \begin{lstlisting}
  11500. (define/public (consistent? t1 t2)
  11501. (match* (t1 t2)
  11502. [('Integer 'Integer) #t]
  11503. [('Boolean 'Boolean) #t]
  11504. [('Void 'Void) #t]
  11505. [('Any t2) #t]
  11506. [(t1 'Any) #t]
  11507. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11508. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  11509. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11510. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  11511. (consistent? rt1 rt2))]
  11512. [(other wise) #f]))
  11513. \end{lstlisting}
  11514. \caption{The consistency predicate on types.}
  11515. \label{fig:consistent}
  11516. \end{figure}
  11517. Returning to the \code{map-vec} example of
  11518. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  11519. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  11520. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  11521. because the two types are consistent. In particular, \code{->} is
  11522. equal to \code{->} and because \code{Any} is consistent with
  11523. \code{Integer}.
  11524. Next consider a program with an error, such as applying the
  11525. \code{map-vec} to a function that sometimes returns a Boolean, as
  11526. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  11527. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  11528. consistent with the type of parameter \code{f} of \code{map-vec}, that
  11529. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  11530. Integer)}. One might say that a gradual type checker is optimistic
  11531. in that it accepts programs that might execute without a runtime type
  11532. error.
  11533. %
  11534. Unfortunately, running this program with input \code{1} triggers an
  11535. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  11536. performs checking at runtime to ensure the integrity of the static
  11537. types, such as the \code{(Integer -> Integer)} annotation on parameter
  11538. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  11539. new \code{Cast} form that is inserted by the type checker. Thus, the
  11540. output of the type checker is a program in the \LangCast{} language, which
  11541. adds \code{Cast} to \LangLoop{}, as shown in
  11542. Figure~\ref{fig:Rgrad-prime-syntax}.
  11543. \begin{figure}[tp]
  11544. \centering
  11545. \fbox{
  11546. \begin{minipage}{0.96\textwidth}
  11547. \small
  11548. \[
  11549. \begin{array}{lcl}
  11550. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  11551. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11552. \end{array}
  11553. \]
  11554. \end{minipage}
  11555. }
  11556. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11557. \label{fig:Rgrad-prime-syntax}
  11558. \end{figure}
  11559. \begin{figure}[tbp]
  11560. \begin{lstlisting}
  11561. (define (map-vec [f : (Integer -> Integer)]
  11562. [v : (Vector Integer Integer)])
  11563. : (Vector Integer Integer)
  11564. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11565. (define (add1 x) (+ x 1))
  11566. (define (true) #t)
  11567. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  11568. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  11569. \end{lstlisting}
  11570. \caption{A variant of the \code{map-vec} example with an error.}
  11571. \label{fig:map-vec-maybe-add1}
  11572. \end{figure}
  11573. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  11574. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  11575. inserted every time the type checker sees two types that are
  11576. consistent but not equal. In the \code{add1} function, \code{x} is
  11577. cast to \code{Integer} and the result of the \code{+} is cast to
  11578. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  11579. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  11580. \begin{figure}[btp]
  11581. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11582. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  11583. : (Vector Integer Integer)
  11584. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11585. (define (add1 [x : Any]) : Any
  11586. (cast (+ (cast x Any Integer) 1) Integer Any))
  11587. (define (true) : Any (cast #t Boolean Any))
  11588. (define (maybe-add1 [x : Any]) : Any
  11589. (if (eq? 0 (read)) (add1 x) (true)))
  11590. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  11591. (vector 0 41)) 0)
  11592. \end{lstlisting}
  11593. \caption{Output of type checking \code{map-vec}
  11594. and \code{maybe-add1}.}
  11595. \label{fig:map-vec-cast}
  11596. \end{figure}
  11597. The type checker for \LangGrad{} is defined in
  11598. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  11599. and \ref{fig:type-check-Rgradual-3}.
  11600. \begin{figure}[tbp]
  11601. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11602. (define type-check-gradual-class
  11603. (class type-check-Rwhile-class
  11604. (super-new)
  11605. (inherit operator-types type-predicates)
  11606. (define/override (type-check-exp env)
  11607. (lambda (e)
  11608. (define recur (type-check-exp env))
  11609. (match e
  11610. [(Prim 'vector-length (list e1))
  11611. (define-values (e1^ t) (recur e1))
  11612. (match t
  11613. [`(Vector ,ts ...)
  11614. (values (Prim 'vector-length (list e1^)) 'Integer)]
  11615. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  11616. [(Prim 'vector-ref (list e1 e2))
  11617. (define-values (e1^ t1) (recur e1))
  11618. (define-values (e2^ t2) (recur e2))
  11619. (check-consistent? t2 'Integer e)
  11620. (match t1
  11621. [`(Vector ,ts ...)
  11622. (match e2^
  11623. [(Int i)
  11624. (unless (and (0 . <= . i) (i . < . (length ts)))
  11625. (error 'type-check "invalid index ~a in ~a" i e))
  11626. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11627. [else (define e1^^ (make-cast e1^ t1 'Any))
  11628. (define e2^^ (make-cast e2^ t2 'Integer))
  11629. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  11630. ['Any
  11631. (define e2^^ (make-cast e2^ t2 'Integer))
  11632. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  11633. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11634. [(Prim 'vector-set! (list e1 e2 e3) )
  11635. (define-values (e1^ t1) (recur e1))
  11636. (define-values (e2^ t2) (recur e2))
  11637. (define-values (e3^ t3) (recur e3))
  11638. (check-consistent? t2 'Integer e)
  11639. (match t1
  11640. [`(Vector ,ts ...)
  11641. (match e2^
  11642. [(Int i)
  11643. (unless (and (0 . <= . i) (i . < . (length ts)))
  11644. (error 'type-check "invalid index ~a in ~a" i e))
  11645. (check-consistent? (list-ref ts i) t3 e)
  11646. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  11647. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  11648. [else
  11649. (define e1^^ (make-cast e1^ t1 'Any))
  11650. (define e2^^ (make-cast e2^ t2 'Integer))
  11651. (define e3^^ (make-cast e3^ t3 'Any))
  11652. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  11653. ['Any
  11654. (define e2^^ (make-cast e2^ t2 'Integer))
  11655. (define e3^^ (make-cast e3^ t3 'Any))
  11656. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  11657. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11658. \end{lstlisting}
  11659. \caption{Type checker for the \LangGrad{} language, part 1.}
  11660. \label{fig:type-check-Rgradual-1}
  11661. \end{figure}
  11662. \begin{figure}[tbp]
  11663. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11664. [(Prim 'eq? (list e1 e2))
  11665. (define-values (e1^ t1) (recur e1))
  11666. (define-values (e2^ t2) (recur e2))
  11667. (check-consistent? t1 t2 e)
  11668. (define T (meet t1 t2))
  11669. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  11670. 'Boolean)]
  11671. [(Prim 'not (list e1))
  11672. (define-values (e1^ t1) (recur e1))
  11673. (match t1
  11674. ['Any
  11675. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  11676. (Bool #t) (Bool #f)))]
  11677. [else
  11678. (define-values (t-ret new-es^)
  11679. (type-check-op 'not (list t1) (list e1^) e))
  11680. (values (Prim 'not new-es^) t-ret)])]
  11681. [(Prim 'and (list e1 e2))
  11682. (recur (If e1 e2 (Bool #f)))]
  11683. [(Prim 'or (list e1 e2))
  11684. (define tmp (gensym 'tmp))
  11685. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  11686. [(Prim op es)
  11687. #:when (not (set-member? explicit-prim-ops op))
  11688. (define-values (new-es ts)
  11689. (for/lists (exprs types) ([e es])
  11690. (recur e)))
  11691. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  11692. (values (Prim op new-es^) t-ret)]
  11693. [(If e1 e2 e3)
  11694. (define-values (e1^ T1) (recur e1))
  11695. (define-values (e2^ T2) (recur e2))
  11696. (define-values (e3^ T3) (recur e3))
  11697. (check-consistent? T2 T3 e)
  11698. (match T1
  11699. ['Boolean
  11700. (define Tif (join T2 T3))
  11701. (values (If e1^ (make-cast e2^ T2 Tif)
  11702. (make-cast e3^ T3 Tif)) Tif)]
  11703. ['Any
  11704. (define Tif (meet T2 T3))
  11705. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  11706. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  11707. Tif)]
  11708. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  11709. [(HasType e1 T)
  11710. (define-values (e1^ T1) (recur e1))
  11711. (check-consistent? T1 T)
  11712. (values (make-cast e1^ T1 T) T)]
  11713. [(SetBang x e1)
  11714. (define-values (e1^ T1) (recur e1))
  11715. (define varT (dict-ref env x))
  11716. (check-consistent? T1 varT e)
  11717. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  11718. [(WhileLoop e1 e2)
  11719. (define-values (e1^ T1) (recur e1))
  11720. (check-consistent? T1 'Boolean e)
  11721. (define-values (e2^ T2) ((type-check-exp env) e2))
  11722. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  11723. \end{lstlisting}
  11724. \caption{Type checker for the \LangGrad{} language, part 2.}
  11725. \label{fig:type-check-Rgradual-2}
  11726. \end{figure}
  11727. \begin{figure}[tbp]
  11728. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11729. [(Apply e1 e2s)
  11730. (define-values (e1^ T1) (recur e1))
  11731. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  11732. (match T1
  11733. [`(,T1ps ... -> ,T1rt)
  11734. (for ([T2 T2s] [Tp T1ps])
  11735. (check-consistent? T2 Tp e))
  11736. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  11737. (make-cast e2 src tgt)))
  11738. (values (Apply e1^ e2s^^) T1rt)]
  11739. [`Any
  11740. (define e1^^ (make-cast e1^ 'Any
  11741. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  11742. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  11743. (make-cast e2 src 'Any)))
  11744. (values (Apply e1^^ e2s^^) 'Any)]
  11745. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11746. [(Lambda params Tr e1)
  11747. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11748. (match p
  11749. [`[,x : ,T] (values x T)]
  11750. [(? symbol? x) (values x 'Any)])))
  11751. (define-values (e1^ T1)
  11752. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11753. (check-consistent? Tr T1 e)
  11754. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11755. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11756. [else ((super type-check-exp env) e)]
  11757. )))
  11758. \end{lstlisting}
  11759. \caption{Type checker for the \LangGrad{} language, part 3.}
  11760. \label{fig:type-check-Rgradual-3}
  11761. \end{figure}
  11762. \begin{figure}[tbp]
  11763. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11764. (define/public (join t1 t2)
  11765. (match* (t1 t2)
  11766. [('Integer 'Integer) 'Integer]
  11767. [('Boolean 'Boolean) 'Boolean]
  11768. [('Void 'Void) 'Void]
  11769. [('Any t2) t2]
  11770. [(t1 'Any) t1]
  11771. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11772. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11773. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11774. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11775. -> ,(join rt1 rt2))]))
  11776. (define/public (meet t1 t2)
  11777. (match* (t1 t2)
  11778. [('Integer 'Integer) 'Integer]
  11779. [('Boolean 'Boolean) 'Boolean]
  11780. [('Void 'Void) 'Void]
  11781. [('Any t2) 'Any]
  11782. [(t1 'Any) 'Any]
  11783. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11784. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11785. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11786. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11787. -> ,(meet rt1 rt2))]))
  11788. (define/public (make-cast e src tgt)
  11789. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11790. (define/public (check-consistent? t1 t2 e)
  11791. (unless (consistent? t1 t2)
  11792. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11793. (define/override (type-check-op op arg-types args e)
  11794. (match (dict-ref (operator-types) op)
  11795. [`(,param-types . ,return-type)
  11796. (for ([at arg-types] [pt param-types])
  11797. (check-consistent? at pt e))
  11798. (values return-type
  11799. (for/list ([e args] [s arg-types] [t param-types])
  11800. (make-cast e s t)))]
  11801. [else (error 'type-check-op "unrecognized ~a" op)]))
  11802. (define explicit-prim-ops
  11803. (set-union
  11804. (type-predicates)
  11805. (set 'procedure-arity 'eq?
  11806. 'vector 'vector-length 'vector-ref 'vector-set!
  11807. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11808. (define/override (fun-def-type d)
  11809. (match d
  11810. [(Def f params rt info body)
  11811. (define ps
  11812. (for/list ([p params])
  11813. (match p
  11814. [`[,x : ,T] T]
  11815. [(? symbol?) 'Any]
  11816. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11817. `(,@ps -> ,rt)]
  11818. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11819. \end{lstlisting}
  11820. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11821. \label{fig:type-check-Rgradual-aux}
  11822. \end{figure}
  11823. \clearpage
  11824. \section{Interpreting \LangCast{}}
  11825. \label{sec:interp-casts}
  11826. The runtime behavior of first-order casts is straightforward, that is,
  11827. casts involving simple types such as \code{Integer} and
  11828. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11829. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11830. puts the integer into a tagged value
  11831. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11832. \code{Integer} is accomplished with the \code{Project} operator, that
  11833. is, by checking the value's tag and either retrieving the underlying
  11834. integer or signaling an error if it the tag is not the one for
  11835. integers (Figure~\ref{fig:apply-project}).
  11836. %
  11837. Things get more interesting for higher-order casts, that is, casts
  11838. involving function or vector types.
  11839. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11840. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11841. this cast at runtime, we can't know in general whether the function
  11842. will always return an integer.\footnote{Predicting the return value of
  11843. a function is equivalent to the halting problem, which is
  11844. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11845. of the cast until the function is applied. This is accomplished by
  11846. wrapping \code{maybe-add1} in a new function that casts its parameter
  11847. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11848. casts the return value from \code{Any} to \code{Integer}.
  11849. Turning our attention to casts involving vector types, we consider the
  11850. example in Figure~\ref{fig:map-vec-bang} that defines a
  11851. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11852. type \code{(Vector Any Any)} and that updates \code{v} in place
  11853. instead of returning a new vector. So we name this function
  11854. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11855. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11856. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11857. cast between vector types would be a build a new vector whose elements
  11858. are the result of casting each of the original elements to the
  11859. appropriate target type. However, this approach is only valid for
  11860. immutable vectors; and our vectors are mutable. In the example of
  11861. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11862. the updates inside of \code{map-vec!} would happen to the new vector
  11863. and not the original one.
  11864. \begin{figure}[tbp]
  11865. % gradual_test_11.rkt
  11866. \begin{lstlisting}
  11867. (define (map-vec! [f : (Any -> Any)]
  11868. [v : (Vector Any Any)]) : Void
  11869. (begin
  11870. (vector-set! v 0 (f (vector-ref v 0)))
  11871. (vector-set! v 1 (f (vector-ref v 1)))))
  11872. (define (add1 x) (+ x 1))
  11873. (let ([v (vector 0 41)])
  11874. (begin (map-vec! add1 v) (vector-ref v 1)))
  11875. \end{lstlisting}
  11876. \caption{An example involving casts on vectors.}
  11877. \label{fig:map-vec-bang}
  11878. \end{figure}
  11879. Instead the interpreter needs to create a new kind of value, a
  11880. \emph{vector proxy}, that intercepts every vector operation. On a
  11881. read, the proxy reads from the underlying vector and then applies a
  11882. cast to the resulting value. On a write, the proxy casts the argument
  11883. value and then performs the write to the underlying vector. For the
  11884. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11885. \code{0} from \code{Integer} to \code{Any}. For the first
  11886. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11887. to \code{Integer}.
  11888. The final category of cast that we need to consider are casts between
  11889. the \code{Any} type and either a function or a vector
  11890. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11891. in which parameter \code{v} does not have a type annotation, so it is
  11892. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11893. type \code{(Vector Integer Integer)} so the type checker inserts a
  11894. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11895. thought is to use \code{Inject}, but that doesn't work because
  11896. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11897. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11898. to \code{Any}.
  11899. \begin{figure}[tbp]
  11900. \begin{lstlisting}
  11901. (define (map-vec! [f : (Any -> Any)] v) : Void
  11902. (begin
  11903. (vector-set! v 0 (f (vector-ref v 0)))
  11904. (vector-set! v 1 (f (vector-ref v 1)))))
  11905. (define (add1 x) (+ x 1))
  11906. (let ([v (vector 0 41)])
  11907. (begin (map-vec! add1 v) (vector-ref v 1)))
  11908. \end{lstlisting}
  11909. \caption{Casting a vector to \code{Any}.}
  11910. \label{fig:map-vec-any}
  11911. \end{figure}
  11912. The \LangCast{} interpreter uses an auxiliary function named
  11913. \code{apply-cast} to cast a value from a source type to a target type,
  11914. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11915. of the kinds of casts that we've discussed in this section.
  11916. \begin{figure}[tbp]
  11917. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11918. (define/public (apply-cast v s t)
  11919. (match* (s t)
  11920. [(t1 t2) #:when (equal? t1 t2) v]
  11921. [('Any t2)
  11922. (match t2
  11923. [`(,ts ... -> ,rt)
  11924. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11925. (define v^ (apply-project v any->any))
  11926. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11927. [`(Vector ,ts ...)
  11928. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11929. (define v^ (apply-project v vec-any))
  11930. (apply-cast v^ vec-any `(Vector ,@ts))]
  11931. [else (apply-project v t2)])]
  11932. [(t1 'Any)
  11933. (match t1
  11934. [`(,ts ... -> ,rt)
  11935. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11936. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11937. (apply-inject v^ (any-tag any->any))]
  11938. [`(Vector ,ts ...)
  11939. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11940. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11941. (apply-inject v^ (any-tag vec-any))]
  11942. [else (apply-inject v (any-tag t1))])]
  11943. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11944. (define x (gensym 'x))
  11945. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11946. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11947. (define cast-writes
  11948. (for/list ([t1 ts1] [t2 ts2])
  11949. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11950. `(vector-proxy ,(vector v (apply vector cast-reads)
  11951. (apply vector cast-writes)))]
  11952. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11953. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11954. `(function ,xs ,(Cast
  11955. (Apply (Value v)
  11956. (for/list ([x xs][t1 ts1][t2 ts2])
  11957. (Cast (Var x) t2 t1)))
  11958. rt1 rt2) ())]
  11959. ))
  11960. \end{lstlisting}
  11961. \caption{The \code{apply-cast} auxiliary method.}
  11962. \label{fig:apply-cast}
  11963. \end{figure}
  11964. The interpreter for \LangCast{} is defined in
  11965. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11966. dispatching to \code{apply-cast}. To handle the addition of vector
  11967. proxies, we update the vector primitives in \code{interp-op} using the
  11968. functions in Figure~\ref{fig:guarded-vector}.
  11969. \begin{figure}[tbp]
  11970. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11971. (define interp-Rcast-class
  11972. (class interp-Rwhile-class
  11973. (super-new)
  11974. (inherit apply-fun apply-inject apply-project)
  11975. (define/override (interp-op op)
  11976. (match op
  11977. ['vector-length guarded-vector-length]
  11978. ['vector-ref guarded-vector-ref]
  11979. ['vector-set! guarded-vector-set!]
  11980. ['any-vector-ref (lambda (v i)
  11981. (match v [`(tagged ,v^ ,tg)
  11982. (guarded-vector-ref v^ i)]))]
  11983. ['any-vector-set! (lambda (v i a)
  11984. (match v [`(tagged ,v^ ,tg)
  11985. (guarded-vector-set! v^ i a)]))]
  11986. ['any-vector-length (lambda (v)
  11987. (match v [`(tagged ,v^ ,tg)
  11988. (guarded-vector-length v^)]))]
  11989. [else (super interp-op op)]
  11990. ))
  11991. (define/override ((interp-exp env) e)
  11992. (define (recur e) ((interp-exp env) e))
  11993. (match e
  11994. [(Value v) v]
  11995. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11996. [else ((super interp-exp env) e)]))
  11997. ))
  11998. (define (interp-Rcast p)
  11999. (send (new interp-Rcast-class) interp-program p))
  12000. \end{lstlisting}
  12001. \caption{The interpreter for \LangCast{}.}
  12002. \label{fig:interp-Rcast}
  12003. \end{figure}
  12004. \begin{figure}[tbp]
  12005. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12006. (define (guarded-vector-ref vec i)
  12007. (match vec
  12008. [`(vector-proxy ,proxy)
  12009. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  12010. (define rd (vector-ref (vector-ref proxy 1) i))
  12011. (apply-fun rd (list val) 'guarded-vector-ref)]
  12012. [else (vector-ref vec i)]))
  12013. (define (guarded-vector-set! vec i arg)
  12014. (match vec
  12015. [`(vector-proxy ,proxy)
  12016. (define wr (vector-ref (vector-ref proxy 2) i))
  12017. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  12018. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  12019. [else (vector-set! vec i arg)]))
  12020. (define (guarded-vector-length vec)
  12021. (match vec
  12022. [`(vector-proxy ,proxy)
  12023. (guarded-vector-length (vector-ref proxy 0))]
  12024. [else (vector-length vec)]))
  12025. \end{lstlisting}
  12026. \caption{The guarded-vector auxiliary functions.}
  12027. \label{fig:guarded-vector}
  12028. \end{figure}
  12029. \section{Lower Casts}
  12030. \label{sec:lower-casts}
  12031. The next step in the journey towards x86 is the \code{lower-casts}
  12032. pass that translates the casts in \LangCast{} to the lower-level
  12033. \code{Inject} and \code{Project} operators and a new operator for
  12034. creating vector proxies, extending the \LangLoop{} language to create
  12035. \LangProxy{}. We recommend creating an auxiliary function named
  12036. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  12037. and a target type, and translates it to expression in \LangProxy{} that has
  12038. the same behavior as casting the expression from the source to the
  12039. target type in the interpreter.
  12040. The \code{lower-cast} function can follow a code structure similar to
  12041. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  12042. the interpreter for \LangCast{} because it must handle the same cases as
  12043. \code{apply-cast} and it needs to mimic the behavior of
  12044. \code{apply-cast}. The most interesting cases are those concerning the
  12045. casts between two vector types and between two function types.
  12046. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  12047. type to another vector type is accomplished by creating a proxy that
  12048. intercepts the operations on the underlying vector. Here we make the
  12049. creation of the proxy explicit with the \code{vector-proxy} primitive
  12050. operation. It takes three arguments, the first is an expression for
  12051. the vector, the second is a vector of functions for casting an element
  12052. that is being read from the vector, and the third is a vector of
  12053. functions for casting an element that is being written to the vector.
  12054. You can create the functions using \code{Lambda}. Also, as we shall
  12055. see in the next section, we need to differentiate these vectors from
  12056. the user-created ones, so we recommend using a new primitive operator
  12057. named \code{raw-vector} instead of \code{vector} to create these
  12058. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  12059. the output of \code{lower-casts} on the example in
  12060. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  12061. integers to a vector of \code{Any}.
  12062. \begin{figure}[tbp]
  12063. \begin{lstlisting}
  12064. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  12065. (begin
  12066. (vector-set! v 0 (f (vector-ref v 0)))
  12067. (vector-set! v 1 (f (vector-ref v 1)))))
  12068. (define (add1 [x : Any]) : Any
  12069. (inject (+ (project x Integer) 1) Integer))
  12070. (let ([v (vector 0 41)])
  12071. (begin
  12072. (map-vec! add1 (vector-proxy v
  12073. (raw-vector (lambda: ([x9 : Integer]) : Any
  12074. (inject x9 Integer))
  12075. (lambda: ([x9 : Integer]) : Any
  12076. (inject x9 Integer)))
  12077. (raw-vector (lambda: ([x9 : Any]) : Integer
  12078. (project x9 Integer))
  12079. (lambda: ([x9 : Any]) : Integer
  12080. (project x9 Integer)))))
  12081. (vector-ref v 1)))
  12082. \end{lstlisting}
  12083. \caption{Output of \code{lower-casts} on the example in
  12084. Figure~\ref{fig:map-vec-bang}.}
  12085. \label{fig:map-vec-bang-lower-cast}
  12086. \end{figure}
  12087. A cast from one function type to another function type is accomplished
  12088. by generating a \code{Lambda} whose parameter and return types match
  12089. the target function type. The body of the \code{Lambda} should cast
  12090. the parameters from the target type to the source type (yes,
  12091. backwards! functions are contravariant\index{contravariant} in the
  12092. parameters), then call the underlying function, and finally cast the
  12093. result from the source return type to the target return type.
  12094. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  12095. \code{lower-casts} pass on the \code{map-vec} example in
  12096. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  12097. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  12098. \begin{figure}[tbp]
  12099. \begin{lstlisting}
  12100. (define (map-vec [f : (Integer -> Integer)]
  12101. [v : (Vector Integer Integer)])
  12102. : (Vector Integer Integer)
  12103. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12104. (define (add1 [x : Any]) : Any
  12105. (inject (+ (project x Integer) 1) Integer))
  12106. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  12107. (project (add1 (inject x9 Integer)) Integer))
  12108. (vector 0 41)) 1)
  12109. \end{lstlisting}
  12110. \caption{Output of \code{lower-casts} on the example in
  12111. Figure~\ref{fig:gradual-map-vec}.}
  12112. \label{fig:map-vec-lower-cast}
  12113. \end{figure}
  12114. \section{Differentiate Proxies}
  12115. \label{sec:differentiate-proxies}
  12116. So far the job of differentiating vectors and vector proxies has been
  12117. the job of the interpreter. For example, the interpreter for \LangCast{}
  12118. implements \code{vector-ref} using the \code{guarded-vector-ref}
  12119. function in Figure~\ref{fig:guarded-vector}. In the
  12120. \code{differentiate-proxies} pass we shift this responsibility to the
  12121. generated code.
  12122. We begin by designing the output language $R^p_8$. In
  12123. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  12124. proxies. In $R^p_8$ we return the \code{Vector} type to
  12125. its original meaning, as the type of real vectors, and we introduce a
  12126. new type, \code{PVector}, whose values can be either real vectors or
  12127. vector proxies. This new type comes with a suite of new primitive
  12128. operations for creating and using values of type \code{PVector}. We
  12129. don't need to introduce a new type to represent vector proxies. A
  12130. proxy is represented by a vector containing three things: 1) the
  12131. underlying vector, 2) a vector of functions for casting elements that
  12132. are read from the vector, and 3) a vector of functions for casting
  12133. values to be written to the vector. So we define the following
  12134. abbreviation for the type of a vector proxy:
  12135. \[
  12136. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  12137. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  12138. \to (\key{PVector}~ T' \ldots)
  12139. \]
  12140. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  12141. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  12142. %
  12143. Next we describe each of the new primitive operations.
  12144. \begin{description}
  12145. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  12146. (\key{PVector} $T \ldots$)]\ \\
  12147. %
  12148. This operation brands a vector as a value of the \code{PVector} type.
  12149. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  12150. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  12151. %
  12152. This operation brands a vector proxy as value of the \code{PVector} type.
  12153. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  12154. \code{Boolean}] \ \\
  12155. %
  12156. returns true if the value is a vector proxy and false if it is a
  12157. real vector.
  12158. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  12159. (\key{Vector} $T \ldots$)]\ \\
  12160. %
  12161. Assuming that the input is a vector (and not a proxy), this
  12162. operation returns the vector.
  12163. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  12164. $\to$ \code{Boolean}]\ \\
  12165. %
  12166. Given a vector proxy, this operation returns the length of the
  12167. underlying vector.
  12168. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  12169. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  12170. %
  12171. Given a vector proxy, this operation returns the $i$th element of
  12172. the underlying vector.
  12173. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  12174. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  12175. proxy, this operation writes a value to the $i$th element of the
  12176. underlying vector.
  12177. \end{description}
  12178. Now to discuss the translation that differentiates vectors from
  12179. proxies. First, every type annotation in the program must be
  12180. translated (recursively) to replace \code{Vector} with \code{PVector}.
  12181. Next, we must insert uses of \code{PVector} operations in the
  12182. appropriate places. For example, we wrap every vector creation with an
  12183. \code{inject-vector}.
  12184. \begin{lstlisting}
  12185. (vector |$e_1 \ldots e_n$|)
  12186. |$\Rightarrow$|
  12187. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  12188. \end{lstlisting}
  12189. The \code{raw-vector} operator that we introduced in the previous
  12190. section does not get injected.
  12191. \begin{lstlisting}
  12192. (raw-vector |$e_1 \ldots e_n$|)
  12193. |$\Rightarrow$|
  12194. (vector |$e'_1 \ldots e'_n$|)
  12195. \end{lstlisting}
  12196. The \code{vector-proxy} primitive translates as follows.
  12197. \begin{lstlisting}
  12198. (vector-proxy |$e_1~e_2~e_3$|)
  12199. |$\Rightarrow$|
  12200. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  12201. \end{lstlisting}
  12202. We translate the vector operations into conditional expressions that
  12203. check whether the value is a proxy and then dispatch to either the
  12204. appropriate proxy vector operation or the regular vector operation.
  12205. For example, the following is the translation for \code{vector-ref}.
  12206. \begin{lstlisting}
  12207. (vector-ref |$e_1$| |$i$|)
  12208. |$\Rightarrow$|
  12209. (let ([|$v~e_1$|])
  12210. (if (proxy? |$v$|)
  12211. (proxy-vector-ref |$v$| |$i$|)
  12212. (vector-ref (project-vector |$v$|) |$i$|)
  12213. \end{lstlisting}
  12214. Note in the case of a real vector, we must apply \code{project-vector}
  12215. before the \code{vector-ref}.
  12216. \section{Reveal Casts}
  12217. \label{sec:reveal-casts-gradual}
  12218. Recall that the \code{reveal-casts} pass
  12219. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  12220. \code{Inject} and \code{Project} into lower-level operations. In
  12221. particular, \code{Project} turns into a conditional expression that
  12222. inspects the tag and retrieves the underlying value. Here we need to
  12223. augment the translation of \code{Project} to handle the situation when
  12224. the target type is \code{PVector}. Instead of using
  12225. \code{vector-length} we need to use \code{proxy-vector-length}.
  12226. \begin{lstlisting}
  12227. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  12228. |$\Rightarrow$|
  12229. (let |$\itm{tmp}$| |$e'$|
  12230. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  12231. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  12232. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  12233. (exit)))
  12234. \end{lstlisting}
  12235. \section{Closure Conversion}
  12236. \label{sec:closure-conversion-gradual}
  12237. The closure conversion pass only requires one minor adjustment. The
  12238. auxiliary function that translates type annotations needs to be
  12239. updated to handle the \code{PVector} type.
  12240. \section{Explicate Control}
  12241. \label{sec:explicate-control-gradual}
  12242. Update the \code{explicate-control} pass to handle the new primitive
  12243. operations on the \code{PVector} type.
  12244. \section{Select Instructions}
  12245. \label{sec:select-instructions-gradual}
  12246. Recall that the \code{select-instructions} pass is responsible for
  12247. lowering the primitive operations into x86 instructions. So we need
  12248. to translate the new \code{PVector} operations to x86. To do so, the
  12249. first question we need to answer is how will we differentiate the two
  12250. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  12251. We need just one bit to accomplish this, and use the bit in position
  12252. $57$ of the 64-bit tag at the front of every vector (see
  12253. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  12254. for \code{inject-vector} we leave it that way.
  12255. \begin{lstlisting}
  12256. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  12257. |$\Rightarrow$|
  12258. movq |$e'_1$|, |$\itm{lhs'}$|
  12259. \end{lstlisting}
  12260. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  12261. \begin{lstlisting}
  12262. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  12263. |$\Rightarrow$|
  12264. movq |$e'_1$|, %r11
  12265. movq |$(1 << 57)$|, %rax
  12266. orq 0(%r11), %rax
  12267. movq %rax, 0(%r11)
  12268. movq %r11, |$\itm{lhs'}$|
  12269. \end{lstlisting}
  12270. The \code{proxy?} operation consumes the information so carefully
  12271. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  12272. isolates the $57$th bit to tell whether the value is a real vector or
  12273. a proxy.
  12274. \begin{lstlisting}
  12275. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  12276. |$\Rightarrow$|
  12277. movq |$e_1'$|, %r11
  12278. movq 0(%r11), %rax
  12279. sarq $57, %rax
  12280. andq $1, %rax
  12281. movq %rax, |$\itm{lhs'}$|
  12282. \end{lstlisting}
  12283. The \code{project-vector} operation is straightforward to translate,
  12284. so we leave it up to the reader.
  12285. Regarding the \code{proxy-vector} operations, the runtime provides
  12286. procedures that implement them (they are recursive functions!) so
  12287. here we simply need to translate these vector operations into the
  12288. appropriate function call. For example, here is the translation for
  12289. \code{proxy-vector-ref}.
  12290. \begin{lstlisting}
  12291. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  12292. |$\Rightarrow$|
  12293. movq |$e_1'$|, %rdi
  12294. movq |$e_2'$|, %rsi
  12295. callq proxy_vector_ref
  12296. movq %rax, |$\itm{lhs'}$|
  12297. \end{lstlisting}
  12298. We have another batch of vector operations to deal with, those for the
  12299. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  12300. \code{any-vector-ref} when there is a \code{vector-ref} on something
  12301. of type \code{Any}, and similarly for \code{any-vector-set!} and
  12302. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  12303. Section~\ref{sec:select-Rany} we selected instructions for these
  12304. operations based on the idea that the underlying value was a real
  12305. vector. But in the current setting, the underlying value is of type
  12306. \code{PVector}. So \code{any-vector-ref} can be translates to
  12307. pseudo-x86 as follows. We begin by projecting the underlying value out
  12308. of the tagged value and then call the \code{proxy\_vector\_ref}
  12309. procedure in the runtime.
  12310. \begin{lstlisting}
  12311. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  12312. movq |$\neg 111$|, %rdi
  12313. andq |$e_1'$|, %rdi
  12314. movq |$e_2'$|, %rsi
  12315. callq proxy_vector_ref
  12316. movq %rax, |$\itm{lhs'}$|
  12317. \end{lstlisting}
  12318. The \code{any-vector-set!} and \code{any-vector-length} operators can
  12319. be translated in a similar way.
  12320. \begin{exercise}\normalfont
  12321. Implement a compiler for the gradually-typed \LangGrad{} language by
  12322. extending and adapting your compiler for \LangLoop{}. Create 10 new
  12323. partially-typed test programs. In addition to testing with these
  12324. new programs, also test your compiler on all the tests for \LangLoop{}
  12325. and tests for \LangDyn{}. Sometimes you may get a type checking error
  12326. on the \LangDyn{} programs but you can adapt them by inserting
  12327. a cast to the \code{Any} type around each subexpression
  12328. causing a type error. While \LangDyn{} doesn't have explicit casts,
  12329. you can induce one by wrapping the subexpression \code{e}
  12330. with a call to an un-annotated identity function, like this:
  12331. \code{((lambda (x) x) e)}.
  12332. \end{exercise}
  12333. \begin{figure}[p]
  12334. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12335. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  12336. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12337. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12338. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12339. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12340. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12341. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12342. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12343. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12344. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12345. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12346. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12347. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12348. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12349. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12350. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12351. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12352. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12353. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12354. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12355. \path[->,bend right=15] (Rgradual) edge [above] node
  12356. {\ttfamily\footnotesize type-check} (Rgradualp);
  12357. \path[->,bend right=15] (Rgradualp) edge [above] node
  12358. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12359. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12360. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12361. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12362. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12363. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12364. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12365. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12366. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12367. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12368. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12369. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12370. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12371. \path[->,bend left=15] (F1-1) edge [below] node
  12372. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12373. \path[->,bend right=15] (F1-2) edge [above] node
  12374. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12375. \path[->,bend right=15] (F1-3) edge [above] node
  12376. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12377. \path[->,bend right=15] (F1-4) edge [above] node
  12378. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12379. \path[->,bend right=15] (F1-5) edge [right] node
  12380. {\ttfamily\footnotesize explicate-control} (C3-2);
  12381. \path[->,bend left=15] (C3-2) edge [left] node
  12382. {\ttfamily\footnotesize select-instr.} (x86-2);
  12383. \path[->,bend right=15] (x86-2) edge [left] node
  12384. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12385. \path[->,bend right=15] (x86-2-1) edge [below] node
  12386. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12387. \path[->,bend right=15] (x86-2-2) edge [left] node
  12388. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12389. \path[->,bend left=15] (x86-3) edge [above] node
  12390. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12391. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12392. \end{tikzpicture}
  12393. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  12394. \label{fig:Rgradual-passes}
  12395. \end{figure}
  12396. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  12397. for the compilation of \LangGrad{}.
  12398. \section{Further Reading}
  12399. This chapter just scratches the surface of gradual typing. The basic
  12400. approach described here is missing two key ingredients that one would
  12401. want in a implementation of gradual typing: blame
  12402. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  12403. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  12404. problem addressed by blame tracking is that when a cast on a
  12405. higher-order value fails, it often does so at a point in the program
  12406. that is far removed from the original cast. Blame tracking is a
  12407. technique for propagating extra information through casts and proxies
  12408. so that when a cast fails, the error message can point back to the
  12409. original location of the cast in the source program.
  12410. The problem addressed by space-efficient casts also relates to
  12411. higher-order casts. It turns out that in partially typed programs, a
  12412. function or vector can flow through very-many casts at runtime. With
  12413. the approach described in this chapter, each cast adds another
  12414. \code{lambda} wrapper or a vector proxy. Not only does this take up
  12415. considerable space, but it also makes the function calls and vector
  12416. operations slow. For example, a partially-typed version of quicksort
  12417. could, in the worst case, build a chain of proxies of length $O(n)$
  12418. around the vector, changing the overall time complexity of the
  12419. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  12420. solution to this problem by representing casts using the coercion
  12421. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  12422. long chains of proxies by compressing them into a concise normal
  12423. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  12424. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  12425. the Grift compiler.
  12426. \begin{center}
  12427. \url{https://github.com/Gradual-Typing/Grift}
  12428. \end{center}
  12429. There are also interesting interactions between gradual typing and
  12430. other language features, such as parametetric polymorphism,
  12431. information-flow types, and type inference, to name a few. We
  12432. recommend the reader to the online gradual typing bibliography:
  12433. \begin{center}
  12434. \url{http://samth.github.io/gradual-typing-bib/}
  12435. \end{center}
  12436. % TODO: challenge problem:
  12437. % type analysis and type specialization?
  12438. % coercions?
  12439. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12440. \chapter{Parametric Polymorphism}
  12441. \label{ch:Rpoly}
  12442. \index{parametric polymorphism}
  12443. \index{generics}
  12444. This chapter studies the compilation of parametric
  12445. polymorphism\index{parametric polymorphism}
  12446. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  12447. Racket. Parametric polymorphism enables improved code reuse by
  12448. parameterizing functions and data structures with respect to the types
  12449. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  12450. revisits the \code{map-vec} example but this time gives it a more
  12451. fitting type. This \code{map-vec} function is parameterized with
  12452. respect to the element type of the vector. The type of \code{map-vec}
  12453. is the following polymorphic type as specified by the \code{All} and
  12454. the type parameter \code{a}.
  12455. \begin{lstlisting}
  12456. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12457. \end{lstlisting}
  12458. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  12459. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  12460. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  12461. \code{a}, but we could have just as well applied \code{map-vec} to a
  12462. vector of Booleans (and a function on Booleans).
  12463. \begin{figure}[tbp]
  12464. % poly_test_2.rkt
  12465. \begin{lstlisting}
  12466. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  12467. (define (map-vec f v)
  12468. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12469. (define (add1 [x : Integer]) : Integer (+ x 1))
  12470. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12471. \end{lstlisting}
  12472. \caption{The \code{map-vec} example using parametric polymorphism.}
  12473. \label{fig:map-vec-poly}
  12474. \end{figure}
  12475. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  12476. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  12477. syntax. We add a second form for function definitions in which a type
  12478. declaration comes before the \code{define}. In the abstract syntax,
  12479. the return type in the \code{Def} is \code{Any}, but that should be
  12480. ignored in favor of the return type in the type declaration. (The
  12481. \code{Any} comes from using the same parser as in
  12482. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  12483. enables the use of an \code{All} type for a function, thereby making
  12484. it polymorphic. The grammar for types is extended to include
  12485. polymorphic types and type variables.
  12486. \begin{figure}[tp]
  12487. \centering
  12488. \fbox{
  12489. \begin{minipage}{0.96\textwidth}
  12490. \small
  12491. \[
  12492. \begin{array}{lcl}
  12493. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12494. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  12495. &\mid& \LP\key{:}~\Var~\Type\RP \\
  12496. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  12497. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  12498. \end{array}
  12499. \]
  12500. \end{minipage}
  12501. }
  12502. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  12503. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12504. \label{fig:Rpoly-concrete-syntax}
  12505. \end{figure}
  12506. \begin{figure}[tp]
  12507. \centering
  12508. \fbox{
  12509. \begin{minipage}{0.96\textwidth}
  12510. \small
  12511. \[
  12512. \begin{array}{lcl}
  12513. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12514. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12515. &\mid& \DECL{\Var}{\Type} \\
  12516. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  12517. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12518. \end{array}
  12519. \]
  12520. \end{minipage}
  12521. }
  12522. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  12523. (Figure~\ref{fig:Rwhile-syntax}).}
  12524. \label{fig:Rpoly-syntax}
  12525. \end{figure}
  12526. By including polymorphic types in the $\Type$ non-terminal we choose
  12527. to make them first-class which has interesting repercussions on the
  12528. compiler. Many languages with polymorphism, such as
  12529. C++~\citep{stroustrup88:_param_types} and Standard
  12530. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  12531. it is useful to see an example of first-class polymorphism. In
  12532. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  12533. whose parameter is a polymorphic function. The occurrence of a
  12534. polymorphic type underneath a function type is enabled by the normal
  12535. recursive structure of the grammar for $\Type$ and the categorization
  12536. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  12537. applies the polymorphic function to a Boolean and to an integer.
  12538. \begin{figure}[tbp]
  12539. \begin{lstlisting}
  12540. (: apply-twice ((All (b) (b -> b)) -> Integer))
  12541. (define (apply-twice f)
  12542. (if (f #t) (f 42) (f 777)))
  12543. (: id (All (a) (a -> a)))
  12544. (define (id x) x)
  12545. (apply-twice id)
  12546. \end{lstlisting}
  12547. \caption{An example illustrating first-class polymorphism.}
  12548. \label{fig:apply-twice}
  12549. \end{figure}
  12550. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  12551. three new responsibilities (compared to \LangLoop{}). The type checking of
  12552. function application is extended to handle the case where the operator
  12553. expression is a polymorphic function. In that case the type arguments
  12554. are deduced by matching the type of the parameters with the types of
  12555. the arguments.
  12556. %
  12557. The \code{match-types} auxiliary function carries out this deduction
  12558. by recursively descending through a parameter type \code{pt} and the
  12559. corresponding argument type \code{at}, making sure that they are equal
  12560. except when there is a type parameter on the left (in the parameter
  12561. type). If it's the first time that the type parameter has been
  12562. encountered, then the algorithm deduces an association of the type
  12563. parameter to the corresponding type on the right (in the argument
  12564. type). If it's not the first time that the type parameter has been
  12565. encountered, the algorithm looks up its deduced type and makes sure
  12566. that it is equal to the type on the right.
  12567. %
  12568. Once the type arguments are deduced, the operator expression is
  12569. wrapped in an \code{Inst} AST node (for instantiate) that records the
  12570. type of the operator, but more importantly, records the deduced type
  12571. arguments. The return type of the application is the return type of
  12572. the polymorphic function, but with the type parameters replaced by the
  12573. deduced type arguments, using the \code{subst-type} function.
  12574. The second responsibility of the type checker is extending the
  12575. function \code{type-equal?} to handle the \code{All} type. This is
  12576. not quite a simple as equal on other types, such as function and
  12577. vector types, because two polymorphic types can be syntactically
  12578. different even though they are equivalent types. For example,
  12579. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  12580. Two polymorphic types should be considered equal if they differ only
  12581. in the choice of the names of the type parameters. The
  12582. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  12583. renames the type parameters of the first type to match the type
  12584. parameters of the second type.
  12585. The third responsibility of the type checker is making sure that only
  12586. defined type variables appear in type annotations. The
  12587. \code{check-well-formed} function defined in
  12588. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  12589. sure that each type variable has been defined.
  12590. The output language of the type checker is \LangInst{}, defined in
  12591. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  12592. declaration and polymorphic function into a single definition, using
  12593. the \code{Poly} form, to make polymorphic functions more convenient to
  12594. process in next pass of the compiler.
  12595. \begin{figure}[tp]
  12596. \centering
  12597. \fbox{
  12598. \begin{minipage}{0.96\textwidth}
  12599. \small
  12600. \[
  12601. \begin{array}{lcl}
  12602. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12603. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  12604. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12605. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  12606. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12607. \end{array}
  12608. \]
  12609. \end{minipage}
  12610. }
  12611. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  12612. (Figure~\ref{fig:Rwhile-syntax}).}
  12613. \label{fig:Rpoly-prime-syntax}
  12614. \end{figure}
  12615. The output of the type checker on the polymorphic \code{map-vec}
  12616. example is listed in Figure~\ref{fig:map-vec-type-check}.
  12617. \begin{figure}[tbp]
  12618. % poly_test_2.rkt
  12619. \begin{lstlisting}
  12620. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  12621. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  12622. (define (add1 [x : Integer]) : Integer (+ x 1))
  12623. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12624. (Integer))
  12625. add1 (vector 0 41)) 1)
  12626. \end{lstlisting}
  12627. \caption{Output of the type checker on the \code{map-vec} example.}
  12628. \label{fig:map-vec-type-check}
  12629. \end{figure}
  12630. \begin{figure}[tbp]
  12631. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12632. (define type-check-poly-class
  12633. (class type-check-Rwhile-class
  12634. (super-new)
  12635. (inherit check-type-equal?)
  12636. (define/override (type-check-apply env e1 es)
  12637. (define-values (e^ ty) ((type-check-exp env) e1))
  12638. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  12639. ((type-check-exp env) e)))
  12640. (match ty
  12641. [`(,ty^* ... -> ,rt)
  12642. (for ([arg-ty ty*] [param-ty ty^*])
  12643. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  12644. (values e^ es^ rt)]
  12645. [`(All ,xs (,tys ... -> ,rt))
  12646. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12647. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  12648. (match-types env^^ param-ty arg-ty)))
  12649. (define targs
  12650. (for/list ([x xs])
  12651. (match (dict-ref env^^ x (lambda () #f))
  12652. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  12653. x (Apply e1 es))]
  12654. [ty ty])))
  12655. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  12656. [else (error 'type-check "expected a function, not ~a" ty)]))
  12657. (define/override ((type-check-exp env) e)
  12658. (match e
  12659. [(Lambda `([,xs : ,Ts] ...) rT body)
  12660. (for ([T Ts]) ((check-well-formed env) T))
  12661. ((check-well-formed env) rT)
  12662. ((super type-check-exp env) e)]
  12663. [(HasType e1 ty)
  12664. ((check-well-formed env) ty)
  12665. ((super type-check-exp env) e)]
  12666. [else ((super type-check-exp env) e)]))
  12667. (define/override ((type-check-def env) d)
  12668. (verbose 'type-check "poly/def" d)
  12669. (match d
  12670. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  12671. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  12672. (for ([p ps]) ((check-well-formed ts-env) p))
  12673. ((check-well-formed ts-env) rt)
  12674. (define new-env (append ts-env (map cons xs ps) env))
  12675. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12676. (check-type-equal? ty^ rt body)
  12677. (Generic ts (Def f p:t* rt info body^))]
  12678. [else ((super type-check-def env) d)]))
  12679. (define/override (type-check-program p)
  12680. (match p
  12681. [(Program info body)
  12682. (type-check-program (ProgramDefsExp info '() body))]
  12683. [(ProgramDefsExp info ds body)
  12684. (define ds^ (combine-decls-defs ds))
  12685. (define new-env (for/list ([d ds^])
  12686. (cons (def-name d) (fun-def-type d))))
  12687. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  12688. (define-values (body^ ty) ((type-check-exp new-env) body))
  12689. (check-type-equal? ty 'Integer body)
  12690. (ProgramDefsExp info ds^^ body^)]))
  12691. ))
  12692. \end{lstlisting}
  12693. \caption{Type checker for the \LangPoly{} language.}
  12694. \label{fig:type-check-Rvar0}
  12695. \end{figure}
  12696. \begin{figure}[tbp]
  12697. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12698. (define/override (type-equal? t1 t2)
  12699. (match* (t1 t2)
  12700. [(`(All ,xs ,T1) `(All ,ys ,T2))
  12701. (define env (map cons xs ys))
  12702. (type-equal? (subst-type env T1) T2)]
  12703. [(other wise)
  12704. (super type-equal? t1 t2)]))
  12705. (define/public (match-types env pt at)
  12706. (match* (pt at)
  12707. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  12708. [('Void 'Void) env] [('Any 'Any) env]
  12709. [(`(Vector ,pts ...) `(Vector ,ats ...))
  12710. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  12711. (match-types env^ pt1 at1))]
  12712. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  12713. (define env^ (match-types env prt art))
  12714. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  12715. (match-types env^^ pt1 at1))]
  12716. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  12717. (define env^ (append (map cons pxs axs) env))
  12718. (match-types env^ pt1 at1)]
  12719. [((? symbol? x) at)
  12720. (match (dict-ref env x (lambda () #f))
  12721. [#f (error 'type-check "undefined type variable ~a" x)]
  12722. ['Type (cons (cons x at) env)]
  12723. [t^ (check-type-equal? at t^ 'matching) env])]
  12724. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  12725. (define/public (subst-type env pt)
  12726. (match pt
  12727. ['Integer 'Integer] ['Boolean 'Boolean]
  12728. ['Void 'Void] ['Any 'Any]
  12729. [`(Vector ,ts ...)
  12730. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  12731. [`(,ts ... -> ,rt)
  12732. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  12733. [`(All ,xs ,t)
  12734. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  12735. [(? symbol? x) (dict-ref env x)]
  12736. [else (error 'type-check "expected a type not ~a" pt)]))
  12737. (define/public (combine-decls-defs ds)
  12738. (match ds
  12739. ['() '()]
  12740. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  12741. (unless (equal? name f)
  12742. (error 'type-check "name mismatch, ~a != ~a" name f))
  12743. (match type
  12744. [`(All ,xs (,ps ... -> ,rt))
  12745. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12746. (cons (Generic xs (Def name params^ rt info body))
  12747. (combine-decls-defs ds^))]
  12748. [`(,ps ... -> ,rt)
  12749. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12750. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12751. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12752. [`(,(Def f params rt info body) . ,ds^)
  12753. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12754. \end{lstlisting}
  12755. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12756. \label{fig:type-check-Rvar0-aux}
  12757. \end{figure}
  12758. \begin{figure}[tbp]
  12759. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12760. (define/public ((check-well-formed env) ty)
  12761. (match ty
  12762. ['Integer (void)]
  12763. ['Boolean (void)]
  12764. ['Void (void)]
  12765. [(? symbol? a)
  12766. (match (dict-ref env a (lambda () #f))
  12767. ['Type (void)]
  12768. [else (error 'type-check "undefined type variable ~a" a)])]
  12769. [`(Vector ,ts ...)
  12770. (for ([t ts]) ((check-well-formed env) t))]
  12771. [`(,ts ... -> ,t)
  12772. (for ([t ts]) ((check-well-formed env) t))
  12773. ((check-well-formed env) t)]
  12774. [`(All ,xs ,t)
  12775. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12776. ((check-well-formed env^) t)]
  12777. [else (error 'type-check "unrecognized type ~a" ty)]))
  12778. \end{lstlisting}
  12779. \caption{Well-formed types.}
  12780. \label{fig:well-formed-types}
  12781. \end{figure}
  12782. % TODO: interpreter for R'_10
  12783. \section{Compiling Polymorphism}
  12784. \label{sec:compiling-poly}
  12785. Broadly speaking, there are four approaches to compiling parametric
  12786. polymorphism, which we describe below.
  12787. \begin{description}
  12788. \item[Monomorphization] generates a different version of a polymorphic
  12789. function for each set of type arguments that it is used with,
  12790. producing type-specialized code. This approach results in the most
  12791. efficient code but requires whole-program compilation (no separate
  12792. compilation) and increases code size. For our current purposes
  12793. monomorphization is a non-starter because, with first-class
  12794. polymorphism, it is sometimes not possible to determine which
  12795. generic functions are used with which type arguments during
  12796. compilation. (It can be done at runtime, with just-in-time
  12797. compilation.) This approach is used to compile C++
  12798. templates~\citep{stroustrup88:_param_types} and polymorphic
  12799. functions in NESL~\citep{Blelloch:1993aa} and
  12800. ML~\citep{Weeks:2006aa}.
  12801. \item[Uniform representation] generates one version of each
  12802. polymorphic function but requires all values have a common ``boxed''
  12803. format, such as the tagged values of type \code{Any} in
  12804. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12805. similarly to code in a dynamically typed language (like \LangDyn{}),
  12806. in which primitive operators require their arguments to be projected
  12807. from \code{Any} and their results are injected into \code{Any}. (In
  12808. object-oriented languages, the projection is accomplished via
  12809. virtual method dispatch.) The uniform representation approach is
  12810. compatible with separate compilation and with first-class
  12811. polymorphism. However, it produces the least-efficient code because
  12812. it introduces overhead in the entire program, including
  12813. non-polymorphic code. This approach is used in implementations of
  12814. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12815. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12816. Java~\citep{Bracha:1998fk}.
  12817. \item[Mixed representation] generates one version of each polymorphic
  12818. function, using a boxed representation for type
  12819. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12820. and conversions are performed at the boundaries between monomorphic
  12821. and polymorphic (e.g. when a polymorphic function is instantiated
  12822. and called). This approach is compatible with separate compilation
  12823. and first-class polymorphism and maintains the efficiency of
  12824. monomorphic code. The tradeoff is increased overhead at the boundary
  12825. between monomorphic and polymorphic code. This approach is used in
  12826. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12827. Java 5 with the addition of autoboxing.
  12828. \item[Type passing] uses the unboxed representation in both
  12829. monomorphic and polymorphic code. Each polymorphic function is
  12830. compiled to a single function with extra parameters that describe
  12831. the type arguments. The type information is used by the generated
  12832. code to know how to access the unboxed values at runtime. This
  12833. approach is used in implementation of the Napier88
  12834. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12835. passing is compatible with separate compilation and first-class
  12836. polymorphism and maintains the efficiency for monomorphic
  12837. code. There is runtime overhead in polymorphic code from dispatching
  12838. on type information.
  12839. \end{description}
  12840. In this chapter we use the mixed representation approach, partly
  12841. because of its favorable attributes, and partly because it is
  12842. straightforward to implement using the tools that we have already
  12843. built to support gradual typing. To compile polymorphic functions, we
  12844. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12845. \LangCast{}.
  12846. \section{Erase Types}
  12847. \label{sec:erase-types}
  12848. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12849. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12850. shows the output of the \code{erase-types} pass on the polymorphic
  12851. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12852. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12853. \code{All} types are removed from the type of \code{map-vec}.
  12854. \begin{figure}[tbp]
  12855. \begin{lstlisting}
  12856. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12857. : (Vector Any Any)
  12858. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12859. (define (add1 [x : Integer]) : Integer (+ x 1))
  12860. (vector-ref ((cast map-vec
  12861. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12862. ((Integer -> Integer) (Vector Integer Integer)
  12863. -> (Vector Integer Integer)))
  12864. add1 (vector 0 41)) 1)
  12865. \end{lstlisting}
  12866. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12867. \label{fig:map-vec-erase}
  12868. \end{figure}
  12869. This process of type erasure creates a challenge at points of
  12870. instantiation. For example, consider the instantiation of
  12871. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12872. The type of \code{map-vec} is
  12873. \begin{lstlisting}
  12874. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12875. \end{lstlisting}
  12876. and it is instantiated to
  12877. \begin{lstlisting}
  12878. ((Integer -> Integer) (Vector Integer Integer)
  12879. -> (Vector Integer Integer))
  12880. \end{lstlisting}
  12881. After erasure, the type of \code{map-vec} is
  12882. \begin{lstlisting}
  12883. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12884. \end{lstlisting}
  12885. but we need to convert it to the instantiated type. This is easy to
  12886. do in the target language \LangCast{} with a single \code{cast}. In
  12887. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12888. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12889. the instantiated type. The source and target type of a cast must be
  12890. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12891. because both the source and target are obtained from the same
  12892. polymorphic type of \code{map-vec}, replacing the type parameters with
  12893. \code{Any} in the former and with the deduced type arguments in the
  12894. later. (Recall that the \code{Any} type is consistent with any type.)
  12895. To implement the \code{erase-types} pass, we recommend defining a
  12896. recursive auxiliary function named \code{erase-type} that applies the
  12897. following two transformations. It replaces type variables with
  12898. \code{Any}
  12899. \begin{lstlisting}
  12900. |$x$|
  12901. |$\Rightarrow$|
  12902. Any
  12903. \end{lstlisting}
  12904. and it removes the polymorphic \code{All} types.
  12905. \begin{lstlisting}
  12906. (All |$xs$| |$T_1$|)
  12907. |$\Rightarrow$|
  12908. |$T'_1$|
  12909. \end{lstlisting}
  12910. Apply the \code{erase-type} function to all of the type annotations in
  12911. the program.
  12912. Regarding the translation of expressions, the case for \code{Inst} is
  12913. the interesting one. We translate it into a \code{Cast}, as shown
  12914. below. The type of the subexpression $e$ is the polymorphic type
  12915. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12916. $T$, the type $T'$. The target type $T''$ is the result of
  12917. substituting the arguments types $ts$ for the type parameters $xs$ in
  12918. $T$ followed by doing type erasure.
  12919. \begin{lstlisting}
  12920. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12921. |$\Rightarrow$|
  12922. (Cast |$e'$| |$T'$| |$T''$|)
  12923. \end{lstlisting}
  12924. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12925. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12926. Finally, each polymorphic function is translated to a regular
  12927. functions in which type erasure has been applied to all the type
  12928. annotations and the body.
  12929. \begin{lstlisting}
  12930. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12931. |$\Rightarrow$|
  12932. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12933. \end{lstlisting}
  12934. \begin{exercise}\normalfont
  12935. Implement a compiler for the polymorphic language \LangPoly{} by
  12936. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12937. programs that use polymorphic functions. Some of them should make
  12938. use of first-class polymorphism.
  12939. \end{exercise}
  12940. \begin{figure}[p]
  12941. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12942. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12943. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12944. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12945. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12946. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12947. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12948. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12949. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12950. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12951. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12952. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12953. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12954. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12955. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12956. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12957. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12958. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12959. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12960. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12961. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12962. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12963. \path[->,bend right=15] (Rpoly) edge [above] node
  12964. {\ttfamily\footnotesize type-check} (Rpolyp);
  12965. \path[->,bend right=15] (Rpolyp) edge [above] node
  12966. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12967. \path[->,bend right=15] (Rgradualp) edge [above] node
  12968. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12969. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12970. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12971. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12972. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12973. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12974. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12975. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12976. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12977. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12978. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12979. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12980. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12981. \path[->,bend left=15] (F1-1) edge [below] node
  12982. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12983. \path[->,bend right=15] (F1-2) edge [above] node
  12984. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12985. \path[->,bend right=15] (F1-3) edge [above] node
  12986. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12987. \path[->,bend right=15] (F1-4) edge [above] node
  12988. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12989. \path[->,bend right=15] (F1-5) edge [right] node
  12990. {\ttfamily\footnotesize explicate-control} (C3-2);
  12991. \path[->,bend left=15] (C3-2) edge [left] node
  12992. {\ttfamily\footnotesize select-instr.} (x86-2);
  12993. \path[->,bend right=15] (x86-2) edge [left] node
  12994. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12995. \path[->,bend right=15] (x86-2-1) edge [below] node
  12996. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12997. \path[->,bend right=15] (x86-2-2) edge [left] node
  12998. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12999. \path[->,bend left=15] (x86-3) edge [above] node
  13000. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13001. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13002. \end{tikzpicture}
  13003. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  13004. \label{fig:Rpoly-passes}
  13005. \end{figure}
  13006. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  13007. for the compilation of \LangPoly{}.
  13008. % TODO: challenge problem: specialization of instantiations
  13009. % Further Reading
  13010. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13011. \chapter{Appendix}
  13012. \section{Interpreters}
  13013. \label{appendix:interp}
  13014. \index{interpreter}
  13015. We provide interpreters for each of the source languages \LangInt{},
  13016. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  13017. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  13018. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  13019. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  13020. and x86 are in the \key{interp.rkt} file.
  13021. \section{Utility Functions}
  13022. \label{appendix:utilities}
  13023. The utility functions described in this section are in the
  13024. \key{utilities.rkt} file of the support code.
  13025. \paragraph{\code{interp-tests}}
  13026. The \key{interp-tests} function runs the compiler passes and the
  13027. interpreters on each of the specified tests to check whether each pass
  13028. is correct. The \key{interp-tests} function has the following
  13029. parameters:
  13030. \begin{description}
  13031. \item[name (a string)] a name to identify the compiler,
  13032. \item[typechecker] a function of exactly one argument that either
  13033. raises an error using the \code{error} function when it encounters a
  13034. type error, or returns \code{\#f} when it encounters a type
  13035. error. If there is no type error, the type checker returns the
  13036. program.
  13037. \item[passes] a list with one entry per pass. An entry is a list with
  13038. four things:
  13039. \begin{enumerate}
  13040. \item a string giving the name of the pass,
  13041. \item the function that implements the pass (a translator from AST
  13042. to AST),
  13043. \item a function that implements the interpreter (a function from
  13044. AST to result value) for the output language,
  13045. \item and a type checker for the output language. Type checkers for
  13046. the $R$ and $C$ languages are provided in the support code. For
  13047. example, the type checkers for \LangVar{} and \LangCVar{} are in
  13048. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  13049. type checker entry is optional. The support code does not provide
  13050. type checkers for the x86 languages.
  13051. \end{enumerate}
  13052. \item[source-interp] an interpreter for the source language. The
  13053. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  13054. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  13055. \item[tests] a list of test numbers that specifies which tests to
  13056. run. (see below)
  13057. \end{description}
  13058. %
  13059. The \key{interp-tests} function assumes that the subdirectory
  13060. \key{tests} has a collection of Racket programs whose names all start
  13061. with the family name, followed by an underscore and then the test
  13062. number, ending with the file extension \key{.rkt}. Also, for each test
  13063. program that calls \code{read} one or more times, there is a file with
  13064. the same name except that the file extension is \key{.in} that
  13065. provides the input for the Racket program. If the test program is
  13066. expected to fail type checking, then there should be an empty file of
  13067. the same name but with extension \key{.tyerr}.
  13068. \paragraph{\code{compiler-tests}}
  13069. runs the compiler passes to generate x86 (a \key{.s} file) and then
  13070. runs the GNU C compiler (gcc) to generate machine code. It runs the
  13071. machine code and checks that the output is $42$. The parameters to the
  13072. \code{compiler-tests} function are similar to those of the
  13073. \code{interp-tests} function, and consist of
  13074. \begin{itemize}
  13075. \item a compiler name (a string),
  13076. \item a type checker,
  13077. \item description of the passes,
  13078. \item name of a test-family, and
  13079. \item a list of test numbers.
  13080. \end{itemize}
  13081. \paragraph{\code{compile-file}}
  13082. takes a description of the compiler passes (see the comment for
  13083. \key{interp-tests}) and returns a function that, given a program file
  13084. name (a string ending in \key{.rkt}), applies all of the passes and
  13085. writes the output to a file whose name is the same as the program file
  13086. name but with \key{.rkt} replaced with \key{.s}.
  13087. \paragraph{\code{read-program}}
  13088. takes a file path and parses that file (it must be a Racket program)
  13089. into an abstract syntax tree.
  13090. \paragraph{\code{parse-program}}
  13091. takes an S-expression representation of an abstract syntax tree and converts it into
  13092. the struct-based representation.
  13093. \paragraph{\code{assert}}
  13094. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  13095. and displays the message \key{msg} if the Boolean \key{bool} is false.
  13096. \paragraph{\code{lookup}}
  13097. % remove discussion of lookup? -Jeremy
  13098. takes a key and an alist, and returns the first value that is
  13099. associated with the given key, if there is one. If not, an error is
  13100. triggered. The alist may contain both immutable pairs (built with
  13101. \key{cons}) and mutable pairs (built with \key{mcons}).
  13102. %The \key{map2} function ...
  13103. \section{x86 Instruction Set Quick-Reference}
  13104. \label{sec:x86-quick-reference}
  13105. \index{x86}
  13106. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  13107. do. We write $A \to B$ to mean that the value of $A$ is written into
  13108. location $B$. Address offsets are given in bytes. The instruction
  13109. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  13110. registers (such as \code{\%rax}), or memory references (such as
  13111. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  13112. reference per instruction. Other operands must be immediates or
  13113. registers.
  13114. \begin{table}[tbp]
  13115. \centering
  13116. \begin{tabular}{l|l}
  13117. \textbf{Instruction} & \textbf{Operation} \\ \hline
  13118. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  13119. \texttt{negq} $A$ & $- A \to A$ \\
  13120. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  13121. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  13122. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  13123. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  13124. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  13125. \texttt{retq} & Pops the return address and jumps to it \\
  13126. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  13127. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  13128. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  13129. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  13130. be an immediate) \\
  13131. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  13132. matches the condition code of the instruction, otherwise go to the
  13133. next instructions. The condition codes are \key{e} for ``equal'',
  13134. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  13135. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  13136. \texttt{jl} $L$ & \\
  13137. \texttt{jle} $L$ & \\
  13138. \texttt{jg} $L$ & \\
  13139. \texttt{jge} $L$ & \\
  13140. \texttt{jmp} $L$ & Jump to label $L$ \\
  13141. \texttt{movq} $A$, $B$ & $A \to B$ \\
  13142. \texttt{movzbq} $A$, $B$ &
  13143. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  13144. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  13145. and the extra bytes of $B$ are set to zero.} \\
  13146. & \\
  13147. & \\
  13148. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  13149. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  13150. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  13151. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  13152. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  13153. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  13154. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  13155. description of the condition codes. $A$ must be a single byte register
  13156. (e.g., \texttt{al} or \texttt{cl}).} \\
  13157. \texttt{setl} $A$ & \\
  13158. \texttt{setle} $A$ & \\
  13159. \texttt{setg} $A$ & \\
  13160. \texttt{setge} $A$ &
  13161. \end{tabular}
  13162. \vspace{5pt}
  13163. \caption{Quick-reference for the x86 instructions used in this book.}
  13164. \label{tab:x86-instr}
  13165. \end{table}
  13166. \cleardoublepage
  13167. \section{Concrete Syntax for Intermediate Languages}
  13168. The concrete syntax of \LangAny{} is defined in
  13169. Figure~\ref{fig:Rany-concrete-syntax}.
  13170. \begin{figure}[tp]
  13171. \centering
  13172. \fbox{
  13173. \begin{minipage}{0.97\textwidth}\small
  13174. \[
  13175. \begin{array}{lcl}
  13176. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  13177. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  13178. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  13179. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  13180. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  13181. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  13182. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  13183. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  13184. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  13185. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  13186. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  13187. \mid \LP\key{void?}\;\Exp\RP \\
  13188. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  13189. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  13190. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  13191. \end{array}
  13192. \]
  13193. \end{minipage}
  13194. }
  13195. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  13196. (Figure~\ref{fig:Rlam-syntax}).}
  13197. \label{fig:Rany-concrete-syntax}
  13198. \end{figure}
  13199. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  13200. defined in Figures~\ref{fig:c0-concrete-syntax},
  13201. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  13202. and \ref{fig:c3-concrete-syntax}, respectively.
  13203. \begin{figure}[tbp]
  13204. \fbox{
  13205. \begin{minipage}{0.96\textwidth}
  13206. \[
  13207. \begin{array}{lcl}
  13208. \Atm &::=& \Int \mid \Var \\
  13209. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  13210. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  13211. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  13212. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  13213. \end{array}
  13214. \]
  13215. \end{minipage}
  13216. }
  13217. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  13218. \label{fig:c0-concrete-syntax}
  13219. \end{figure}
  13220. \begin{figure}[tbp]
  13221. \fbox{
  13222. \begin{minipage}{0.96\textwidth}
  13223. \small
  13224. \[
  13225. \begin{array}{lcl}
  13226. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  13227. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  13228. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  13229. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  13230. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  13231. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  13232. \mid \key{goto}~\itm{label}\key{;}\\
  13233. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  13234. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  13235. \end{array}
  13236. \]
  13237. \end{minipage}
  13238. }
  13239. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  13240. \label{fig:c1-concrete-syntax}
  13241. \end{figure}
  13242. \begin{figure}[tbp]
  13243. \fbox{
  13244. \begin{minipage}{0.96\textwidth}
  13245. \small
  13246. \[
  13247. \begin{array}{lcl}
  13248. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  13249. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  13250. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  13251. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  13252. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  13253. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  13254. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  13255. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  13256. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  13257. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  13258. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  13259. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  13260. \end{array}
  13261. \]
  13262. \end{minipage}
  13263. }
  13264. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  13265. \label{fig:c2-concrete-syntax}
  13266. \end{figure}
  13267. \begin{figure}[tp]
  13268. \fbox{
  13269. \begin{minipage}{0.96\textwidth}
  13270. \small
  13271. \[
  13272. \begin{array}{lcl}
  13273. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  13274. \\
  13275. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  13276. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  13277. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  13278. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  13279. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  13280. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  13281. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  13282. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  13283. \mid \LP\key{collect} \,\itm{int}\RP }\\
  13284. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  13285. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  13286. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  13287. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  13288. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  13289. \LangCFun{} & ::= & \Def\ldots
  13290. \end{array}
  13291. \]
  13292. \end{minipage}
  13293. }
  13294. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  13295. \label{fig:c3-concrete-syntax}
  13296. \end{figure}
  13297. \cleardoublepage
  13298. \addcontentsline{toc}{chapter}{Index}
  13299. \printindex
  13300. \cleardoublepage
  13301. \bibliographystyle{plainnat}
  13302. \bibliography{all}
  13303. \addcontentsline{toc}{chapter}{Bibliography}
  13304. \end{document}
  13305. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  13306. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  13307. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  13308. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  13309. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  13310. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  13311. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  13312. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  13313. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  13314. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  13315. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  13316. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  13317. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  13318. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  13319. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  13320. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  13321. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  13322. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  13323. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  13324. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  13325. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  13326. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  13327. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  13328. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  13329. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  13330. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  13331. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  13332. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  13333. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  13334. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  13335. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  13336. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  13337. % LocalWords: alists arity github unordered pqueue exprs ret param
  13338. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  13339. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  13340. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  13341. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  13342. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  13343. % LocalWords: ValueOf typechecker