book.tex 539 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927
  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. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. There is a magical moment when a programmer presses the ``run'' button
  147. and the software begins to execute. Somehow a program written in a
  148. high-level language is running on a computer that is only capable of
  149. shuffling bits. Here we reveal the wizardry that makes that moment
  150. possible. Beginning with the groundbreaking work of Backus and
  151. colleagues in the 1950s, computer scientists discovered techniques for
  152. constructing programs, called \emph{compilers}, that automatically
  153. translate high-level programs into machine code.
  154. We take you on a journey by constructing your own compiler for a small
  155. but powerful language. Along the way we explain the essential
  156. concepts, algorithms, and data structures that underlie compilers. We
  157. develop your understanding of how programs are mapped onto computer
  158. hardware, which is helpful when reasoning about properties at the
  159. junction between hardware and software such as execution time,
  160. software errors, and security vulnerabilities. For those interested
  161. in pursuing compiler construction, our goal is to provide a
  162. stepping-stone to advanced topics such as just-in-time compilation,
  163. program analysis, and program optimization. For those interested in
  164. designing and implementing their own programming languages, we connect
  165. language design choices to their impact on the compiler its generated
  166. code.
  167. A compiler is typically organized as a sequence of stages that
  168. progressively translates a program to code that runs on hardware. We
  169. take this approach to the extreme by partitioning our compiler into a
  170. large number of \emph{nanopasses}, each of which performs a single
  171. task. This allows us to test the output of each pass in isolation, and
  172. furthermore, allows us to focus our attention making the compiler far
  173. easier to understand.
  174. %% [TODO: easier to understand/debug for those maintaining the compiler,
  175. %% proving correctness]
  176. The most familiar approach to describing compilers is with one pass
  177. per chapter. The problem with that is it obfuscates how language
  178. features motivate design choices in a compiler. We take an
  179. \emph{incremental} approach in which we build a complete compiler in
  180. each chapter, starting with arithmetic and variables and add new
  181. features in subsequent chapters.
  182. Our choice of language features is designed to elicit the fundamental
  183. concepts and algorithms used in compilers.
  184. \begin{itemize}
  185. \item We begin with integer arithmetic and local variables in
  186. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  187. the fundamental tools of compiler construction: \emph{abstract
  188. syntax trees} and \emph{recursive functions}.
  189. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  190. \emph{graph coloring} to assign variables to machine registers.
  191. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  192. an elegant recursive algorithm for mapping expressions to
  193. \emph{control-flow graphs}.
  194. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  195. \emph{garbage collection}.
  196. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  197. but lack lexical scoping, similar to the C programming
  198. language~\citep{Kernighan:1988nx} except that we generate efficient
  199. tail calls. The reader learns about the procedure call stack,
  200. \emph{calling conventions}, and their interaction with register
  201. allocation and garbage collection.
  202. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  203. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  204. \emph{closure conversion}, in which lambdas are translated into a
  205. combination of functions and tuples.
  206. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  207. point the input languages are statically typed. The reader extends
  208. the statically typed language with an \code{Any} type which serves
  209. as a target for compiling the dynamically typed language.
  210. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  211. programming languages with the addition of loops and mutable
  212. variables. These additions elicit the need for \emph{dataflow
  213. analysis} in the register allocator.
  214. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  215. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  216. in which different regions of a program may be static or dynamically
  217. typed. The reader implements runtime support for \emph{proxies} that
  218. allow values to safely move between regions.
  219. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  220. leveraging the \code{Any} type and type casts developed in Chapters
  221. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  222. \end{itemize}
  223. There are many language features that we do not include. Our choices
  224. weigh the incidental complexity of a feature against the fundamental
  225. concepts that it exposes. For example, we include tuples and not
  226. records because they both elicit the study of heap allocation and
  227. garbage collection but records come with more incidental complexity.
  228. Since 2016 this book has served as the textbook for the compiler
  229. course at Indiana University, a 16-week course for upper-level
  230. undergraduates and first-year graduate students.
  231. %
  232. Prior to this course, students learn to program in both imperative and
  233. functional languages, study data structures and algorithms, and take
  234. discrete mathematics.
  235. %
  236. At the beginning of the course, students form groups of 2-4 people.
  237. The groups complete one chapter every two weeks, starting with
  238. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  239. chapters include a challenge problem that we assign to the graduate
  240. students. The last two weeks of the course involve a final project in
  241. which students design and implement a compiler extension of their
  242. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  243. \ref{ch:Rpoly} can be used in support of these projects or they can
  244. replace some of the earlier chapters. For example, a course with an
  245. emphasis on statically-typed imperative languages would skip
  246. Chapter~\ref{ch:Rdyn} in favor of
  247. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  248. the dependencies between chapters.
  249. This book has also been used in compiler courses at California
  250. Polytechnic State University, Rose–Hulman Institute of Technology, and
  251. University of Massachusetts Lowell.
  252. \begin{figure}[tp]
  253. \begin{tikzpicture}[baseline=(current bounding box.center)]
  254. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  255. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  256. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  257. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  258. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  259. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  260. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  261. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  262. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  263. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  264. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  265. \path[->] (C1) edge [above] node {} (C2);
  266. \path[->] (C2) edge [above] node {} (C3);
  267. \path[->] (C3) edge [above] node {} (C4);
  268. \path[->] (C4) edge [above] node {} (C5);
  269. \path[->] (C5) edge [above] node {} (C6);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C8) edge [above] node {} (C10);
  274. \path[->] (C10) edge [above] node {} (C11);
  275. \end{tikzpicture}
  276. \caption{Diagram of chapter dependencies.}
  277. \label{fig:chapter-dependences}
  278. \end{figure}
  279. We use the \href{https://racket-lang.org/}{Racket} language both for
  280. the implementation of the compiler and for the input language, so the
  281. reader should be proficient with Racket or Scheme. There are many
  282. excellent resources for learning Scheme and
  283. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  284. support code for this book is in the \code{github} repository at the
  285. following URL:
  286. \begin{center}\small
  287. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  288. \end{center}
  289. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  290. is helpful but not necessary for the reader to have taken a computer
  291. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  292. of x86-64 assembly language that are needed.
  293. %
  294. We follow the System V calling
  295. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  296. that we generate works with the runtime system (written in C) when it
  297. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  298. operating systems.
  299. %
  300. On the Windows operating system, \code{gcc} uses the Microsoft x64
  301. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  302. assembly code that we generate does \emph{not} work with the runtime
  303. system on Windows. One workaround is to use a virtual machine with
  304. Linux as the guest operating system.
  305. \section*{Acknowledgments}
  306. The tradition of compiler construction at Indiana University goes back
  307. to research and courses on programming languages by Daniel Friedman in
  308. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  309. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  310. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  311. the compiler course and continued the development of Chez Scheme.
  312. %
  313. The compiler course evolved to incorporate novel pedagogical ideas
  314. while also including elements of efficient real-world compilers. One
  315. of Friedman's ideas was to split the compiler into many small
  316. passes. Another idea, called ``the game'', was to test the code
  317. generated by each pass on interpreters.
  318. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  319. developed infrastructure to support this approach and evolved the
  320. course to use even smaller
  321. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  322. design decisions in this book are inspired by the assignment
  323. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  324. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  325. organization of the course made it difficult for students to
  326. understand the rationale for the compiler design. Ghuloum proposed the
  327. incremental approach~\citep{Ghuloum:2006bh}.
  328. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  329. Nystrom, and Michael Wollowski for teaching courses based on early
  330. drafts.
  331. We thank Ronald Garcia for being Jeremy's partner when they took the
  332. compiler course in the early 2000's and especially for finding the bug
  333. that sent the garbage collector on a wild goose chase!
  334. \mbox{}\\
  335. \noindent Jeremy G. Siek \\
  336. Bloomington, Indiana
  337. %Oscar Waddell ??
  338. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  339. \chapter{Preliminaries}
  340. \label{ch:trees-recur}
  341. In this chapter we review the basic tools that are needed to implement
  342. a compiler. Programs are typically input by a programmer as text,
  343. i.e., a sequence of characters. The program-as-text representation is
  344. called \emph{concrete syntax}. We use concrete syntax to concisely
  345. write down and talk about programs. Inside the compiler, we use
  346. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  347. that efficiently supports the operations that the compiler needs to
  348. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  349. syntax tree}\index{AST}\index{program}\index{parse} The translation
  350. from concrete syntax to abstract syntax is a process called
  351. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  352. implementation of parsing in this book. A parser is provided in the
  353. support code for translating from concrete to abstract syntax.
  354. ASTs can be represented in many different ways inside the compiler,
  355. depending on the programming language used to write the compiler.
  356. %
  357. We use Racket's
  358. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  359. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  360. define the abstract syntax of programming languages
  361. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  362. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  363. recursive functions to construct and deconstruct ASTs
  364. (Section~\ref{sec:recursion}). This chapter provides an brief
  365. introduction to these ideas. \index{struct}
  366. \section{Abstract Syntax Trees and Racket Structures}
  367. \label{sec:ast}
  368. Compilers use abstract syntax trees to represent programs because they
  369. often need to ask questions like: for a given part of a program, what
  370. kind of language feature is it? What are its sub-parts? Consider the
  371. program on the left and its AST on the right. This program is an
  372. addition operation and it has two sub-parts, a read operation and a
  373. negation. The negation has another sub-part, the integer constant
  374. \code{8}. By using a tree to represent the program, we can easily
  375. follow the links to go from one part of a program to its sub-parts.
  376. \begin{center}
  377. \begin{minipage}{0.4\textwidth}
  378. \begin{lstlisting}
  379. (+ (read) (- 8))
  380. \end{lstlisting}
  381. \end{minipage}
  382. \begin{minipage}{0.4\textwidth}
  383. \begin{equation}
  384. \begin{tikzpicture}
  385. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  386. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  387. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  388. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  389. \draw[->] (plus) to (read);
  390. \draw[->] (plus) to (minus);
  391. \draw[->] (minus) to (8);
  392. \end{tikzpicture}
  393. \label{eq:arith-prog}
  394. \end{equation}
  395. \end{minipage}
  396. \end{center}
  397. We use the standard terminology for trees to describe ASTs: each
  398. circle above is called a \emph{node}. The arrows connect a node to its
  399. \emph{children} (which are also nodes). The top-most node is the
  400. \emph{root}. Every node except for the root has a \emph{parent} (the
  401. node it is the child of). If a node has no children, it is a
  402. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  403. \index{node}
  404. \index{children}
  405. \index{root}
  406. \index{parent}
  407. \index{leaf}
  408. \index{internal node}
  409. %% Recall that an \emph{symbolic expression} (S-expression) is either
  410. %% \begin{enumerate}
  411. %% \item an atom, or
  412. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  413. %% where $e_1$ and $e_2$ are each an S-expression.
  414. %% \end{enumerate}
  415. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  416. %% null value \code{'()}, etc. We can create an S-expression in Racket
  417. %% simply by writing a backquote (called a quasi-quote in Racket)
  418. %% followed by the textual representation of the S-expression. It is
  419. %% quite common to use S-expressions to represent a list, such as $a, b
  420. %% ,c$ in the following way:
  421. %% \begin{lstlisting}
  422. %% `(a . (b . (c . ())))
  423. %% \end{lstlisting}
  424. %% Each element of the list is in the first slot of a pair, and the
  425. %% second slot is either the rest of the list or the null value, to mark
  426. %% the end of the list. Such lists are so common that Racket provides
  427. %% special notation for them that removes the need for the periods
  428. %% and so many parenthesis:
  429. %% \begin{lstlisting}
  430. %% `(a b c)
  431. %% \end{lstlisting}
  432. %% The following expression creates an S-expression that represents AST
  433. %% \eqref{eq:arith-prog}.
  434. %% \begin{lstlisting}
  435. %% `(+ (read) (- 8))
  436. %% \end{lstlisting}
  437. %% When using S-expressions to represent ASTs, the convention is to
  438. %% represent each AST node as a list and to put the operation symbol at
  439. %% the front of the list. The rest of the list contains the children. So
  440. %% in the above case, the root AST node has operation \code{`+} and its
  441. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  442. %% diagram \eqref{eq:arith-prog}.
  443. %% To build larger S-expressions one often needs to splice together
  444. %% several smaller S-expressions. Racket provides the comma operator to
  445. %% splice an S-expression into a larger one. For example, instead of
  446. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  447. %% we could have first created an S-expression for AST
  448. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  449. %% S-expression.
  450. %% \begin{lstlisting}
  451. %% (define ast1.4 `(- 8))
  452. %% (define ast1.1 `(+ (read) ,ast1.4))
  453. %% \end{lstlisting}
  454. %% In general, the Racket expression that follows the comma (splice)
  455. %% can be any expression that produces an S-expression.
  456. We define a Racket \code{struct} for each kind of node. For this
  457. chapter we require just two kinds of nodes: one for integer constants
  458. and one for primitive operations. The following is the \code{struct}
  459. definition for integer constants.
  460. \begin{lstlisting}
  461. (struct Int (value))
  462. \end{lstlisting}
  463. An integer node includes just one thing: the integer value.
  464. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  465. \begin{lstlisting}
  466. (define eight (Int 8))
  467. \end{lstlisting}
  468. We say that the value created by \code{(Int 8)} is an
  469. \emph{instance} of the \code{Int} structure.
  470. The following is the \code{struct} definition for primitives operations.
  471. \begin{lstlisting}
  472. (struct Prim (op args))
  473. \end{lstlisting}
  474. A primitive operation node includes an operator symbol \code{op}
  475. and a list of children \code{args}. For example, to create
  476. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  477. \begin{lstlisting}
  478. (define neg-eight (Prim '- (list eight)))
  479. \end{lstlisting}
  480. Primitive operations may have zero or more children. The \code{read}
  481. operator has zero children:
  482. \begin{lstlisting}
  483. (define rd (Prim 'read '()))
  484. \end{lstlisting}
  485. whereas the addition operator has two children:
  486. \begin{lstlisting}
  487. (define ast1.1 (Prim '+ (list rd neg-eight)))
  488. \end{lstlisting}
  489. We have made a design choice regarding the \code{Prim} structure.
  490. Instead of using one structure for many different operations
  491. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  492. structure for each operation, as follows.
  493. \begin{lstlisting}
  494. (struct Read ())
  495. (struct Add (left right))
  496. (struct Neg (value))
  497. \end{lstlisting}
  498. The reason we choose to use just one structure is that in many parts
  499. of the compiler the code for the different primitive operators is the
  500. same, so we might as well just write that code once, which is enabled
  501. by using a single structure.
  502. When compiling a program such as \eqref{eq:arith-prog}, we need to
  503. know that the operation associated with the root node is addition and
  504. we need to be able to access its two children. Racket provides pattern
  505. matching to support these kinds of queries, as we see in
  506. Section~\ref{sec:pattern-matching}.
  507. In this book, we often write down the concrete syntax of a program
  508. even when we really have in mind the AST because the concrete syntax
  509. is more concise. We recommend that, in your mind, you always think of
  510. programs as abstract syntax trees.
  511. \section{Grammars}
  512. \label{sec:grammar}
  513. \index{integer}
  514. \index{literal}
  515. \index{constant}
  516. A programming language can be thought of as a \emph{set} of programs.
  517. The set is typically infinite (one can always create larger and larger
  518. programs), so one cannot simply describe a language by listing all of
  519. the programs in the language. Instead we write down a set of rules, a
  520. \emph{grammar}, for building programs. Grammars are often used to
  521. define the concrete syntax of a language, but they can also be used to
  522. describe the abstract syntax. We write our rules in a variant of
  523. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  524. \index{Backus-Naur Form}\index{BNF}
  525. As an example, we describe a small language, named \LangInt{}, that consists of
  526. integers and arithmetic operations.
  527. \index{grammar}
  528. The first grammar rule for the abstract syntax of \LangInt{} says that an
  529. instance of the \code{Int} structure is an expression:
  530. \begin{equation}
  531. \Exp ::= \INT{\Int} \label{eq:arith-int}
  532. \end{equation}
  533. %
  534. Each rule has a left-hand-side and a right-hand-side. The way to read
  535. a rule is that if you have an AST node that matches the
  536. right-hand-side, then you can categorize it according to the
  537. left-hand-side.
  538. %
  539. A name such as $\Exp$ that is defined by the grammar rules is a
  540. \emph{non-terminal}. \index{non-terminal}
  541. %
  542. The name $\Int$ is a also a non-terminal, but instead of defining it
  543. with a grammar rule, we define it with the following explanation. We
  544. make the simplifying design decision that all of the languages in this
  545. book only handle machine-representable integers. On most modern
  546. machines this corresponds to integers represented with 64-bits, i.e.,
  547. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  548. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  549. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  550. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  551. that the sequence of decimals represent an integer in range $-2^{62}$
  552. to $2^{62}-1$.
  553. The second grammar rule is the \texttt{read} operation that receives
  554. an input integer from the user of the program.
  555. \begin{equation}
  556. \Exp ::= \READ{} \label{eq:arith-read}
  557. \end{equation}
  558. The third rule says that, given an $\Exp$ node, the negation of that
  559. node is also an $\Exp$.
  560. \begin{equation}
  561. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  562. \end{equation}
  563. Symbols in typewriter font such as \key{-} and \key{read} are
  564. \emph{terminal} symbols and must literally appear in the program for
  565. the rule to be applicable.
  566. \index{terminal}
  567. We can apply these rules to categorize the ASTs that are in the
  568. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  569. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  570. following AST is an $\Exp$.
  571. \begin{center}
  572. \begin{minipage}{0.4\textwidth}
  573. \begin{lstlisting}
  574. (Prim '- (list (Int 8)))
  575. \end{lstlisting}
  576. \end{minipage}
  577. \begin{minipage}{0.25\textwidth}
  578. \begin{equation}
  579. \begin{tikzpicture}
  580. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  581. \node[draw, circle] (8) at (0, -1.2) {$8$};
  582. \draw[->] (minus) to (8);
  583. \end{tikzpicture}
  584. \label{eq:arith-neg8}
  585. \end{equation}
  586. \end{minipage}
  587. \end{center}
  588. The next grammar rule is for addition expressions:
  589. \begin{equation}
  590. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  591. \end{equation}
  592. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  593. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  594. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  595. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  596. to show that
  597. \begin{lstlisting}
  598. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  599. \end{lstlisting}
  600. is an $\Exp$ in the \LangInt{} language.
  601. If you have an AST for which the above rules do not apply, then the
  602. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  603. is not in \LangInt{} because there are no rules for \code{+} with only one
  604. argument, nor for \key{-} with two arguments. Whenever we define a
  605. language with a grammar, the language only includes those programs
  606. that are justified by the rules.
  607. The last grammar rule for \LangInt{} states that there is a \code{Program}
  608. node to mark the top of the whole program:
  609. \[
  610. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  611. \]
  612. The \code{Program} structure is defined as follows
  613. \begin{lstlisting}
  614. (struct Program (info body))
  615. \end{lstlisting}
  616. where \code{body} is an expression. In later chapters, the \code{info}
  617. part will be used to store auxiliary information but for now it is
  618. just the empty list.
  619. It is common to have many grammar rules with the same left-hand side
  620. but different right-hand sides, such as the rules for $\Exp$ in the
  621. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  622. combine several right-hand-sides into a single rule.
  623. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  624. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  625. defined in Figure~\ref{fig:r0-concrete-syntax}.
  626. The \code{read-program} function provided in \code{utilities.rkt} of
  627. the support code reads a program in from a file (the sequence of
  628. characters in the concrete syntax of Racket) and parses it into an
  629. abstract syntax tree. See the description of \code{read-program} in
  630. Appendix~\ref{appendix:utilities} for more details.
  631. \begin{figure}[tp]
  632. \fbox{
  633. \begin{minipage}{0.96\textwidth}
  634. \[
  635. \begin{array}{rcl}
  636. \begin{array}{rcl}
  637. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  638. \LangInt{} &::=& \Exp
  639. \end{array}
  640. \end{array}
  641. \]
  642. \end{minipage}
  643. }
  644. \caption{The concrete syntax of \LangInt{}.}
  645. \label{fig:r0-concrete-syntax}
  646. \end{figure}
  647. \begin{figure}[tp]
  648. \fbox{
  649. \begin{minipage}{0.96\textwidth}
  650. \[
  651. \begin{array}{rcl}
  652. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  653. &\mid& \ADD{\Exp}{\Exp} \\
  654. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  655. \end{array}
  656. \]
  657. \end{minipage}
  658. }
  659. \caption{The abstract syntax of \LangInt{}.}
  660. \label{fig:r0-syntax}
  661. \end{figure}
  662. \section{Pattern Matching}
  663. \label{sec:pattern-matching}
  664. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  665. the parts of an AST node. Racket provides the \texttt{match} form to
  666. access the parts of a structure. Consider the following example and
  667. the output on the right. \index{match} \index{pattern matching}
  668. \begin{center}
  669. \begin{minipage}{0.5\textwidth}
  670. \begin{lstlisting}
  671. (match ast1.1
  672. [(Prim op (list child1 child2))
  673. (print op)])
  674. \end{lstlisting}
  675. \end{minipage}
  676. \vrule
  677. \begin{minipage}{0.25\textwidth}
  678. \begin{lstlisting}
  679. '+
  680. \end{lstlisting}
  681. \end{minipage}
  682. \end{center}
  683. In the above example, the \texttt{match} form takes an AST
  684. \eqref{eq:arith-prog} and binds its parts to the three pattern
  685. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  686. prints out the operator. In general, a match clause consists of a
  687. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  688. recursively defined to be either a pattern variable, a structure name
  689. followed by a pattern for each of the structure's arguments, or an
  690. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  691. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  692. and Chapter 9 of The Racket
  693. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  694. for a complete description of \code{match}.)
  695. %
  696. The body of a match clause may contain arbitrary Racket code. The
  697. pattern variables can be used in the scope of the body, such as
  698. \code{op} in \code{(print op)}.
  699. A \code{match} form may contain several clauses, as in the following
  700. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  701. the AST. The \code{match} proceeds through the clauses in order,
  702. checking whether the pattern can match the input AST. The body of the
  703. first clause that matches is executed. The output of \code{leaf?} for
  704. several ASTs is shown on the right.
  705. \begin{center}
  706. \begin{minipage}{0.6\textwidth}
  707. \begin{lstlisting}
  708. (define (leaf? arith)
  709. (match arith
  710. [(Int n) #t]
  711. [(Prim 'read '()) #t]
  712. [(Prim '- (list e1)) #f]
  713. [(Prim '+ (list e1 e2)) #f]))
  714. (leaf? (Prim 'read '()))
  715. (leaf? (Prim '- (list (Int 8))))
  716. (leaf? (Int 8))
  717. \end{lstlisting}
  718. \end{minipage}
  719. \vrule
  720. \begin{minipage}{0.25\textwidth}
  721. \begin{lstlisting}
  722. #t
  723. #f
  724. #t
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. When writing a \code{match}, we refer to the grammar definition to
  729. identify which non-terminal we are expecting to match against, then we
  730. make sure that 1) we have one clause for each alternative of that
  731. non-terminal and 2) that the pattern in each clause corresponds to the
  732. corresponding right-hand side of a grammar rule. For the \code{match}
  733. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  734. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  735. alternatives, so the \code{match} has 4 clauses. The pattern in each
  736. clause corresponds to the right-hand side of a grammar rule. For
  737. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  738. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  739. patterns, replace non-terminals such as $\Exp$ with pattern variables
  740. of your choice (e.g. \code{e1} and \code{e2}).
  741. \section{Recursive Functions}
  742. \label{sec:recursion}
  743. \index{recursive function}
  744. Programs are inherently recursive. For example, an \LangInt{} expression is
  745. often made of smaller expressions. Thus, the natural way to process an
  746. entire program is with a recursive function. As a first example of
  747. such a recursive function, we define \texttt{exp?} below, which takes
  748. an arbitrary value and determines whether or not it is an \LangInt{}
  749. expression.
  750. %
  751. We say that a function is defined by \emph{structural recursion} when
  752. it is defined using a sequence of match clauses that correspond to a
  753. grammar, and the body of each clause makes a recursive call on each
  754. child node.\footnote{This principle of structuring code according to
  755. the data definition is advocated in the book \emph{How to Design
  756. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  757. Below we also define a second function, named \code{Rint?}, that
  758. determines whether an AST is an \LangInt{} program. In general we can
  759. expect to write one recursive function to handle each non-terminal in
  760. a grammar.\index{structural recursion}
  761. %
  762. \begin{center}
  763. \begin{minipage}{0.7\textwidth}
  764. \begin{lstlisting}
  765. (define (exp? ast)
  766. (match ast
  767. [(Int n) #t]
  768. [(Prim 'read '()) #t]
  769. [(Prim '- (list e)) (exp? e)]
  770. [(Prim '+ (list e1 e2))
  771. (and (exp? e1) (exp? e2))]
  772. [else #f]))
  773. (define (Rint? ast)
  774. (match ast
  775. [(Program '() e) (exp? e)]
  776. [else #f]))
  777. (Rint? (Program '() ast1.1)
  778. (Rint? (Program '()
  779. (Prim '- (list (Prim 'read '())
  780. (Prim '+ (list (Num 8)))))))
  781. \end{lstlisting}
  782. \end{minipage}
  783. \vrule
  784. \begin{minipage}{0.25\textwidth}
  785. \begin{lstlisting}
  786. #t
  787. #f
  788. \end{lstlisting}
  789. \end{minipage}
  790. \end{center}
  791. You may be tempted to merge the two functions into one, like this:
  792. \begin{center}
  793. \begin{minipage}{0.5\textwidth}
  794. \begin{lstlisting}
  795. (define (Rint? ast)
  796. (match ast
  797. [(Int n) #t]
  798. [(Prim 'read '()) #t]
  799. [(Prim '- (list e)) (Rint? e)]
  800. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  801. [(Program '() e) (Rint? e)]
  802. [else #f]))
  803. \end{lstlisting}
  804. \end{minipage}
  805. \end{center}
  806. %
  807. Sometimes such a trick will save a few lines of code, especially when
  808. it comes to the \code{Program} wrapper. Yet this style is generally
  809. \emph{not} recommended because it can get you into trouble.
  810. %
  811. For example, the above function is subtly wrong:
  812. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  813. returns true when it should return false.
  814. \section{Interpreters}
  815. \label{sec:interp-Rint}
  816. \index{interpreter}
  817. In general, the intended behavior of a program is defined by the
  818. specification of the language. For example, the Scheme language is
  819. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  820. defined in its reference manual~\citep{plt-tr}. In this book we use
  821. interpreters to specify each language that we consider. An interpreter
  822. that is designated as the definition of a language is called a
  823. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  824. \index{definitional interpreter} We warm up by creating a definitional
  825. interpreter for the \LangInt{} language, which serves as a second example
  826. of structural recursion. The \texttt{interp-Rint} function is defined in
  827. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  828. input program followed by a call to the \lstinline{interp-exp} helper
  829. function, which in turn has one match clause per grammar rule for
  830. \LangInt{} expressions.
  831. \begin{figure}[tp]
  832. \begin{lstlisting}
  833. (define (interp-exp e)
  834. (match e
  835. [(Int n) n]
  836. [(Prim 'read '())
  837. (define r (read))
  838. (cond [(fixnum? r) r]
  839. [else (error 'interp-exp "read expected an integer" r)])]
  840. [(Prim '- (list e))
  841. (define v (interp-exp e))
  842. (fx- 0 v)]
  843. [(Prim '+ (list e1 e2))
  844. (define v1 (interp-exp e1))
  845. (define v2 (interp-exp e2))
  846. (fx+ v1 v2)]))
  847. (define (interp-Rint p)
  848. (match p
  849. [(Program '() e) (interp-exp e)]))
  850. \end{lstlisting}
  851. \caption{Interpreter for the \LangInt{} language.}
  852. \label{fig:interp-Rint}
  853. \end{figure}
  854. Let us consider the result of interpreting a few \LangInt{} programs. The
  855. following program adds two integers.
  856. \begin{lstlisting}
  857. (+ 10 32)
  858. \end{lstlisting}
  859. The result is \key{42}, the answer to life, the universe, and
  860. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  861. Galaxy} by Douglas Adams.}.
  862. %
  863. We wrote the above program in concrete syntax whereas the parsed
  864. abstract syntax is:
  865. \begin{lstlisting}
  866. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  867. \end{lstlisting}
  868. The next example demonstrates that expressions may be nested within
  869. each other, in this case nesting several additions and negations.
  870. \begin{lstlisting}
  871. (+ 10 (- (+ 12 20)))
  872. \end{lstlisting}
  873. What is the result of the above program?
  874. As mentioned previously, the \LangInt{} language does not support
  875. arbitrarily-large integers, but only $63$-bit integers, so we
  876. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  877. in Racket.
  878. Suppose
  879. \[
  880. n = 999999999999999999
  881. \]
  882. which indeed fits in $63$-bits. What happens when we run the
  883. following program in our interpreter?
  884. \begin{lstlisting}
  885. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  886. \end{lstlisting}
  887. It produces an error:
  888. \begin{lstlisting}
  889. fx+: result is not a fixnum
  890. \end{lstlisting}
  891. We establish the convention that if running the definitional
  892. interpreter on a program produces an error then the meaning of that
  893. program is \emph{unspecified}\index{unspecified behavior}, unless the
  894. error is a \code{trapped-error}. A compiler for the language is under
  895. no obligations regarding programs with unspecified behavior; it does
  896. not have to produce an executable, and if it does, that executable can
  897. do anything. On the other hand, if the error is a
  898. \code{trapped-error}, then the compiler must produce an executable and
  899. it is required to report that an error occurred. To signal an error,
  900. exit with a return code of \code{255}. The interpreters in chapters
  901. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  902. \code{trapped-error}.
  903. %% This convention applies to the languages defined in this
  904. %% book, as a way to simplify the student's task of implementing them,
  905. %% but this convention is not applicable to all programming languages.
  906. %%
  907. Moving on to the last feature of the \LangInt{} language, the \key{read}
  908. operation prompts the user of the program for an integer. Recall that
  909. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  910. \code{8}. So if we run
  911. \begin{lstlisting}
  912. (interp-Rint (Program '() ast1.1))
  913. \end{lstlisting}
  914. and if the input is \code{50}, the result is \code{42}.
  915. We include the \key{read} operation in \LangInt{} so a clever student
  916. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  917. during compilation to obtain the output and then generates the trivial
  918. code to produce the output. (Yes, a clever student did this in the
  919. first instance of this course.)
  920. The job of a compiler is to translate a program in one language into a
  921. program in another language so that the output program behaves the
  922. same way as the input program does. This idea is depicted in the
  923. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  924. $\mathcal{L}_2$, and a definitional interpreter for each language.
  925. Given a compiler that translates from language $\mathcal{L}_1$ to
  926. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  927. compiler must translate it into some program $P_2$ such that
  928. interpreting $P_1$ and $P_2$ on their respective interpreters with
  929. same input $i$ yields the same output $o$.
  930. \begin{equation} \label{eq:compile-correct}
  931. \begin{tikzpicture}[baseline=(current bounding box.center)]
  932. \node (p1) at (0, 0) {$P_1$};
  933. \node (p2) at (3, 0) {$P_2$};
  934. \node (o) at (3, -2.5) {$o$};
  935. \path[->] (p1) edge [above] node {compile} (p2);
  936. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  937. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  938. \end{tikzpicture}
  939. \end{equation}
  940. In the next section we see our first example of a compiler.
  941. \section{Example Compiler: a Partial Evaluator}
  942. \label{sec:partial-evaluation}
  943. In this section we consider a compiler that translates \LangInt{} programs
  944. into \LangInt{} programs that may be more efficient, that is, this compiler
  945. is an optimizer. This optimizer eagerly computes the parts of the
  946. program that do not depend on any inputs, a process known as
  947. \emph{partial evaluation}~\citep{Jones:1993uq}.
  948. \index{partial evaluation}
  949. For example, given the following program
  950. \begin{lstlisting}
  951. (+ (read) (- (+ 5 3)))
  952. \end{lstlisting}
  953. our compiler will translate it into the program
  954. \begin{lstlisting}
  955. (+ (read) -8)
  956. \end{lstlisting}
  957. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  958. evaluator for the \LangInt{} language. The output of the partial evaluator
  959. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  960. recursion over $\Exp$ is captured in the \code{pe-exp} function
  961. whereas the code for partially evaluating the negation and addition
  962. operations is factored into two separate helper functions:
  963. \code{pe-neg} and \code{pe-add}. The input to these helper
  964. functions is the output of partially evaluating the children.
  965. \begin{figure}[tp]
  966. \begin{lstlisting}
  967. (define (pe-neg r)
  968. (match r
  969. [(Int n) (Int (fx- 0 n))]
  970. [else (Prim '- (list r))]))
  971. (define (pe-add r1 r2)
  972. (match* (r1 r2)
  973. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  974. [(_ _) (Prim '+ (list r1 r2))]))
  975. (define (pe-exp e)
  976. (match e
  977. [(Int n) (Int n)]
  978. [(Prim 'read '()) (Prim 'read '())]
  979. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  980. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  981. (define (pe-Rint p)
  982. (match p
  983. [(Program '() e) (Program '() (pe-exp e))]))
  984. \end{lstlisting}
  985. \caption{A partial evaluator for \LangInt{}.}
  986. \label{fig:pe-arith}
  987. \end{figure}
  988. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  989. arguments are integers and if they are, perform the appropriate
  990. arithmetic. Otherwise, they create an AST node for the arithmetic
  991. operation.
  992. To gain some confidence that the partial evaluator is correct, we can
  993. test whether it produces programs that get the same result as the
  994. input programs. That is, we can test whether it satisfies Diagram
  995. \ref{eq:compile-correct}. The following code runs the partial
  996. evaluator on several examples and tests the output program. The
  997. \texttt{parse-program} and \texttt{assert} functions are defined in
  998. Appendix~\ref{appendix:utilities}.\\
  999. \begin{minipage}{1.0\textwidth}
  1000. \begin{lstlisting}
  1001. (define (test-pe p)
  1002. (assert "testing pe-Rint"
  1003. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1004. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1005. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1006. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1007. \end{lstlisting}
  1008. \end{minipage}
  1009. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1010. \chapter{Integers and Variables}
  1011. \label{ch:Rvar}
  1012. This chapter is about compiling a subset of Racket to x86-64 assembly
  1013. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1014. integer arithmetic and local variable binding. We often refer to
  1015. x86-64 simply as x86. The chapter begins with a description of the
  1016. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1017. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1018. is large so we discuss only the instructions needed for compiling
  1019. \LangVar{}. We introduce more x86 instructions in later chapters.
  1020. After introducing \LangVar{} and x86, we reflect on their differences
  1021. and come up with a plan to break down the translation from \LangVar{}
  1022. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1023. rest of the sections in this chapter give detailed hints regarding
  1024. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1025. We hope to give enough hints that the well-prepared reader, together
  1026. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1027. a couple weeks. To give the reader a feeling for the scale of this
  1028. first compiler, the instructor solution for the \LangVar{} compiler is
  1029. approximately 500 lines of code.
  1030. \section{The \LangVar{} Language}
  1031. \label{sec:s0}
  1032. \index{variable}
  1033. The \LangVar{} language extends the \LangInt{} language with variable
  1034. definitions. The concrete syntax of the \LangVar{} language is defined by
  1035. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1036. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  1037. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1038. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1039. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1040. \key{Program} struct to mark the top of the program.
  1041. %% The $\itm{info}$
  1042. %% field of the \key{Program} structure contains an \emph{association
  1043. %% list} (a list of key-value pairs) that is used to communicate
  1044. %% auxiliary data from one compiler pass the next.
  1045. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1046. exhibit several compilation techniques.
  1047. \begin{figure}[tp]
  1048. \centering
  1049. \fbox{
  1050. \begin{minipage}{0.96\textwidth}
  1051. \[
  1052. \begin{array}{rcl}
  1053. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1054. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1055. \LangVar{} &::=& \Exp
  1056. \end{array}
  1057. \]
  1058. \end{minipage}
  1059. }
  1060. \caption{The concrete syntax of \LangVar{}.}
  1061. \label{fig:r1-concrete-syntax}
  1062. \end{figure}
  1063. \begin{figure}[tp]
  1064. \centering
  1065. \fbox{
  1066. \begin{minipage}{0.96\textwidth}
  1067. \[
  1068. \begin{array}{rcl}
  1069. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1070. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1071. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1072. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1073. \end{array}
  1074. \]
  1075. \end{minipage}
  1076. }
  1077. \caption{The abstract syntax of \LangVar{}.}
  1078. \label{fig:r1-syntax}
  1079. \end{figure}
  1080. Let us dive further into the syntax and semantics of the \LangVar{}
  1081. language. The \key{let} feature defines a variable for use within its
  1082. body and initializes the variable with the value of an expression.
  1083. The abstract syntax for \key{let} is defined in
  1084. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1085. \begin{lstlisting}
  1086. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1087. \end{lstlisting}
  1088. For example, the following program initializes \code{x} to $32$ and then
  1089. evaluates the body \code{(+ 10 x)}, producing $42$.
  1090. \begin{lstlisting}
  1091. (let ([x (+ 12 20)]) (+ 10 x))
  1092. \end{lstlisting}
  1093. When there are multiple \key{let}'s for the same variable, the closest
  1094. enclosing \key{let} is used. That is, variable definitions overshadow
  1095. prior definitions. Consider the following program with two \key{let}'s
  1096. that define variables named \code{x}. Can you figure out the result?
  1097. \begin{lstlisting}
  1098. (let ([x 32]) (+ (let ([x 10]) x) x))
  1099. \end{lstlisting}
  1100. For the purposes of depicting which variable uses correspond to which
  1101. definitions, the following shows the \code{x}'s annotated with
  1102. subscripts to distinguish them. Double check that your answer for the
  1103. above is the same as your answer for this annotated version of the
  1104. program.
  1105. \begin{lstlisting}
  1106. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1107. \end{lstlisting}
  1108. The initializing expression is always evaluated before the body of the
  1109. \key{let}, so in the following, the \key{read} for \code{x} is
  1110. performed before the \key{read} for \code{y}. Given the input
  1111. $52$ then $10$, the following produces $42$ (not $-42$).
  1112. \begin{lstlisting}
  1113. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1114. \end{lstlisting}
  1115. \subsection{Extensible Interpreters via Method Overriding}
  1116. \label{sec:extensible-interp}
  1117. To prepare for discussing the interpreter for \LangVar{}, we need to
  1118. explain why we choose to implement the interpreter using
  1119. object-oriented programming, that is, as a collection of methods
  1120. inside of a class. Throughout this book we define many interpreters,
  1121. one for each of the languages that we study. Because each language
  1122. builds on the prior one, there is a lot of commonality between their
  1123. interpreters. We want to write down those common parts just once
  1124. instead of many times. A naive approach would be to have, for example,
  1125. the interpreter for \LangIf{} handle all of the new features in that
  1126. language and then have a default case that dispatches to the
  1127. interpreter for \LangVar{}. The following code sketches this idea.
  1128. \begin{center}
  1129. \begin{minipage}{0.45\textwidth}
  1130. \begin{lstlisting}
  1131. (define (interp-Rvar e)
  1132. (match e
  1133. [(Prim '- (list e))
  1134. (fx- 0 (interp-Rvar e))]
  1135. ...))
  1136. \end{lstlisting}
  1137. \end{minipage}
  1138. \begin{minipage}{0.45\textwidth}
  1139. \begin{lstlisting}
  1140. (define (interp-Rif e)
  1141. (match e
  1142. [(If cnd thn els)
  1143. (match (interp-Rif cnd)
  1144. [#t (interp-Rif thn)]
  1145. [#f (interp-Rif els)])]
  1146. ...
  1147. [else (interp-Rvar e)]))
  1148. \end{lstlisting}
  1149. \end{minipage}
  1150. \end{center}
  1151. The problem with this approach is that it does not handle situations
  1152. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1153. feature, like the \code{-} operator, as in the following program.
  1154. \begin{lstlisting}
  1155. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1156. \end{lstlisting}
  1157. If we invoke \code{interp-Rif} on this program, it dispatches to
  1158. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1159. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1160. which is an \code{If}. But there is no case for \code{If} in
  1161. \code{interp-Rvar}, so we get an error!
  1162. To make our interpreters extensible we need something called
  1163. \emph{open recursion}\index{open recursion}, where the tying of the
  1164. recursive knot is delayed to when the functions are
  1165. composed. Object-oriented languages provide open recursion with the
  1166. late-binding of overridden methods\index{method overriding}. The
  1167. following code sketches this idea for interpreting \LangVar{} and
  1168. \LangIf{} using the
  1169. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1170. \index{class} feature of Racket. We define one class for each
  1171. language and define a method for interpreting expressions inside each
  1172. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1173. and the method \code{interp-exp} in \LangIf{} overrides the
  1174. \code{interp-exp} in \LangVar{}. Note that the default case of
  1175. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1176. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1177. that dispatches to the \code{interp-exp} in \LangVar{}.
  1178. \begin{center}
  1179. \begin{minipage}{0.45\textwidth}
  1180. \begin{lstlisting}
  1181. (define interp-Rvar-class
  1182. (class object%
  1183. (define/public (interp-exp e)
  1184. (match e
  1185. [(Prim '- (list e))
  1186. (fx- 0 (interp-exp e))]
  1187. ...))
  1188. ...))
  1189. \end{lstlisting}
  1190. \end{minipage}
  1191. \begin{minipage}{0.45\textwidth}
  1192. \begin{lstlisting}
  1193. (define interp-Rif-class
  1194. (class interp-Rvar-class
  1195. (define/override (interp-exp e)
  1196. (match e
  1197. [(If cnd thn els)
  1198. (match (interp-exp cnd)
  1199. [#t (interp-exp thn)]
  1200. [#f (interp-exp els)])]
  1201. ...
  1202. [else (super interp-exp e)]))
  1203. ...
  1204. ))
  1205. \end{lstlisting}
  1206. \end{minipage}
  1207. \end{center}
  1208. Getting back to the troublesome example, repeated here:
  1209. \begin{lstlisting}
  1210. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1211. \end{lstlisting}
  1212. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1213. expression by creating an object of the \LangIf{} class and sending it the
  1214. \code{interp-exp} method with the argument \code{e0}.
  1215. \begin{lstlisting}
  1216. (send (new interp-Rif-class) interp-exp e0)
  1217. \end{lstlisting}
  1218. The default case of \code{interp-exp} in \LangIf{} handles it by
  1219. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1220. handles the \code{-} operator. But then for the recursive method call,
  1221. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1222. \code{If} is handled correctly. Thus, method overriding gives us the
  1223. open recursion that we need to implement our interpreters in an
  1224. extensible way.
  1225. \newpage
  1226. \subsection{Definitional Interpreter for \LangVar{}}
  1227. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1228. \small
  1229. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1230. An \emph{association list} (alist) is a list of key-value pairs.
  1231. For example, we can map people to their ages with an alist.
  1232. \index{alist}\index{association list}
  1233. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1234. (define ages
  1235. '((jane . 25) (sam . 24) (kate . 45)))
  1236. \end{lstlisting}
  1237. The \emph{dictionary} interface is for mapping keys to values.
  1238. Every alist implements this interface. \index{dictionary} The package
  1239. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1240. provides many functions for working with dictionaries. Here
  1241. are a few of them:
  1242. \begin{description}
  1243. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1244. returns the value associated with the given $\itm{key}$.
  1245. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1246. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1247. but otherwise is the same as $\itm{dict}$.
  1248. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1249. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1250. of keys and values in $\itm{dict}$. For example, the following
  1251. creates a new alist in which the ages are incremented.
  1252. \end{description}
  1253. \vspace{-10pt}
  1254. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1255. (for/list ([(k v) (in-dict ages)])
  1256. (cons k (add1 v)))
  1257. \end{lstlisting}
  1258. \end{tcolorbox}
  1259. \end{wrapfigure}
  1260. Having justified the use of classes and methods to implement
  1261. interpreters, we turn to the definitional interpreter for \LangVar{}
  1262. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1263. \LangInt{} but adds two new \key{match} cases for variables and
  1264. \key{let}. For \key{let} we need a way to communicate the value bound
  1265. to a variable to all the uses of the variable. To accomplish this, we
  1266. maintain a mapping from variables to values. Throughout the compiler
  1267. we often need to map variables to information about them. We refer to
  1268. these mappings as
  1269. \emph{environments}\index{environment}.\footnote{Another common term
  1270. for environment in the compiler literature is \emph{symbol
  1271. table}\index{symbol table}.}
  1272. %
  1273. For simplicity, we use an association list (alist) to represent the
  1274. environment. The sidebar to the right gives a brief introduction to
  1275. alists and the \code{racket/dict} package. The \code{interp-exp}
  1276. function takes the current environment, \code{env}, as an extra
  1277. parameter. When the interpreter encounters a variable, it finds the
  1278. corresponding value using the \code{dict-ref} function. When the
  1279. interpreter encounters a \key{Let}, it evaluates the initializing
  1280. expression, extends the environment with the result value bound to the
  1281. variable, using \code{dict-set}, then evaluates the body of the
  1282. \key{Let}.
  1283. \begin{figure}[tp]
  1284. \begin{lstlisting}
  1285. (define interp-Rvar-class
  1286. (class object%
  1287. (super-new)
  1288. (define/public ((interp-exp env) e)
  1289. (match e
  1290. [(Int n) n]
  1291. [(Prim 'read '())
  1292. (define r (read))
  1293. (cond [(fixnum? r) r]
  1294. [else (error 'interp-exp "expected an integer" r)])]
  1295. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1296. [(Prim '+ (list e1 e2))
  1297. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1298. [(Var x) (dict-ref env x)]
  1299. [(Let x e body)
  1300. (define new-env (dict-set env x ((interp-exp env) e)))
  1301. ((interp-exp new-env) body)]))
  1302. (define/public (interp-program p)
  1303. (match p
  1304. [(Program '() e) ((interp-exp '()) e)]))
  1305. ))
  1306. (define (interp-Rvar p)
  1307. (send (new interp-Rvar-class) interp-program p))
  1308. \end{lstlisting}
  1309. \caption{Interpreter for the \LangVar{} language.}
  1310. \label{fig:interp-Rvar}
  1311. \end{figure}
  1312. The goal for this chapter is to implement a compiler that translates
  1313. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1314. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1315. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1316. is, they output the same integer $n$. We depict this correctness
  1317. criteria in the following diagram.
  1318. \[
  1319. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1320. \node (p1) at (0, 0) {$P_1$};
  1321. \node (p2) at (4, 0) {$P_2$};
  1322. \node (o) at (4, -2) {$n$};
  1323. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1324. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1325. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1326. \end{tikzpicture}
  1327. \]
  1328. In the next section we introduce the \LangXInt{} subset of x86 that
  1329. suffices for compiling \LangVar{}.
  1330. \section{The \LangXInt{} Assembly Language}
  1331. \label{sec:x86}
  1332. \index{x86}
  1333. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1334. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1335. assembler.
  1336. %
  1337. A program begins with a \code{main} label followed by a sequence of
  1338. instructions. The \key{globl} directive says that the \key{main}
  1339. procedure is externally visible, which is necessary so that the
  1340. operating system can call it. In the grammar, ellipses such as
  1341. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1342. \ldots$ is a sequence of instructions.\index{instruction}
  1343. %
  1344. An x86 program is stored in the computer's memory. For our purposes,
  1345. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1346. values. The computer has a \emph{program counter} (PC)\index{program
  1347. counter}\index{PC} stored in the \code{rip} register that points to
  1348. the address of the next instruction to be executed. For most
  1349. instructions, the program counter is incremented after the instruction
  1350. is executed, so it points to the next instruction in memory. Most x86
  1351. instructions take two operands, where each operand is either an
  1352. integer constant (called \emph{immediate value}\index{immediate
  1353. value}), a \emph{register}\index{register}, or a memory location.
  1354. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1355. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1356. && \key{r8} \mid \key{r9} \mid \key{r10}
  1357. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1358. \mid \key{r14} \mid \key{r15}}
  1359. \begin{figure}[tp]
  1360. \fbox{
  1361. \begin{minipage}{0.96\textwidth}
  1362. \[
  1363. \begin{array}{lcl}
  1364. \Reg &::=& \allregisters{} \\
  1365. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1366. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1367. \key{subq} \; \Arg\key{,} \Arg \mid
  1368. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1369. && \key{callq} \; \mathit{label} \mid
  1370. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1371. && \itm{label}\key{:}\; \Instr \\
  1372. \LangXInt{} &::= & \key{.globl main}\\
  1373. & & \key{main:} \; \Instr\ldots
  1374. \end{array}
  1375. \]
  1376. \end{minipage}
  1377. }
  1378. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1379. \label{fig:x86-int-concrete}
  1380. \end{figure}
  1381. A register is a special kind of variable. Each one holds a 64-bit
  1382. value; there are 16 general-purpose registers in the computer and
  1383. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1384. is written with a \key{\%} followed by the register name, such as
  1385. \key{\%rax}.
  1386. An immediate value is written using the notation \key{\$}$n$ where $n$
  1387. is an integer.
  1388. %
  1389. %
  1390. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1391. which obtains the address stored in register $r$ and then adds $n$
  1392. bytes to the address. The resulting address is used to load or store
  1393. to memory depending on whether it occurs as a source or destination
  1394. argument of an instruction.
  1395. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1396. source $s$ and destination $d$, applies the arithmetic operation, then
  1397. writes the result back to the destination $d$.
  1398. %
  1399. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1400. stores the result in $d$.
  1401. %
  1402. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1403. specified by the label and $\key{retq}$ returns from a procedure to
  1404. its caller.
  1405. %
  1406. We discuss procedure calls in more detail later in this chapter and in
  1407. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1408. updates the program counter to the address of the instruction after
  1409. the specified label.
  1410. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1411. all of the x86 instructions used in this book.
  1412. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1413. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1414. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1415. adds $32$ to the $10$ in \key{rax} and
  1416. puts the result, $42$, back into \key{rax}.
  1417. %
  1418. The last instruction, \key{retq}, finishes the \key{main} function by
  1419. returning the integer in \key{rax} to the operating system. The
  1420. operating system interprets this integer as the program's exit
  1421. code. By convention, an exit code of 0 indicates that a program
  1422. completed successfully, and all other exit codes indicate various
  1423. errors. Nevertheless, in this book we return the result of the program
  1424. as the exit code.
  1425. \begin{figure}[tbp]
  1426. \begin{lstlisting}
  1427. .globl main
  1428. main:
  1429. movq $10, %rax
  1430. addq $32, %rax
  1431. retq
  1432. \end{lstlisting}
  1433. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1434. \label{fig:p0-x86}
  1435. \end{figure}
  1436. The x86 assembly language varies in a couple ways depending on what
  1437. operating system it is assembled in. The code examples shown here are
  1438. correct on Linux and most Unix-like platforms, but when assembled on
  1439. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1440. as in \key{\_main}.
  1441. We exhibit the use of memory for storing intermediate results in the
  1442. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1443. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1444. memory called the \emph{procedure call stack} (or \emph{stack} for
  1445. short). \index{stack}\index{procedure call stack} The stack consists
  1446. of a separate \emph{frame}\index{frame} for each procedure call. The
  1447. memory layout for an individual frame is shown in
  1448. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1449. \emph{stack pointer}\index{stack pointer} and points to the item at
  1450. the top of the stack. The stack grows downward in memory, so we
  1451. increase the size of the stack by subtracting from the stack pointer.
  1452. In the context of a procedure call, the \emph{return
  1453. address}\index{return address} is the instruction after the call
  1454. instruction on the caller side. The function call instruction,
  1455. \code{callq}, pushes the return address onto the stack prior to
  1456. jumping to the procedure. The register \key{rbp} is the \emph{base
  1457. pointer}\index{base pointer} and is used to access variables that
  1458. are stored in the frame of the current procedure call. The base
  1459. pointer of the caller is pushed onto the stack after the return
  1460. address and then the base pointer is set to the location of the old
  1461. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1462. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1463. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1464. \begin{figure}[tbp]
  1465. \begin{lstlisting}
  1466. start:
  1467. movq $10, -8(%rbp)
  1468. negq -8(%rbp)
  1469. movq -8(%rbp), %rax
  1470. addq $52, %rax
  1471. jmp conclusion
  1472. .globl main
  1473. main:
  1474. pushq %rbp
  1475. movq %rsp, %rbp
  1476. subq $16, %rsp
  1477. jmp start
  1478. conclusion:
  1479. addq $16, %rsp
  1480. popq %rbp
  1481. retq
  1482. \end{lstlisting}
  1483. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1484. \label{fig:p1-x86}
  1485. \end{figure}
  1486. \begin{figure}[tbp]
  1487. \centering
  1488. \begin{tabular}{|r|l|} \hline
  1489. Position & Contents \\ \hline
  1490. 8(\key{\%rbp}) & return address \\
  1491. 0(\key{\%rbp}) & old \key{rbp} \\
  1492. -8(\key{\%rbp}) & variable $1$ \\
  1493. -16(\key{\%rbp}) & variable $2$ \\
  1494. \ldots & \ldots \\
  1495. 0(\key{\%rsp}) & variable $n$\\ \hline
  1496. \end{tabular}
  1497. \caption{Memory layout of a frame.}
  1498. \label{fig:frame}
  1499. \end{figure}
  1500. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1501. control is transferred from the operating system to the \code{main}
  1502. function. The operating system issues a \code{callq main} instruction
  1503. which pushes its return address on the stack and then jumps to
  1504. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1505. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1506. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1507. alignment (because the \code{callq} pushed the return address). The
  1508. first three instructions are the typical \emph{prelude}\index{prelude}
  1509. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1510. pointer for the caller onto the stack and subtracts $8$ from the stack
  1511. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1512. base pointer so that it points the location of the old base
  1513. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1514. pointer down to make enough room for storing variables. This program
  1515. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1516. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1517. functions. The last instruction of the prelude is \code{jmp start},
  1518. which transfers control to the instructions that were generated from
  1519. the Racket expression \code{(+ 52 (- 10))}.
  1520. The first instruction under the \code{start} label is
  1521. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1522. %
  1523. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1524. %
  1525. The next instruction moves the $-10$ from variable $1$ into the
  1526. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1527. the value in \code{rax}, updating its contents to $42$.
  1528. The three instructions under the label \code{conclusion} are the
  1529. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1530. two instructions restore the \code{rsp} and \code{rbp} registers to
  1531. the state they were in at the beginning of the procedure. The
  1532. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1533. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1534. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1535. instruction, \key{retq}, jumps back to the procedure that called this
  1536. one and adds $8$ to the stack pointer.
  1537. The compiler needs a convenient representation for manipulating x86
  1538. programs, so we define an abstract syntax for x86 in
  1539. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1540. \LangXInt{}. The main difference compared to the concrete syntax of
  1541. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1542. allowed in front of every instructions. Instead instructions are
  1543. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1544. label associated with every block, which is why the \key{X86Program}
  1545. struct includes an alist mapping labels to blocks. The reason for this
  1546. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1547. introduce conditional branching. The \code{Block} structure includes
  1548. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1549. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1550. $\itm{info}$ field should contain an empty list. Also, regarding the
  1551. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1552. integer for representing the arity of the function, i.e., the number
  1553. of arguments, which is helpful to know during register allocation
  1554. (Chapter~\ref{ch:register-allocation-Rvar}).
  1555. \begin{figure}[tp]
  1556. \fbox{
  1557. \begin{minipage}{0.98\textwidth}
  1558. \small
  1559. \[
  1560. \begin{array}{lcl}
  1561. \Reg &::=& \allregisters{} \\
  1562. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1563. \mid \DEREF{\Reg}{\Int} \\
  1564. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1565. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1566. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1567. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1568. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1569. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1570. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1571. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1572. \end{array}
  1573. \]
  1574. \end{minipage}
  1575. }
  1576. \caption{The abstract syntax of \LangXInt{} assembly.}
  1577. \label{fig:x86-int-ast}
  1578. \end{figure}
  1579. \section{Planning the trip to x86 via the \LangCVar{} language}
  1580. \label{sec:plan-s0-x86}
  1581. To compile one language to another it helps to focus on the
  1582. differences between the two languages because the compiler will need
  1583. to bridge those differences. What are the differences between \LangVar{}
  1584. and x86 assembly? Here are some of the most important ones:
  1585. \begin{enumerate}
  1586. \item[(a)] x86 arithmetic instructions typically have two arguments
  1587. and update the second argument in place. In contrast, \LangVar{}
  1588. arithmetic operations take two arguments and produce a new value.
  1589. An x86 instruction may have at most one memory-accessing argument.
  1590. Furthermore, some instructions place special restrictions on their
  1591. arguments.
  1592. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1593. expression, whereas x86 instructions restrict their arguments to be
  1594. integers constants, registers, and memory locations.
  1595. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1596. sequence of instructions and jumps to labeled positions, whereas in
  1597. \LangVar{} the order of evaluation is a left-to-right depth-first
  1598. traversal of the abstract syntax tree.
  1599. \item[(d)] A program in \LangVar{} can have any number of variables
  1600. whereas x86 has 16 registers and the procedure calls stack.
  1601. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1602. same name. In x86, registers have unique names and memory locations
  1603. have unique addresses.
  1604. \end{enumerate}
  1605. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1606. the problem into several steps, dealing with the above differences one
  1607. at a time. Each of these steps is called a \emph{pass} of the
  1608. compiler.\index{pass}\index{compiler pass}
  1609. %
  1610. This terminology comes from the way each step passes over the AST of
  1611. the program.
  1612. %
  1613. We begin by sketching how we might implement each pass, and give them
  1614. names. We then figure out an ordering of the passes and the
  1615. input/output language for each pass. The very first pass has
  1616. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1617. its output language. In between we can choose whichever language is
  1618. most convenient for expressing the output of each pass, whether that
  1619. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1620. our own design. Finally, to implement each pass we write one
  1621. recursive function per non-terminal in the grammar of the input
  1622. language of the pass. \index{intermediate language}
  1623. \begin{description}
  1624. \item[\key{select-instructions}] handles the difference between
  1625. \LangVar{} operations and x86 instructions. This pass converts each
  1626. \LangVar{} operation to a short sequence of instructions that
  1627. accomplishes the same task.
  1628. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1629. a primitive operation is a variable or integer, that is, an
  1630. \emph{atomic} expression. We refer to non-atomic expressions as
  1631. \emph{complex}. This pass introduces temporary variables to hold
  1632. the results of complex subexpressions.\index{atomic
  1633. expression}\index{complex expression}%
  1634. \footnote{The subexpressions of an operation are often called
  1635. operators and operands which explains the presence of
  1636. \code{opera*} in the name of this pass.}
  1637. \item[\key{explicate-control}] makes the execution order of the
  1638. program explicit. It convert the abstract syntax tree representation
  1639. into a control-flow graph in which each node contains a sequence of
  1640. statements and the edges between nodes say which nodes contain jumps
  1641. to other nodes.
  1642. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1643. registers or stack locations in x86.
  1644. \item[\key{uniquify}] deals with the shadowing of variables by
  1645. renaming every variable to a unique name.
  1646. \end{description}
  1647. The next question is: in what order should we apply these passes? This
  1648. question can be challenging because it is difficult to know ahead of
  1649. time which orderings will be better (easier to implement, produce more
  1650. efficient code, etc.) so oftentimes trial-and-error is
  1651. involved. Nevertheless, we can try to plan ahead and make educated
  1652. choices regarding the ordering.
  1653. What should be the ordering of \key{explicate-control} with respect to
  1654. \key{uniquify}? The \key{uniquify} pass should come first because
  1655. \key{explicate-control} changes all the \key{let}-bound variables to
  1656. become local variables whose scope is the entire program, which would
  1657. confuse variables with the same name.
  1658. %
  1659. We place \key{remove-complex-opera*} before \key{explicate-control}
  1660. because the later removes the \key{let} form, but it is convenient to
  1661. use \key{let} in the output of \key{remove-complex-opera*}.
  1662. %
  1663. The ordering of \key{uniquify} with respect to
  1664. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1665. \key{uniquify} to come first.
  1666. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1667. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1668. learn that, in x86, registers are used for passing arguments to
  1669. functions and it is preferable to assign parameters to their
  1670. corresponding registers. On the other hand, by selecting instructions
  1671. first we may run into a dead end in \key{assign-homes}. Recall that
  1672. only one argument of an x86 instruction may be a memory access but
  1673. \key{assign-homes} might fail to assign even one of them to a
  1674. register.
  1675. %
  1676. A sophisticated approach is to iteratively repeat the two passes until
  1677. a solution is found. However, to reduce implementation complexity we
  1678. recommend a simpler approach in which \key{select-instructions} comes
  1679. first, followed by the \key{assign-homes}, then a third pass named
  1680. \key{patch-instructions} that uses a reserved register to fix
  1681. outstanding problems.
  1682. \begin{figure}[tbp]
  1683. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1684. \node (Rvar) at (0,2) {\large \LangVar{}};
  1685. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1686. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1687. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1688. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1689. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1690. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1691. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1692. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1693. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1694. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1695. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1696. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1697. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1698. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1699. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1700. \end{tikzpicture}
  1701. \caption{Diagram of the passes for compiling \LangVar{}. }
  1702. \label{fig:Rvar-passes}
  1703. \end{figure}
  1704. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1705. passes and identifies the input and output language of each pass. The
  1706. last pass, \key{print-x86}, converts from the abstract syntax of
  1707. \LangXInt{} to the concrete syntax. In the following two sections
  1708. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1709. dialect of x86. The remainder of this chapter gives hints regarding
  1710. the implementation of each of the compiler passes in
  1711. Figure~\ref{fig:Rvar-passes}.
  1712. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1713. %% are programs that are still in the \LangVar{} language, though the
  1714. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1715. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1716. %% %
  1717. %% The output of \key{explicate-control} is in an intermediate language
  1718. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1719. %% syntax, which we introduce in the next section. The
  1720. %% \key{select-instruction} pass translates from \LangCVar{} to
  1721. %% \LangXVar{}. The \key{assign-homes} and
  1722. %% \key{patch-instructions}
  1723. %% passes input and output variants of x86 assembly.
  1724. \subsection{The \LangCVar{} Intermediate Language}
  1725. The output of \key{explicate-control} is similar to the $C$
  1726. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1727. categories for expressions and statements, so we name it \LangCVar{}. The
  1728. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1729. (The concrete syntax for \LangCVar{} is in the Appendix,
  1730. Figure~\ref{fig:c0-concrete-syntax}.)
  1731. %
  1732. The \LangCVar{} language supports the same operators as \LangVar{} but
  1733. the arguments of operators are restricted to atomic
  1734. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1735. assignment statements which can be executed in sequence using the
  1736. \key{Seq} form. A sequence of statements always ends with
  1737. \key{Return}, a guarantee that is baked into the grammar rules for
  1738. \itm{tail}. The naming of this non-terminal comes from the term
  1739. \emph{tail position}\index{tail position}, which refers to an
  1740. expression that is the last one to execute within a function.
  1741. A \LangCVar{} program consists of a control-flow graph represented as
  1742. an alist mapping labels to tails. This is more general than necessary
  1743. for the present chapter, as we do not yet introduce \key{goto} for
  1744. jumping to labels, but it saves us from having to change the syntax in
  1745. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1746. \key{start}, and the whole program is its tail.
  1747. %
  1748. The $\itm{info}$ field of the \key{CProgram} form, after the
  1749. \key{explicate-control} pass, contains a mapping from the symbol
  1750. \key{locals} to a list of variables, that is, a list of all the
  1751. variables used in the program. At the start of the program, these
  1752. variables are uninitialized; they become initialized on their first
  1753. assignment.
  1754. \begin{figure}[tbp]
  1755. \fbox{
  1756. \begin{minipage}{0.96\textwidth}
  1757. \[
  1758. \begin{array}{lcl}
  1759. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1760. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1761. &\mid& \ADD{\Atm}{\Atm}\\
  1762. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1763. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1764. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1765. \end{array}
  1766. \]
  1767. \end{minipage}
  1768. }
  1769. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1770. \label{fig:c0-syntax}
  1771. \end{figure}
  1772. The definitional interpreter for \LangCVar{} is in the support code,
  1773. in the file \code{interp-Cvar.rkt}.
  1774. \subsection{The \LangXVar{} dialect}
  1775. The \LangXVar{} language is the output of the pass
  1776. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1777. number of program-scope variables and removes the restrictions
  1778. regarding instruction arguments.
  1779. \section{Uniquify Variables}
  1780. \label{sec:uniquify-Rvar}
  1781. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1782. programs in which every \key{let} binds a unique variable name. For
  1783. example, the \code{uniquify} pass should translate the program on the
  1784. left into the program on the right. \\
  1785. \begin{tabular}{lll}
  1786. \begin{minipage}{0.4\textwidth}
  1787. \begin{lstlisting}
  1788. (let ([x 32])
  1789. (+ (let ([x 10]) x) x))
  1790. \end{lstlisting}
  1791. \end{minipage}
  1792. &
  1793. $\Rightarrow$
  1794. &
  1795. \begin{minipage}{0.4\textwidth}
  1796. \begin{lstlisting}
  1797. (let ([x.1 32])
  1798. (+ (let ([x.2 10]) x.2) x.1))
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. \end{tabular} \\
  1802. %
  1803. The following is another example translation, this time of a program
  1804. with a \key{let} nested inside the initializing expression of another
  1805. \key{let}.\\
  1806. \begin{tabular}{lll}
  1807. \begin{minipage}{0.4\textwidth}
  1808. \begin{lstlisting}
  1809. (let ([x (let ([x 4])
  1810. (+ x 1))])
  1811. (+ x 2))
  1812. \end{lstlisting}
  1813. \end{minipage}
  1814. &
  1815. $\Rightarrow$
  1816. &
  1817. \begin{minipage}{0.4\textwidth}
  1818. \begin{lstlisting}
  1819. (let ([x.2 (let ([x.1 4])
  1820. (+ x.1 1))])
  1821. (+ x.2 2))
  1822. \end{lstlisting}
  1823. \end{minipage}
  1824. \end{tabular}
  1825. We recommend implementing \code{uniquify} by creating a structurally
  1826. recursive function named \code{uniquify-exp} that mostly just copies
  1827. an expression. However, when encountering a \key{let}, it should
  1828. generate a unique name for the variable and associate the old name
  1829. with the new name in an alist.\footnote{The Racket function
  1830. \code{gensym} is handy for generating unique variable names.} The
  1831. \code{uniquify-exp} function needs to access this alist when it gets
  1832. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1833. for the alist.
  1834. The skeleton of the \code{uniquify-exp} function is shown in
  1835. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1836. convenient to partially apply it to an alist and then apply it to
  1837. different expressions, as in the last case for primitive operations in
  1838. Figure~\ref{fig:uniquify-Rvar}. The
  1839. %
  1840. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1841. %
  1842. form of Racket is useful for transforming each element of a list to
  1843. produce a new list.\index{for/list}
  1844. \begin{exercise}
  1845. \normalfont % I don't like the italics for exercises. -Jeremy
  1846. Complete the \code{uniquify} pass by filling in the blanks in
  1847. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1848. variables and for the \key{let} form in the file \code{compiler.rkt}
  1849. in the support code.
  1850. \end{exercise}
  1851. \begin{figure}[tbp]
  1852. \begin{lstlisting}
  1853. (define (uniquify-exp env)
  1854. (lambda (e)
  1855. (match e
  1856. [(Var x) ___]
  1857. [(Int n) (Int n)]
  1858. [(Let x e body) ___]
  1859. [(Prim op es)
  1860. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1861. (define (uniquify p)
  1862. (match p
  1863. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1864. \end{lstlisting}
  1865. \caption{Skeleton for the \key{uniquify} pass.}
  1866. \label{fig:uniquify-Rvar}
  1867. \end{figure}
  1868. \begin{exercise}
  1869. \normalfont % I don't like the italics for exercises. -Jeremy
  1870. Create five \LangVar{} programs that exercise the most interesting
  1871. parts of the \key{uniquify} pass, that is, the programs should include
  1872. \key{let} forms, variables, and variables that overshadow each other.
  1873. The five programs should be placed in the subdirectory named
  1874. \key{tests} and the file names should start with \code{var\_test\_}
  1875. followed by a unique integer and end with the file extension
  1876. \key{.rkt}.
  1877. %
  1878. The \key{run-tests.rkt} script in the support code checks whether the
  1879. output programs produce the same result as the input programs. The
  1880. script uses the \key{interp-tests} function
  1881. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1882. your \key{uniquify} pass on the example programs. The \code{passes}
  1883. parameter of \key{interp-tests} is a list that should have one entry
  1884. for each pass in your compiler. For now, define \code{passes} to
  1885. contain just one entry for \code{uniquify} as follows.
  1886. \begin{lstlisting}
  1887. (define passes
  1888. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1889. \end{lstlisting}
  1890. Run the \key{run-tests.rkt} script in the support code to check
  1891. whether the output programs produce the same result as the input
  1892. programs.
  1893. \end{exercise}
  1894. \section{Remove Complex Operands}
  1895. \label{sec:remove-complex-opera-Rvar}
  1896. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1897. \LangVar{} programs in which the arguments of operations are atomic
  1898. expressions. Put another way, this pass removes complex
  1899. operands\index{complex operand}, such as the expression \code{(- 10)}
  1900. in the program below. This is accomplished by introducing a new
  1901. \key{let}-bound variable, binding the complex operand to the new
  1902. variable, and then using the new variable in place of the complex
  1903. operand, as shown in the output of \code{remove-complex-opera*} on the
  1904. right.\\
  1905. \begin{tabular}{lll}
  1906. \begin{minipage}{0.4\textwidth}
  1907. % var_test_19.rkt
  1908. \begin{lstlisting}
  1909. (+ 52 (- 10))
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. &
  1913. $\Rightarrow$
  1914. &
  1915. \begin{minipage}{0.4\textwidth}
  1916. \begin{lstlisting}
  1917. (let ([tmp.1 (- 10)])
  1918. (+ 52 tmp.1))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \end{tabular}
  1922. \begin{figure}[tp]
  1923. \centering
  1924. \fbox{
  1925. \begin{minipage}{0.96\textwidth}
  1926. \[
  1927. \begin{array}{rcl}
  1928. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1929. \Exp &::=& \Atm \mid \READ{} \\
  1930. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1931. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1932. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1933. \end{array}
  1934. \]
  1935. \end{minipage}
  1936. }
  1937. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1938. \label{fig:r1-anf-syntax}
  1939. \end{figure}
  1940. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1941. this pass, the language \LangVarANF{}. The only difference is that
  1942. operator arguments are required to be atomic expressions. In the
  1943. literature, this is called \emph{administrative normal form}, or ANF
  1944. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  1945. normal form} \index{ANF}
  1946. We recommend implementing this pass with two mutually recursive
  1947. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1948. \code{rco-atom} to subexpressions that are required to be atomic and
  1949. to apply \code{rco-exp} to subexpressions that can be atomic or
  1950. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1951. \LangVar{} expression as input. The \code{rco-exp} function returns an
  1952. expression. The \code{rco-atom} function returns two things: an
  1953. atomic expression and alist mapping temporary variables to complex
  1954. subexpressions. You can return multiple things from a function using
  1955. Racket's \key{values} form and you can receive multiple things from a
  1956. function call using the \key{define-values} form. If you are not
  1957. familiar with these features, review the Racket documentation. Also,
  1958. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1959. form is useful for applying a function to each
  1960. element of a list, in the case where the function returns multiple
  1961. values.
  1962. \index{for/lists}
  1963. The following shows the output of \code{rco-atom} on the expression
  1964. \code{(- 10)} (using concrete syntax to be concise).
  1965. \begin{tabular}{lll}
  1966. \begin{minipage}{0.4\textwidth}
  1967. \begin{lstlisting}
  1968. (- 10)
  1969. \end{lstlisting}
  1970. \end{minipage}
  1971. &
  1972. $\Rightarrow$
  1973. &
  1974. \begin{minipage}{0.4\textwidth}
  1975. \begin{lstlisting}
  1976. tmp.1
  1977. ((tmp.1 . (- 10)))
  1978. \end{lstlisting}
  1979. \end{minipage}
  1980. \end{tabular}
  1981. Take special care of programs such as the following one that binds a
  1982. variable to an atomic expression. You should leave such variable
  1983. bindings unchanged, as shown in to the program on the right \\
  1984. \begin{tabular}{lll}
  1985. \begin{minipage}{0.4\textwidth}
  1986. % var_test_20.rkt
  1987. \begin{lstlisting}
  1988. (let ([a 42])
  1989. (let ([b a])
  1990. b))
  1991. \end{lstlisting}
  1992. \end{minipage}
  1993. &
  1994. $\Rightarrow$
  1995. &
  1996. \begin{minipage}{0.4\textwidth}
  1997. \begin{lstlisting}
  1998. (let ([a 42])
  1999. (let ([b a])
  2000. b))
  2001. \end{lstlisting}
  2002. \end{minipage}
  2003. \end{tabular} \\
  2004. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2005. produce the following output with unnecessary temporary variables.\\
  2006. \begin{minipage}{0.4\textwidth}
  2007. \begin{lstlisting}
  2008. (let ([tmp.1 42])
  2009. (let ([a tmp.1])
  2010. (let ([tmp.2 a])
  2011. (let ([b tmp.2])
  2012. b))))
  2013. \end{lstlisting}
  2014. \end{minipage}
  2015. \begin{exercise}\normalfont
  2016. %
  2017. Implement the \code{remove-complex-opera*} function in
  2018. \code{compiler.rkt}.
  2019. %
  2020. Create three new \LangInt{} programs that exercise the interesting
  2021. code in the \code{remove-complex-opera*} pass (Following the same file
  2022. name guidelines as before.).
  2023. %
  2024. In the \code{run-tests.rkt} script, add the following entry to the
  2025. list of \code{passes} and then run the script to test your compiler.
  2026. \begin{lstlisting}
  2027. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2028. \end{lstlisting}
  2029. While debugging your compiler, it is often useful to see the
  2030. intermediate programs that are output from each pass. To print the
  2031. intermeidate programs, place the following before the call to
  2032. \code{interp-tests} in \code{run-tests.rkt}.
  2033. \begin{lstlisting}
  2034. (debug-level 1)
  2035. \end{lstlisting}
  2036. \end{exercise}
  2037. \section{Explicate Control}
  2038. \label{sec:explicate-control-Rvar}
  2039. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2040. programs that make the order of execution explicit in their
  2041. syntax. For now this amounts to flattening \key{let} constructs into a
  2042. sequence of assignment statements. For example, consider the following
  2043. \LangVar{} program.\\
  2044. % var_test_11.rkt
  2045. \begin{minipage}{0.96\textwidth}
  2046. \begin{lstlisting}
  2047. (let ([y (let ([x 20])
  2048. (+ x (let ([x 22]) x)))])
  2049. y)
  2050. \end{lstlisting}
  2051. \end{minipage}\\
  2052. %
  2053. The output of the previous pass and of \code{explicate-control} is
  2054. shown below. Recall that the right-hand-side of a \key{let} executes
  2055. before its body, so the order of evaluation for this program is to
  2056. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2057. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2058. output of \code{explicate-control} makes this ordering explicit.\\
  2059. \begin{tabular}{lll}
  2060. \begin{minipage}{0.4\textwidth}
  2061. \begin{lstlisting}
  2062. (let ([y (let ([x.1 20])
  2063. (let ([x.2 22])
  2064. (+ x.1 x.2)))])
  2065. y)
  2066. \end{lstlisting}
  2067. \end{minipage}
  2068. &
  2069. $\Rightarrow$
  2070. &
  2071. \begin{minipage}{0.4\textwidth}
  2072. \begin{lstlisting}[language=C]
  2073. start:
  2074. x.1 = 20;
  2075. x.2 = 22;
  2076. y = (+ x.1 x.2);
  2077. return y;
  2078. \end{lstlisting}
  2079. \end{minipage}
  2080. \end{tabular}
  2081. \begin{figure}[tbp]
  2082. \begin{lstlisting}
  2083. (define (explicate-tail e)
  2084. (match e
  2085. [(Var x) ___]
  2086. [(Int n) (Return (Int n))]
  2087. [(Let x rhs body) ___]
  2088. [(Prim op es) ___]
  2089. [else (error "explicate-tail unhandled case" e)]))
  2090. (define (explicate-assign e x cont)
  2091. (match e
  2092. [(Var x) ___]
  2093. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2094. [(Let y rhs body) ___]
  2095. [(Prim op es) ___]
  2096. [else (error "explicate-assign unhandled case" e)]))
  2097. (define (explicate-control p)
  2098. (match p
  2099. [(Program info body) ___]))
  2100. \end{lstlisting}
  2101. \caption{Skeleton for the \key{explicate-control} pass.}
  2102. \label{fig:explicate-control-Rvar}
  2103. \end{figure}
  2104. The organization of this pass depends on the notion of tail position
  2105. that we have alluded to earlier. Formally, \emph{tail
  2106. position}\index{tail position} in the context of \LangVar{} is
  2107. defined recursively by the following two rules.
  2108. \begin{enumerate}
  2109. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2110. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2111. \end{enumerate}
  2112. We recommend implementing \code{explicate-control} using two mutually
  2113. recursive functions, \code{explicate-tail} and
  2114. \code{explicate-assign}, as suggested in the skeleton code in
  2115. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2116. function should be applied to expressions in tail position whereas the
  2117. \code{explicate-assign} should be applied to expressions that occur on
  2118. the right-hand-side of a \key{let}.
  2119. %
  2120. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2121. input and produces a \Tail{} in \LangCVar{} (see
  2122. Figure~\ref{fig:c0-syntax}).
  2123. %
  2124. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2125. the variable that it is to be assigned to, and a \Tail{} in
  2126. \LangCVar{} for the code that will come after the assignment. The
  2127. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2128. The \code{explicate-assign} function is in accumulator-passing style
  2129. in that the \code{cont} parameter is used for accumulating the
  2130. output. The reader might be tempted to instead organize
  2131. \code{explicate-assign} in a more direct fashion, without the
  2132. \code{cont} parameter and perhaps using \code{append} to combine
  2133. statements. We warn against that alternative because the
  2134. accumulator-passing style is key to how we generate high-quality code
  2135. for conditional expressions in Chapter~\ref{ch:Rif}.
  2136. \begin{exercise}\normalfont
  2137. %
  2138. Implement the \code{explicate-control} function in
  2139. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2140. exercise the code in \code{explicate-control}.
  2141. %
  2142. In the \code{run-tests.rkt} script, add the following entry to the
  2143. list of \code{passes} and then run the script to test your compiler.
  2144. \begin{lstlisting}
  2145. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2146. \end{lstlisting}
  2147. \end{exercise}
  2148. \section{Select Instructions}
  2149. \label{sec:select-Rvar}
  2150. \index{instruction selection}
  2151. In the \code{select-instructions} pass we begin the work of
  2152. translating from \LangCVar{} to \LangXVar{}. The target language of
  2153. this pass is a variant of x86 that still uses variables, so we add an
  2154. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2155. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2156. recommend implementing the \code{select-instructions} with
  2157. three auxiliary functions, one for each of the non-terminals of
  2158. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2159. The cases for $\Atm$ are straightforward, variables stay
  2160. the same and integer constants are changed to immediates:
  2161. $\INT{n}$ changes to $\IMM{n}$.
  2162. Next we consider the cases for $\Stmt$, starting with arithmetic
  2163. operations. For example, consider the addition operation. We can use
  2164. the \key{addq} instruction, but it performs an in-place update. So we
  2165. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2166. add $\itm{arg}_2$ to \itm{var}. \\
  2167. \begin{tabular}{lll}
  2168. \begin{minipage}{0.4\textwidth}
  2169. \begin{lstlisting}
  2170. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2171. \end{lstlisting}
  2172. \end{minipage}
  2173. &
  2174. $\Rightarrow$
  2175. &
  2176. \begin{minipage}{0.4\textwidth}
  2177. \begin{lstlisting}
  2178. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2179. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2180. \end{lstlisting}
  2181. \end{minipage}
  2182. \end{tabular} \\
  2183. %
  2184. There are also cases that require special care to avoid generating
  2185. needlessly complicated code. For example, if one of the arguments of
  2186. the addition is the same variable as the left-hand side of the
  2187. assignment, then there is no need for the extra move instruction. The
  2188. assignment statement can be translated into a single \key{addq}
  2189. instruction as follows.\\
  2190. \begin{tabular}{lll}
  2191. \begin{minipage}{0.4\textwidth}
  2192. \begin{lstlisting}
  2193. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2194. \end{lstlisting}
  2195. \end{minipage}
  2196. &
  2197. $\Rightarrow$
  2198. &
  2199. \begin{minipage}{0.4\textwidth}
  2200. \begin{lstlisting}
  2201. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2202. \end{lstlisting}
  2203. \end{minipage}
  2204. \end{tabular}
  2205. The \key{read} operation does not have a direct counterpart in x86
  2206. assembly, so we provide this functionality with the function
  2207. \code{read\_int} in the file \code{runtime.c}, written in
  2208. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2209. functionality in this file as the \emph{runtime system}\index{runtime
  2210. system}, or simply the \emph{runtime} for short. When compiling your
  2211. generated x86 assembly code, you need to compile \code{runtime.c} to
  2212. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2213. \code{-c}) and link it into the executable. For our purposes of code
  2214. generation, all you need to do is translate an assignment of
  2215. \key{read} into a call to the \code{read\_int} function followed by a
  2216. move from \code{rax} to the left-hand-side variable. (Recall that the
  2217. return value of a function goes into \code{rax}.) \\
  2218. \begin{tabular}{lll}
  2219. \begin{minipage}{0.3\textwidth}
  2220. \begin{lstlisting}
  2221. |$\itm{var}$| = (read);
  2222. \end{lstlisting}
  2223. \end{minipage}
  2224. &
  2225. $\Rightarrow$
  2226. &
  2227. \begin{minipage}{0.3\textwidth}
  2228. \begin{lstlisting}
  2229. callq read_int
  2230. movq %rax, |$\itm{var}$|
  2231. \end{lstlisting}
  2232. \end{minipage}
  2233. \end{tabular}
  2234. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2235. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2236. assignment to the \key{rax} register followed by a jump to the
  2237. conclusion of the program (so the conclusion needs to be labeled).
  2238. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2239. recursively and then append the resulting instructions.
  2240. \begin{exercise}
  2241. \normalfont Implement the \key{select-instructions} pass in
  2242. \code{compiler.rkt}. Create three new example programs that are
  2243. designed to exercise all of the interesting cases in this pass.
  2244. %
  2245. In the \code{run-tests.rkt} script, add the following entry to the
  2246. list of \code{passes} and then run the script to test your compiler.
  2247. \begin{lstlisting}
  2248. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2249. \end{lstlisting}
  2250. \end{exercise}
  2251. \section{Assign Homes}
  2252. \label{sec:assign-Rvar}
  2253. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2254. \LangXVar{} programs that no longer use program variables.
  2255. Thus, the \key{assign-homes} pass is responsible for placing all of
  2256. the program variables in registers or on the stack. For runtime
  2257. efficiency, it is better to place variables in registers, but as there
  2258. are only 16 registers, some programs must necessarily resort to
  2259. placing some variables on the stack. In this chapter we focus on the
  2260. mechanics of placing variables on the stack. We study an algorithm for
  2261. placing variables in registers in
  2262. Chapter~\ref{ch:register-allocation-Rvar}.
  2263. Consider again the following \LangVar{} program from
  2264. Section~\ref{sec:remove-complex-opera-Rvar}.
  2265. % var_test_20.rkt
  2266. \begin{lstlisting}
  2267. (let ([a 42])
  2268. (let ([b a])
  2269. b))
  2270. \end{lstlisting}
  2271. The output of \code{select-instructions} is shown on the left and the
  2272. output of \code{assign-homes} on the right. In this example, we
  2273. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2274. variable \code{b} to location \code{-16(\%rbp)}.\\
  2275. \begin{tabular}{l}
  2276. \begin{minipage}{0.4\textwidth}
  2277. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2278. locals-types:
  2279. a : Integer, b : Integer
  2280. start:
  2281. movq $42, a
  2282. movq a, b
  2283. movq b, %rax
  2284. jmp conclusion
  2285. \end{lstlisting}
  2286. \end{minipage}
  2287. {$\Rightarrow$}
  2288. \begin{minipage}{0.4\textwidth}
  2289. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2290. stack-space: 16
  2291. start:
  2292. movq $42, -8(%rbp)
  2293. movq -8(%rbp), -16(%rbp)
  2294. movq -16(%rbp), %rax
  2295. jmp conclusion
  2296. \end{lstlisting}
  2297. \end{minipage}
  2298. \end{tabular}
  2299. The \code{locals-types} entry in the $\itm{info}$ of the
  2300. \code{X86Program} node is an alist mapping all the variables in the
  2301. program to their types (for now just \code{Integer}). The
  2302. \code{assign-homes} pass should replace all uses of those variables
  2303. with stack locations. As an aside, the \code{locals-types} entry is
  2304. computed by \code{type-check-Cvar} in the support code, which installs
  2305. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2306. be propagated to the \code{X86Program} node.
  2307. In the process of assigning variables to stack locations, it is
  2308. convenient for you to compute and store the size of the frame (in
  2309. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2310. the key \code{stack-space}, which is needed later to generate the
  2311. conclusion of the \code{main} procedure. The x86-64 standard requires
  2312. the frame size to be a multiple of 16 bytes.\index{frame}
  2313. \begin{exercise}\normalfont
  2314. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2315. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2316. \Block{}. We recommend that the auxiliary functions take an extra
  2317. parameter that is an alist mapping variable names to homes (stack
  2318. locations for now).
  2319. %
  2320. In the \code{run-tests.rkt} script, add the following entry to the
  2321. list of \code{passes} and then run the script to test your compiler.
  2322. \begin{lstlisting}
  2323. (list "assign homes" assign-homes interp-x86-0)
  2324. \end{lstlisting}
  2325. \end{exercise}
  2326. \section{Patch Instructions}
  2327. \label{sec:patch-s0}
  2328. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2329. \LangXInt{} by making sure that each instruction adheres to the
  2330. restriction that at most one argument of an instruction may be a
  2331. memory reference.
  2332. We return to the following example.
  2333. % var_test_20.rkt
  2334. \begin{lstlisting}
  2335. (let ([a 42])
  2336. (let ([b a])
  2337. b))
  2338. \end{lstlisting}
  2339. The \key{assign-homes} pass produces the following output
  2340. for this program. \\
  2341. \begin{minipage}{0.5\textwidth}
  2342. \begin{lstlisting}
  2343. stack-space: 16
  2344. start:
  2345. movq $42, -8(%rbp)
  2346. movq -8(%rbp), -16(%rbp)
  2347. movq -16(%rbp), %rax
  2348. jmp conclusion
  2349. \end{lstlisting}
  2350. \end{minipage}\\
  2351. The second \key{movq} instruction is problematic because both
  2352. arguments are stack locations. We suggest fixing this problem by
  2353. moving from the source location to the register \key{rax} and then
  2354. from \key{rax} to the destination location, as follows.
  2355. \begin{lstlisting}
  2356. movq -8(%rbp), %rax
  2357. movq %rax, -16(%rbp)
  2358. \end{lstlisting}
  2359. \begin{exercise}
  2360. \normalfont Implement the \key{patch-instructions} pass in
  2361. \code{compiler.rkt}. Create three new example programs that are
  2362. designed to exercise all of the interesting cases in this pass.
  2363. %
  2364. In the \code{run-tests.rkt} script, add the following entry to the
  2365. list of \code{passes} and then run the script to test your compiler.
  2366. \begin{lstlisting}
  2367. (list "patch instructions" patch-instructions interp-x86-0)
  2368. \end{lstlisting}
  2369. \end{exercise}
  2370. \section{Print x86}
  2371. \label{sec:print-x86}
  2372. The last step of the compiler from \LangVar{} to x86 is to convert the
  2373. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2374. string representation (defined in
  2375. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2376. \key{string-append} functions are useful in this regard. The main work
  2377. that this step needs to perform is to create the \key{main} function
  2378. and the standard instructions for its prelude and conclusion, as shown
  2379. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2380. know the amount of space needed for the stack frame, which you can
  2381. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2382. the \key{X86Program} node.
  2383. When running on Mac OS X, you compiler should prefix an underscore to
  2384. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2385. useful for determining which operating system the compiler is running
  2386. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2387. \begin{exercise}\normalfont
  2388. %
  2389. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2390. %
  2391. In the \code{run-tests.rkt} script, add the following entry to the
  2392. list of \code{passes} and then run the script to test your compiler.
  2393. \begin{lstlisting}
  2394. (list "print x86" print-x86 #f)
  2395. \end{lstlisting}
  2396. %
  2397. Uncomment the call to the \key{compiler-tests} function
  2398. (Appendix~\ref{appendix:utilities}), which tests your complete
  2399. compiler by executing the generated x86 code. Compile the provided
  2400. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2401. script to test your compiler.
  2402. \end{exercise}
  2403. \section{Challenge: Partial Evaluator for \LangVar{}}
  2404. \label{sec:pe-Rvar}
  2405. \index{partial evaluation}
  2406. This section describes optional challenge exercises that involve
  2407. adapting and improving the partial evaluator for \LangInt{} that was
  2408. introduced in Section~\ref{sec:partial-evaluation}.
  2409. \begin{exercise}\label{ex:pe-Rvar}
  2410. \normalfont
  2411. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2412. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2413. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2414. and variables to the \LangInt{} language, so you will need to add cases for
  2415. them in the \code{pe-exp} function. Once complete, add the partial
  2416. evaluation pass to the front of your compiler and make sure that your
  2417. compiler still passes all of the tests.
  2418. \end{exercise}
  2419. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2420. \begin{exercise}
  2421. \normalfont
  2422. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2423. \code{pe-add} auxiliary functions with functions that know more about
  2424. arithmetic. For example, your partial evaluator should translate
  2425. \[
  2426. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2427. \code{(+ 2 (read))}
  2428. \]
  2429. To accomplish this, the \code{pe-exp} function should produce output
  2430. in the form of the $\itm{residual}$ non-terminal of the following
  2431. grammar. The idea is that when processing an addition expression, we
  2432. can always produce either 1) an integer constant, 2) and addition
  2433. expression with an integer constant on the left-hand side but not the
  2434. right-hand side, or 3) or an addition expression in which neither
  2435. subexpression is a constant.
  2436. \[
  2437. \begin{array}{lcl}
  2438. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2439. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2440. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2441. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2442. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2443. \end{array}
  2444. \]
  2445. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2446. inputs are $\itm{residual}$ expressions and they should return
  2447. $\itm{residual}$ expressions. Once the improvements are complete,
  2448. make sure that your compiler still passes all of the tests. After
  2449. all, fast code is useless if it produces incorrect results!
  2450. \end{exercise}
  2451. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2452. \chapter{Register Allocation}
  2453. \label{ch:register-allocation-Rvar}
  2454. \index{register allocation}
  2455. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2456. stack. In this Chapter we learn how to improve the performance of the
  2457. generated code by placing some variables into registers. The CPU can
  2458. access a register in a single cycle, whereas accessing the stack can
  2459. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2460. serves as a running example. The source program is on the left and the
  2461. output of instruction selection is on the right. The program is almost
  2462. in the x86 assembly language but it still uses variables.
  2463. \begin{figure}
  2464. \begin{minipage}{0.45\textwidth}
  2465. Example \LangVar{} program:
  2466. % var_test_28.rkt
  2467. \begin{lstlisting}
  2468. (let ([v 1])
  2469. (let ([w 42])
  2470. (let ([x (+ v 7)])
  2471. (let ([y x])
  2472. (let ([z (+ x w)])
  2473. (+ z (- y)))))))
  2474. \end{lstlisting}
  2475. \end{minipage}
  2476. \begin{minipage}{0.45\textwidth}
  2477. After instruction selection:
  2478. \begin{lstlisting}
  2479. locals-types:
  2480. x : Integer, y : Integer,
  2481. z : Integer, t : Integer,
  2482. v : Integer, w : Integer
  2483. start:
  2484. movq $1, v
  2485. movq $42, w
  2486. movq v, x
  2487. addq $7, x
  2488. movq x, y
  2489. movq x, z
  2490. addq w, z
  2491. movq y, t
  2492. negq t
  2493. movq z, %rax
  2494. addq t, %rax
  2495. jmp conclusion
  2496. \end{lstlisting}
  2497. \end{minipage}
  2498. \caption{A running example for register allocation.}
  2499. \label{fig:reg-eg}
  2500. \end{figure}
  2501. The goal of register allocation is to fit as many variables into
  2502. registers as possible. Some programs have more variables than
  2503. registers so we cannot always map each variable to a different
  2504. register. Fortunately, it is common for different variables to be
  2505. needed during different periods of time during program execution, and
  2506. in such cases several variables can be mapped to the same register.
  2507. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2508. After the variable \code{x} is moved to \code{z} it is no longer
  2509. needed. Variable \code{z}, on the other hand, is used only after this
  2510. point, so \code{x} and \code{z} could share the same register. The
  2511. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2512. where a variable is needed. Once we have that information, we compute
  2513. which variables are needed at the same time, i.e., which ones
  2514. \emph{interfere} with each other, and represent this relation as an
  2515. undirected graph whose vertices are variables and edges indicate when
  2516. two variables interfere (Section~\ref{sec:build-interference}). We
  2517. then model register allocation as a graph coloring problem
  2518. (Section~\ref{sec:graph-coloring}).
  2519. If we run out of registers despite these efforts, we place the
  2520. remaining variables on the stack, similar to what we did in
  2521. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2522. for assigning a variable to a stack location. The decision to spill a
  2523. variable is handled as part of the graph coloring process
  2524. (Section~\ref{sec:graph-coloring}).
  2525. We make the simplifying assumption that each variable is assigned to
  2526. one location (a register or stack address). A more sophisticated
  2527. approach is to assign a variable to one or more locations in different
  2528. regions of the program. For example, if a variable is used many times
  2529. in short sequence and then only used again after many other
  2530. instructions, it could be more efficient to assign the variable to a
  2531. register during the initial sequence and then move it to the stack for
  2532. the rest of its lifetime. We refer the interested reader to
  2533. \citet{Cooper:2011aa} for more information about that approach.
  2534. % discuss prioritizing variables based on how much they are used.
  2535. \section{Registers and Calling Conventions}
  2536. \label{sec:calling-conventions}
  2537. \index{calling conventions}
  2538. As we perform register allocation, we need to be aware of the
  2539. \emph{calling conventions} \index{calling conventions} that govern how
  2540. functions calls are performed in x86.
  2541. %
  2542. Even though \LangVar{} does not include programmer-defined functions,
  2543. our generated code includes a \code{main} function that is called by
  2544. the operating system and our generated code contains calls to the
  2545. \code{read\_int} function.
  2546. Function calls require coordination between two pieces of code that
  2547. may be written by different programmers or generated by different
  2548. compilers. Here we follow the System V calling conventions that are
  2549. used by the GNU C compiler on Linux and
  2550. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2551. %
  2552. The calling conventions include rules about how functions share the
  2553. use of registers. In particular, the caller is responsible for freeing
  2554. up some registers prior to the function call for use by the callee.
  2555. These are called the \emph{caller-saved registers}
  2556. \index{caller-saved registers}
  2557. and they are
  2558. \begin{lstlisting}
  2559. rax rcx rdx rsi rdi r8 r9 r10 r11
  2560. \end{lstlisting}
  2561. On the other hand, the callee is responsible for preserving the values
  2562. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2563. which are
  2564. \begin{lstlisting}
  2565. rsp rbp rbx r12 r13 r14 r15
  2566. \end{lstlisting}
  2567. We can think about this caller/callee convention from two points of
  2568. view, the caller view and the callee view:
  2569. \begin{itemize}
  2570. \item The caller should assume that all the caller-saved registers get
  2571. overwritten with arbitrary values by the callee. On the other hand,
  2572. the caller can safely assume that all the callee-saved registers
  2573. contain the same values after the call that they did before the
  2574. call.
  2575. \item The callee can freely use any of the caller-saved registers.
  2576. However, if the callee wants to use a callee-saved register, the
  2577. callee must arrange to put the original value back in the register
  2578. prior to returning to the caller. This can be accomplished by saving
  2579. the value to the stack in the prelude of the function and restoring
  2580. the value in the conclusion of the function.
  2581. \end{itemize}
  2582. In x86, registers are also used for passing arguments to a function
  2583. and for the return value. In particular, the first six arguments to a
  2584. function are passed in the following six registers, in this order.
  2585. \begin{lstlisting}
  2586. rdi rsi rdx rcx r8 r9
  2587. \end{lstlisting}
  2588. If there are more than six arguments, then the convention is to use
  2589. space on the frame of the caller for the rest of the
  2590. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2591. need more than six arguments. For now, the only function we care about
  2592. is \code{read\_int} and it takes zero arguments.
  2593. %
  2594. The register \code{rax} is used for the return value of a function.
  2595. The next question is how these calling conventions impact register
  2596. allocation. Consider the \LangVar{} program in
  2597. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2598. example from the caller point of view and then from the callee point
  2599. of view.
  2600. The program makes two calls to the \code{read} function. Also, the
  2601. variable \code{x} is in use during the second call to \code{read}, so
  2602. we need to make sure that the value in \code{x} does not get
  2603. accidentally wiped out by the call to \code{read}. One obvious
  2604. approach is to save all the values in caller-saved registers to the
  2605. stack prior to each function call, and restore them after each
  2606. call. That way, if the register allocator chooses to assign \code{x}
  2607. to a caller-saved register, its value will be preserved across the
  2608. call to \code{read}. However, saving and restoring to the stack is
  2609. relatively slow. If \code{x} is not used many times, it may be better
  2610. to assign \code{x} to a stack location in the first place. Or better
  2611. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2612. register, then it won't need to be saved and restored during function
  2613. calls.
  2614. The approach that we recommend for variables that are in use during a
  2615. function call is to either assign them to callee-saved registers or to
  2616. spill them to the stack. On the other hand, for variables that are not
  2617. in use during a function call, we try the following alternatives in
  2618. order 1) look for an available caller-saved register (to leave room
  2619. for other variables in the callee-saved register), 2) look for a
  2620. callee-saved register, and 3) spill the variable to the stack.
  2621. It is straightforward to implement this approach in a graph coloring
  2622. register allocator. First, we know which variables are in use during
  2623. every function call because we compute that information for every
  2624. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2625. build the interference graph (Section~\ref{sec:build-interference}),
  2626. we can place an edge between each of these variables and the
  2627. caller-saved registers in the interference graph. This will prevent
  2628. the graph coloring algorithm from assigning those variables to
  2629. caller-saved registers.
  2630. Returning to the example in
  2631. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2632. generated x86 code on the right-hand side, focusing on the
  2633. \code{start} block. Notice that variable \code{x} is assigned to
  2634. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2635. place during the second call to \code{read\_int}. Next, notice that
  2636. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2637. because there are no function calls in the remainder of the block.
  2638. Next we analyze the example from the callee point of view, focusing on
  2639. the prelude and conclusion of the \code{main} function. As usual the
  2640. prelude begins with saving the \code{rbp} register to the stack and
  2641. setting the \code{rbp} to the current stack pointer. We now know why
  2642. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2643. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2644. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2645. (\code{x}). The other callee-saved registers are not saved in the
  2646. prelude because they are not used. The prelude subtracts 8 bytes from
  2647. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2648. \code{start} block. Shifting attention to the \code{conclusion}, we
  2649. see that \code{rbx} is restored from the stack with a \code{popq}
  2650. instruction. \index{prelude}\index{conclusion}
  2651. \begin{figure}[tp]
  2652. \begin{minipage}{0.45\textwidth}
  2653. Example \LangVar{} program:
  2654. %var_test_14.rkt
  2655. \begin{lstlisting}
  2656. (let ([x (read)])
  2657. (let ([y (read)])
  2658. (+ (+ x y) 42)))
  2659. \end{lstlisting}
  2660. \end{minipage}
  2661. \begin{minipage}{0.45\textwidth}
  2662. Generated x86 assembly:
  2663. \begin{lstlisting}
  2664. start:
  2665. callq read_int
  2666. movq %rax, %rbx
  2667. callq read_int
  2668. movq %rax, %rcx
  2669. addq %rcx, %rbx
  2670. movq %rbx, %rax
  2671. addq $42, %rax
  2672. jmp _conclusion
  2673. .globl main
  2674. main:
  2675. pushq %rbp
  2676. movq %rsp, %rbp
  2677. pushq %rbx
  2678. subq $8, %rsp
  2679. jmp start
  2680. conclusion:
  2681. addq $8, %rsp
  2682. popq %rbx
  2683. popq %rbp
  2684. retq
  2685. \end{lstlisting}
  2686. \end{minipage}
  2687. \caption{An example with function calls.}
  2688. \label{fig:example-calling-conventions}
  2689. \end{figure}
  2690. \clearpage
  2691. \section{Liveness Analysis}
  2692. \label{sec:liveness-analysis-Rvar}
  2693. \index{liveness analysis}
  2694. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2695. is, it discovers which variables are in-use in different regions of a
  2696. program.
  2697. %
  2698. A variable or register is \emph{live} at a program point if its
  2699. current value is used at some later point in the program. We
  2700. refer to variables and registers collectively as \emph{locations}.
  2701. %
  2702. Consider the following code fragment in which there are two writes to
  2703. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2704. \begin{center}
  2705. \begin{minipage}{0.96\textwidth}
  2706. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2707. movq $5, a
  2708. movq $30, b
  2709. movq a, c
  2710. movq $10, b
  2711. addq b, c
  2712. \end{lstlisting}
  2713. \end{minipage}
  2714. \end{center}
  2715. The answer is no because \code{a} is live from line 1 to 3 and
  2716. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2717. line 2 is never used because it is overwritten (line 4) before the
  2718. next read (line 5).
  2719. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2720. \small
  2721. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2722. A \emph{set} is an unordered collection of elements without duplicates.
  2723. \index{set}
  2724. \begin{description}
  2725. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2726. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2727. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2728. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2729. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2730. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2731. \end{description}
  2732. \end{tcolorbox}
  2733. \end{wrapfigure}
  2734. The live locations can be computed by traversing the instruction
  2735. sequence back to front (i.e., backwards in execution order). Let
  2736. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2737. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2738. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2739. locations before instruction $I_k$. The live locations after an
  2740. instruction are always the same as the live locations before the next
  2741. instruction. \index{live-after} \index{live-before}
  2742. \begin{equation} \label{eq:live-after-before-next}
  2743. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2744. \end{equation}
  2745. To start things off, there are no live locations after the last
  2746. instruction, so
  2747. \begin{equation}\label{eq:live-last-empty}
  2748. L_{\mathsf{after}}(n) = \emptyset
  2749. \end{equation}
  2750. We then apply the following rule repeatedly, traversing the
  2751. instruction sequence back to front.
  2752. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2753. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2754. \end{equation}
  2755. where $W(k)$ are the locations written to by instruction $I_k$ and
  2756. $R(k)$ are the locations read by instruction $I_k$.
  2757. There is a special case for \code{jmp} instructions. The locations
  2758. that are live before a \code{jmp} should be the locations in
  2759. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2760. maintaining an alist named \code{label->live} that maps each label to
  2761. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2762. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2763. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2764. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2765. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2766. Let us walk through the above example, applying these formulas
  2767. starting with the instruction on line 5. We collect the answers in
  2768. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2769. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2770. instruction (formula~\ref{eq:live-last-empty}). The
  2771. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2772. because it reads from variables \code{b} and \code{c}
  2773. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2774. \[
  2775. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2776. \]
  2777. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2778. the live-before set from line 5 to be the live-after set for this
  2779. instruction (formula~\ref{eq:live-after-before-next}).
  2780. \[
  2781. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2782. \]
  2783. This move instruction writes to \code{b} and does not read from any
  2784. variables, so we have the following live-before set
  2785. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2786. \[
  2787. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2788. \]
  2789. The live-before for instruction \code{movq a, c}
  2790. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2791. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2792. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2793. variable that is not live and does not read from a variable.
  2794. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2795. because it writes to variable \code{a}.
  2796. \begin{figure}[tbp]
  2797. \begin{minipage}{0.45\textwidth}
  2798. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2799. movq $5, a
  2800. movq $30, b
  2801. movq a, c
  2802. movq $10, b
  2803. addq b, c
  2804. \end{lstlisting}
  2805. \end{minipage}
  2806. \vrule\hspace{10pt}
  2807. \begin{minipage}{0.45\textwidth}
  2808. \begin{align*}
  2809. L_{\mathsf{before}}(1)= \emptyset,
  2810. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2811. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2812. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2813. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2814. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2815. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2816. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2817. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2818. L_{\mathsf{after}}(5)= \emptyset
  2819. \end{align*}
  2820. \end{minipage}
  2821. \caption{Example output of liveness analysis on a short example.}
  2822. \label{fig:liveness-example-0}
  2823. \end{figure}
  2824. \begin{exercise}\normalfont
  2825. Perform liveness analysis on the running example in
  2826. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2827. sets for each instruction. Compare your answers to the solution
  2828. shown in Figure~\ref{fig:live-eg}.
  2829. \end{exercise}
  2830. \begin{figure}[tp]
  2831. \hspace{20pt}
  2832. \begin{minipage}{0.45\textwidth}
  2833. \begin{lstlisting}
  2834. |$\{\ttm{rsp}\}$|
  2835. movq $1, v
  2836. |$\{\ttm{v},\ttm{rsp}\}$|
  2837. movq $42, w
  2838. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2839. movq v, x
  2840. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2841. addq $7, x
  2842. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2843. movq x, y
  2844. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2845. movq x, z
  2846. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2847. addq w, z
  2848. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2849. movq y, t
  2850. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2851. negq t
  2852. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2853. movq z, %rax
  2854. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2855. addq t, %rax
  2856. |$\{\ttm{rax},\ttm{rsp}\}$|
  2857. jmp conclusion
  2858. \end{lstlisting}
  2859. \end{minipage}
  2860. \caption{The running example annotated with live-after sets.}
  2861. \label{fig:live-eg}
  2862. \end{figure}
  2863. \begin{exercise}\normalfont
  2864. Implement the \code{uncover-live} pass. Store the sequence of
  2865. live-after sets in the $\itm{info}$ field of the \code{Block}
  2866. structure.
  2867. %
  2868. We recommend creating an auxiliary function that takes a list of
  2869. instructions and an initial live-after set (typically empty) and
  2870. returns the list of live-after sets.
  2871. %
  2872. We also recommend creating auxiliary functions to 1) compute the set
  2873. of locations that appear in an \Arg{}, 2) compute the locations read
  2874. by an instruction (the $R$ function), and 3) the locations written by
  2875. an instruction (the $W$ function). The \code{callq} instruction should
  2876. include all of the caller-saved registers in its write-set $W$ because
  2877. the calling convention says that those registers may be written to
  2878. during the function call. Likewise, the \code{callq} instruction
  2879. should include the appropriate argument-passing registers in its
  2880. read-set $R$, depending on the arity of the function being
  2881. called. (This is why the abstract syntax for \code{callq} includes the
  2882. arity.)
  2883. \end{exercise}
  2884. \clearpage
  2885. \section{Build the Interference Graph}
  2886. \label{sec:build-interference}
  2887. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  2888. \small
  2889. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2890. A \emph{graph} is a collection of vertices and edges where each
  2891. edge connects two vertices. A graph is \emph{directed} if each
  2892. edge points from a source to a target. Otherwise the graph is
  2893. \emph{undirected}.
  2894. \index{graph}\index{directed graph}\index{undirected graph}
  2895. \begin{description}
  2896. %% We currently don't use directed graphs. We instead use
  2897. %% directed multi-graphs. -Jeremy
  2898. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2899. %% directed graph from a list of edges. Each edge is a list
  2900. %% containing the source and target vertex.
  2901. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2902. undirected graph from a list of edges. Each edge is represented by
  2903. a list containing two vertices.
  2904. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2905. inserts a vertex into the graph.
  2906. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2907. inserts an edge between the two vertices into the graph.
  2908. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2909. returns a sequence of all the neighbors of the given vertex.
  2910. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2911. returns a sequence of all the vertices in the graph.
  2912. \end{description}
  2913. \end{tcolorbox}
  2914. \end{wrapfigure}
  2915. Based on the liveness analysis, we know where each location is live.
  2916. However, during register allocation, we need to answer questions of
  2917. the specific form: are locations $u$ and $v$ live at the same time?
  2918. (And therefore cannot be assigned to the same register.) To make this
  2919. question more efficient to answer, we create an explicit data
  2920. structure, an \emph{interference graph}\index{interference graph}. An
  2921. interference graph is an undirected graph that has an edge between two
  2922. locations if they are live at the same time, that is, if they
  2923. interfere with each other.
  2924. An obvious way to compute the interference graph is to look at the set
  2925. of live locations between each instruction and the next and add an edge to the graph
  2926. for every pair of variables in the same set. This approach is less
  2927. than ideal for two reasons. First, it can be expensive because it
  2928. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2929. locations. Second, in the special case where two locations hold the
  2930. same value (because one was assigned to the other), they can be live
  2931. at the same time without interfering with each other.
  2932. A better way to compute the interference graph is to focus on
  2933. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2934. must not overwrite something in a live location. So for each
  2935. instruction, we create an edge between the locations being written to
  2936. and the live locations. (Except that one should not create self
  2937. edges.) Note that for the \key{callq} instruction, we consider all of
  2938. the caller-saved registers as being written to, so an edge is added
  2939. between every live variable and every caller-saved register. For
  2940. \key{movq}, we deal with the above-mentioned special case by not
  2941. adding an edge between a live variable $v$ and the destination if $v$
  2942. matches the source. So we have the following two rules.
  2943. \begin{enumerate}
  2944. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2945. $d$, then add the edge $(d,v)$ for every $v \in
  2946. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2947. \item For any other instruction $I_k$, for every $d \in W(k)$
  2948. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2949. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2950. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2951. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2952. %% \item If instruction $I_k$ is of the form \key{callq}
  2953. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2954. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2955. \end{enumerate}
  2956. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2957. the above rules to each instruction. We highlight a few of the
  2958. instructions. The first instruction is \lstinline{movq $1, v} and the
  2959. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2960. interferes with \code{rsp}.
  2961. %
  2962. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2963. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2964. interferes with \ttm{w} and \ttm{rsp}.
  2965. %
  2966. The next instruction is \lstinline{movq x, y} and the live-after set
  2967. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2968. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2969. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2970. same value. Figure~\ref{fig:interference-results} lists the
  2971. interference results for all of the instructions and the resulting
  2972. interference graph is shown in Figure~\ref{fig:interfere}.
  2973. \begin{figure}[tbp]
  2974. \begin{quote}
  2975. \begin{tabular}{ll}
  2976. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2977. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2978. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2979. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2980. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2981. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2982. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2983. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2984. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2985. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2986. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2987. \lstinline!jmp conclusion!& no interference.
  2988. \end{tabular}
  2989. \end{quote}
  2990. \caption{Interference results for the running example.}
  2991. \label{fig:interference-results}
  2992. \end{figure}
  2993. \begin{figure}[tbp]
  2994. \large
  2995. \[
  2996. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2997. \node (rax) at (0,0) {$\ttm{rax}$};
  2998. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2999. \node (t1) at (0,2) {$\ttm{t}$};
  3000. \node (z) at (3,2) {$\ttm{z}$};
  3001. \node (x) at (6,2) {$\ttm{x}$};
  3002. \node (y) at (3,0) {$\ttm{y}$};
  3003. \node (w) at (6,0) {$\ttm{w}$};
  3004. \node (v) at (9,0) {$\ttm{v}$};
  3005. \draw (t1) to (rax);
  3006. \draw (t1) to (z);
  3007. \draw (z) to (y);
  3008. \draw (z) to (w);
  3009. \draw (x) to (w);
  3010. \draw (y) to (w);
  3011. \draw (v) to (w);
  3012. \draw (v) to (rsp);
  3013. \draw (w) to (rsp);
  3014. \draw (x) to (rsp);
  3015. \draw (y) to (rsp);
  3016. \path[-.,bend left=15] (z) edge node {} (rsp);
  3017. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3018. \draw (rax) to (rsp);
  3019. \end{tikzpicture}
  3020. \]
  3021. \caption{The interference graph of the example program.}
  3022. \label{fig:interfere}
  3023. \end{figure}
  3024. %% Our next concern is to choose a data structure for representing the
  3025. %% interference graph. There are many choices for how to represent a
  3026. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3027. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3028. %% data structure is to study the algorithm that uses the data structure,
  3029. %% determine what operations need to be performed, and then choose the
  3030. %% data structure that provide the most efficient implementations of
  3031. %% those operations. Often times the choice of data structure can have an
  3032. %% effect on the time complexity of the algorithm, as it does here. If
  3033. %% you skim the next section, you will see that the register allocation
  3034. %% algorithm needs to ask the graph for all of its vertices and, given a
  3035. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3036. %% correct choice of graph representation is that of an adjacency
  3037. %% list. There are helper functions in \code{utilities.rkt} for
  3038. %% representing graphs using the adjacency list representation:
  3039. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3040. %% (Appendix~\ref{appendix:utilities}).
  3041. %% %
  3042. %% \margincomment{\footnotesize To do: change to use the
  3043. %% Racket graph library. \\ --Jeremy}
  3044. %% %
  3045. %% In particular, those functions use a hash table to map each vertex to
  3046. %% the set of adjacent vertices, and the sets are represented using
  3047. %% Racket's \key{set}, which is also a hash table.
  3048. \begin{exercise}\normalfont
  3049. Implement the compiler pass named \code{build-interference} according
  3050. to the algorithm suggested above. We recommend using the \code{graph}
  3051. package to create and inspect the interference graph. The output
  3052. graph of this pass should be stored in the $\itm{info}$ field of the
  3053. program, under the key \code{conflicts}.
  3054. \end{exercise}
  3055. \section{Graph Coloring via Sudoku}
  3056. \label{sec:graph-coloring}
  3057. \index{graph coloring}
  3058. \index{Sudoku}
  3059. \index{color}
  3060. We come to the main event, mapping variables to registers and stack
  3061. locations. Variables that interfere with each other must be mapped to
  3062. different locations. In terms of the interference graph, this means
  3063. that adjacent vertices must be mapped to different locations. If we
  3064. think of locations as colors, the register allocation problem becomes
  3065. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3066. The reader may be more familiar with the graph coloring problem than he
  3067. or she realizes; the popular game of Sudoku is an instance of the
  3068. graph coloring problem. The following describes how to build a graph
  3069. out of an initial Sudoku board.
  3070. \begin{itemize}
  3071. \item There is one vertex in the graph for each Sudoku square.
  3072. \item There is an edge between two vertices if the corresponding squares
  3073. are in the same row, in the same column, or if the squares are in
  3074. the same $3\times 3$ region.
  3075. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3076. \item Based on the initial assignment of numbers to squares in the
  3077. Sudoku board, assign the corresponding colors to the corresponding
  3078. vertices in the graph.
  3079. \end{itemize}
  3080. If you can color the remaining vertices in the graph with the nine
  3081. colors, then you have also solved the corresponding game of Sudoku.
  3082. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3083. the corresponding graph with colored vertices. We map the Sudoku
  3084. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3085. sampling of the vertices (the colored ones) because showing edges for
  3086. all of the vertices would make the graph unreadable.
  3087. \begin{figure}[tbp]
  3088. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3089. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3090. \caption{A Sudoku game board and the corresponding colored graph.}
  3091. \label{fig:sudoku-graph}
  3092. \end{figure}
  3093. It turns out that some techniques for playing Sudoku correspond to
  3094. heuristics used in graph coloring algorithms. For example, one of the
  3095. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3096. a process of elimination to determine what numbers are no longer
  3097. available for a square and write down those numbers in the square
  3098. (writing very small). For example, if the number $1$ is assigned to a
  3099. square, then write the pencil mark $1$ in all the squares in the same
  3100. row, column, and region.
  3101. %
  3102. The Pencil Marks technique corresponds to the notion of
  3103. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3104. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3105. are no longer available. In graph terminology, we have the following
  3106. definition:
  3107. \begin{equation*}
  3108. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3109. \text{ and } \mathrm{color}(v) = c \}
  3110. \end{equation*}
  3111. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3112. edge with $u$.
  3113. Using the Pencil Marks technique leads to a simple strategy for
  3114. filling in numbers: if there is a square with only one possible number
  3115. left, then choose that number! But what if there are no squares with
  3116. only one possibility left? One brute-force approach is to try them
  3117. all: choose the first one and if it ultimately leads to a solution,
  3118. great. If not, backtrack and choose the next possibility. One good
  3119. thing about Pencil Marks is that it reduces the degree of branching in
  3120. the search tree. Nevertheless, backtracking can be horribly time
  3121. consuming. One way to reduce the amount of backtracking is to use the
  3122. most-constrained-first heuristic. That is, when choosing a square,
  3123. always choose one with the fewest possibilities left (the vertex with
  3124. the highest saturation). The idea is that choosing highly constrained
  3125. squares earlier rather than later is better because later on there may
  3126. not be any possibilities left in the highly saturated squares.
  3127. However, register allocation is easier than Sudoku because the
  3128. register allocator can map variables to stack locations when the
  3129. registers run out. Thus, it makes sense to replace backtracking with
  3130. greedy search: make the best choice at the time and keep going. We
  3131. still wish to minimize the number of colors needed, so we use the
  3132. most-constrained-first heuristic in the greedy search.
  3133. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3134. algorithm for register allocation based on saturation and the
  3135. most-constrained-first heuristic. It is roughly equivalent to the
  3136. DSATUR
  3137. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3138. as in Sudoku, the algorithm represents colors with integers. The
  3139. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3140. for register allocation. The integers $k$ and larger correspond to
  3141. stack locations. The registers that are not used for register
  3142. allocation, such as \code{rax}, are assigned to negative integers. In
  3143. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3144. %% One might wonder why we include registers at all in the liveness
  3145. %% analysis and interference graph. For example, we never allocate a
  3146. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3147. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3148. %% to use register for passing arguments to functions, it will be
  3149. %% necessary for those registers to appear in the interference graph
  3150. %% because those registers will also be assigned to variables, and we
  3151. %% don't want those two uses to encroach on each other. Regarding
  3152. %% registers such as \code{rax} and \code{rsp} that are not used for
  3153. %% variables, we could omit them from the interference graph but that
  3154. %% would require adding special cases to our algorithm, which would
  3155. %% complicate the logic for little gain.
  3156. \begin{figure}[btp]
  3157. \centering
  3158. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3159. Algorithm: DSATUR
  3160. Input: a graph |$G$|
  3161. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3162. |$W \gets \mathrm{vertices}(G)$|
  3163. while |$W \neq \emptyset$| do
  3164. pick a vertex |$u$| from |$W$| with the highest saturation,
  3165. breaking ties randomly
  3166. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3167. |$\mathrm{color}[u] \gets c$|
  3168. |$W \gets W - \{u\}$|
  3169. \end{lstlisting}
  3170. \caption{The saturation-based greedy graph coloring algorithm.}
  3171. \label{fig:satur-algo}
  3172. \end{figure}
  3173. With the DSATUR algorithm in hand, let us return to the running
  3174. example and consider how to color the interference graph in
  3175. Figure~\ref{fig:interfere}.
  3176. %
  3177. We start by assigning the register nodes to their own color. For
  3178. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3179. assigned $-2$. The variables are not yet colored, so they are
  3180. annotated with a dash. We then update the saturation for vertices that
  3181. are adjacent to a register, obtaining the following annotated
  3182. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3183. it interferes with both \code{rax} and \code{rsp}.
  3184. \[
  3185. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3186. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3187. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3188. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3189. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3190. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3191. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3192. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3193. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3194. \draw (t1) to (rax);
  3195. \draw (t1) to (z);
  3196. \draw (z) to (y);
  3197. \draw (z) to (w);
  3198. \draw (x) to (w);
  3199. \draw (y) to (w);
  3200. \draw (v) to (w);
  3201. \draw (v) to (rsp);
  3202. \draw (w) to (rsp);
  3203. \draw (x) to (rsp);
  3204. \draw (y) to (rsp);
  3205. \path[-.,bend left=15] (z) edge node {} (rsp);
  3206. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3207. \draw (rax) to (rsp);
  3208. \end{tikzpicture}
  3209. \]
  3210. The algorithm says to select a maximally saturated vertex. So we pick
  3211. $\ttm{t}$ and color it with the first available integer, which is
  3212. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3213. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3214. \[
  3215. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3216. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3217. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3218. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3219. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3220. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3221. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3222. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3223. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3224. \draw (t1) to (rax);
  3225. \draw (t1) to (z);
  3226. \draw (z) to (y);
  3227. \draw (z) to (w);
  3228. \draw (x) to (w);
  3229. \draw (y) to (w);
  3230. \draw (v) to (w);
  3231. \draw (v) to (rsp);
  3232. \draw (w) to (rsp);
  3233. \draw (x) to (rsp);
  3234. \draw (y) to (rsp);
  3235. \path[-.,bend left=15] (z) edge node {} (rsp);
  3236. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3237. \draw (rax) to (rsp);
  3238. \end{tikzpicture}
  3239. \]
  3240. We repeat the process, selecting the next maximally saturated vertex,
  3241. which is \code{z}, and color it with the first available number, which
  3242. is $1$. We add $1$ to the saturation for the neighboring vertices
  3243. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3244. \[
  3245. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3246. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3247. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3248. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3249. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3250. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3251. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3252. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3253. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3254. \draw (t1) to (rax);
  3255. \draw (t1) to (z);
  3256. \draw (z) to (y);
  3257. \draw (z) to (w);
  3258. \draw (x) to (w);
  3259. \draw (y) to (w);
  3260. \draw (v) to (w);
  3261. \draw (v) to (rsp);
  3262. \draw (w) to (rsp);
  3263. \draw (x) to (rsp);
  3264. \draw (y) to (rsp);
  3265. \path[-.,bend left=15] (z) edge node {} (rsp);
  3266. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3267. \draw (rax) to (rsp);
  3268. \end{tikzpicture}
  3269. \]
  3270. The most saturated vertices are now \code{w} and \code{y}. We color
  3271. \code{w} with the first available color, which is $0$.
  3272. \[
  3273. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3274. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3275. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3276. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3277. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3278. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3279. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3280. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3281. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3282. \draw (t1) to (rax);
  3283. \draw (t1) to (z);
  3284. \draw (z) to (y);
  3285. \draw (z) to (w);
  3286. \draw (x) to (w);
  3287. \draw (y) to (w);
  3288. \draw (v) to (w);
  3289. \draw (v) to (rsp);
  3290. \draw (w) to (rsp);
  3291. \draw (x) to (rsp);
  3292. \draw (y) to (rsp);
  3293. \path[-.,bend left=15] (z) edge node {} (rsp);
  3294. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3295. \draw (rax) to (rsp);
  3296. \end{tikzpicture}
  3297. \]
  3298. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3299. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3300. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3301. and \code{z}, whose colors are $0$ and $1$ respectively.
  3302. \[
  3303. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3304. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3305. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3306. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3307. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3308. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3309. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3310. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3311. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3312. \draw (t1) to (rax);
  3313. \draw (t1) to (z);
  3314. \draw (z) to (y);
  3315. \draw (z) to (w);
  3316. \draw (x) to (w);
  3317. \draw (y) to (w);
  3318. \draw (v) to (w);
  3319. \draw (v) to (rsp);
  3320. \draw (w) to (rsp);
  3321. \draw (x) to (rsp);
  3322. \draw (y) to (rsp);
  3323. \path[-.,bend left=15] (z) edge node {} (rsp);
  3324. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3325. \draw (rax) to (rsp);
  3326. \end{tikzpicture}
  3327. \]
  3328. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3329. \[
  3330. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3331. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3332. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3333. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3334. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3335. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3336. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3337. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3338. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3339. \draw (t1) to (rax);
  3340. \draw (t1) to (z);
  3341. \draw (z) to (y);
  3342. \draw (z) to (w);
  3343. \draw (x) to (w);
  3344. \draw (y) to (w);
  3345. \draw (v) to (w);
  3346. \draw (v) to (rsp);
  3347. \draw (w) to (rsp);
  3348. \draw (x) to (rsp);
  3349. \draw (y) to (rsp);
  3350. \path[-.,bend left=15] (z) edge node {} (rsp);
  3351. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3352. \draw (rax) to (rsp);
  3353. \end{tikzpicture}
  3354. \]
  3355. In the last step of the algorithm, we color \code{x} with $1$.
  3356. \[
  3357. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3358. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3359. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3360. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3361. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3362. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3363. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3364. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3365. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3366. \draw (t1) to (rax);
  3367. \draw (t1) to (z);
  3368. \draw (z) to (y);
  3369. \draw (z) to (w);
  3370. \draw (x) to (w);
  3371. \draw (y) to (w);
  3372. \draw (v) to (w);
  3373. \draw (v) to (rsp);
  3374. \draw (w) to (rsp);
  3375. \draw (x) to (rsp);
  3376. \draw (y) to (rsp);
  3377. \path[-.,bend left=15] (z) edge node {} (rsp);
  3378. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3379. \draw (rax) to (rsp);
  3380. \end{tikzpicture}
  3381. \]
  3382. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3383. \small
  3384. \begin{tcolorbox}[title=Priority Queue]
  3385. A \emph{priority queue} is a collection of items in which the
  3386. removal of items is governed by priority. In a ``min'' queue,
  3387. lower priority items are removed first. An implementation is in
  3388. \code{priority\_queue.rkt} of the support code. \index{priority
  3389. queue} \index{minimum priority queue}
  3390. \begin{description}
  3391. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3392. priority queue that uses the $\itm{cmp}$ predicate to determine
  3393. whether its first argument has lower or equal priority to its
  3394. second argument.
  3395. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3396. items in the queue.
  3397. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3398. the item into the queue and returns a handle for the item in the
  3399. queue.
  3400. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3401. the lowest priority.
  3402. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3403. notifies the queue that the priority has decreased for the item
  3404. associated with the given handle.
  3405. \end{description}
  3406. \end{tcolorbox}
  3407. \end{wrapfigure}
  3408. We recommend creating an auxiliary function named \code{color-graph}
  3409. that takes an interference graph and a list of all the variables in
  3410. the program. This function should return a mapping of variables to
  3411. their colors (represented as natural numbers). By creating this helper
  3412. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3413. when we add support for functions.
  3414. To prioritize the processing of highly saturated nodes inside the
  3415. \code{color-graph} function, we recommend using the priority queue
  3416. data structure (see the side bar on the right). In addition, you will
  3417. need to maintain a mapping from variables to their ``handles'' in the
  3418. priority queue so that you can notify the priority queue when their
  3419. saturation changes.
  3420. With the coloring complete, we finalize the assignment of variables to
  3421. registers and stack locations. We map the first $k$ colors to the $k$
  3422. registers and the rest of the colors to stack locations. Suppose for
  3423. the moment that we have just one register to use for register
  3424. allocation, \key{rcx}. Then we have the following map from colors to
  3425. locations.
  3426. \[
  3427. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3428. \]
  3429. Composing this mapping with the coloring, we arrive at the following
  3430. assignment of variables to locations.
  3431. \begin{gather*}
  3432. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3433. \ttm{w} \mapsto \key{\%rcx}, \,
  3434. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3435. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3436. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3437. \ttm{t} \mapsto \key{\%rcx} \}
  3438. \end{gather*}
  3439. Adapt the code from the \code{assign-homes} pass
  3440. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3441. assigned location. Applying the above assignment to our running
  3442. example, on the left, yields the program on the right.
  3443. % why frame size of 32? -JGS
  3444. \begin{center}
  3445. \begin{minipage}{0.3\textwidth}
  3446. \begin{lstlisting}
  3447. movq $1, v
  3448. movq $42, w
  3449. movq v, x
  3450. addq $7, x
  3451. movq x, y
  3452. movq x, z
  3453. addq w, z
  3454. movq y, t
  3455. negq t
  3456. movq z, %rax
  3457. addq t, %rax
  3458. jmp conclusion
  3459. \end{lstlisting}
  3460. \end{minipage}
  3461. $\Rightarrow\qquad$
  3462. \begin{minipage}{0.45\textwidth}
  3463. \begin{lstlisting}
  3464. movq $1, -8(%rbp)
  3465. movq $42, %rcx
  3466. movq -8(%rbp), -8(%rbp)
  3467. addq $7, -8(%rbp)
  3468. movq -8(%rbp), -16(%rbp)
  3469. movq -8(%rbp), -8(%rbp)
  3470. addq %rcx, -8(%rbp)
  3471. movq -16(%rbp), %rcx
  3472. negq %rcx
  3473. movq -8(%rbp), %rax
  3474. addq %rcx, %rax
  3475. jmp conclusion
  3476. \end{lstlisting}
  3477. \end{minipage}
  3478. \end{center}
  3479. \begin{exercise}\normalfont
  3480. %
  3481. Implement the compiler pass \code{allocate-registers}.
  3482. %
  3483. Create five programs that exercise all of the register allocation
  3484. algorithm, including spilling variables to the stack.
  3485. %
  3486. Replace \code{assign-homes} in the list of \code{passes} in the
  3487. \code{run-tests.rkt} script with the three new passes:
  3488. \code{uncover-live}, \code{build-interference}, and
  3489. \code{allocate-registers}.
  3490. %
  3491. Temporarily remove the \code{print-x86} pass from the list of passes
  3492. and the call to \code{compiler-tests}.
  3493. %
  3494. Run the script to test the register allocator.
  3495. \end{exercise}
  3496. \section{Patch Instructions}
  3497. \label{sec:patch-instructions}
  3498. The remaining step in the compilation to x86 is to ensure that the
  3499. instructions have at most one argument that is a memory access.
  3500. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3501. is problematic. The fix is to first move \code{-8(\%rbp)}
  3502. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3503. %
  3504. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3505. problematic, but they can be fixed by simply deleting them. In
  3506. general, we recommend deleting all the trivial moves whose source and
  3507. destination are the same location.
  3508. %
  3509. The following is the output of \code{patch-instructions} on the
  3510. running example.
  3511. \begin{center}
  3512. \begin{minipage}{0.4\textwidth}
  3513. \begin{lstlisting}
  3514. movq $1, -8(%rbp)
  3515. movq $42, %rcx
  3516. movq -8(%rbp), -8(%rbp)
  3517. addq $7, -8(%rbp)
  3518. movq -8(%rbp), -16(%rbp)
  3519. movq -8(%rbp), -8(%rbp)
  3520. addq %rcx, -8(%rbp)
  3521. movq -16(%rbp), %rcx
  3522. negq %rcx
  3523. movq -8(%rbp), %rax
  3524. addq %rcx, %rax
  3525. jmp conclusion
  3526. \end{lstlisting}
  3527. \end{minipage}
  3528. $\Rightarrow\qquad$
  3529. \begin{minipage}{0.45\textwidth}
  3530. \begin{lstlisting}
  3531. movq $1, -8(%rbp)
  3532. movq $42, %rcx
  3533. addq $7, -8(%rbp)
  3534. movq -8(%rbp), %rax
  3535. movq %rax, -16(%rbp)
  3536. addq %rcx, -8(%rbp)
  3537. movq -16(%rbp), %rcx
  3538. negq %rcx
  3539. movq -8(%rbp), %rax
  3540. addq %rcx, %rax
  3541. jmp conclusion
  3542. \end{lstlisting}
  3543. \end{minipage}
  3544. \end{center}
  3545. \begin{exercise}\normalfont
  3546. %
  3547. Implement the \code{patch-instructions} compiler pass.
  3548. %
  3549. Insert it after \code{allocate-registers} in the list of \code{passes}
  3550. in the \code{run-tests.rkt} script.
  3551. %
  3552. Run the script to test the \code{patch-instructions} pass.
  3553. \end{exercise}
  3554. \section{Print x86}
  3555. \label{sec:print-x86-reg-alloc}
  3556. \index{calling conventions}
  3557. \index{prelude}\index{conclusion}
  3558. Recall that the \code{print-x86} pass generates the prelude and
  3559. conclusion instructions to satisfy the x86 calling conventions
  3560. (Section~\ref{sec:calling-conventions}). With the addition of the
  3561. register allocator, the callee-saved registers used by the register
  3562. allocator must be saved in the prelude and restored in the conclusion.
  3563. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3564. of \code{X86Program} named \code{used-callee} that stores the set of
  3565. callee-saved registers that were assigned to variables. The
  3566. \code{print-x86} pass can then access this information to decide which
  3567. callee-saved registers need to be saved and restored.
  3568. %
  3569. When calculating the size of the frame to adjust the \code{rsp} in the
  3570. prelude, make sure to take into account the space used for saving the
  3571. callee-saved registers. Also, don't forget that the frame needs to be
  3572. a multiple of 16 bytes!
  3573. An overview of all of the passes involved in register allocation is
  3574. shown in Figure~\ref{fig:reg-alloc-passes}.
  3575. \begin{figure}[tbp]
  3576. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3577. \node (Rvar) at (0,2) {\large \LangVar{}};
  3578. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3579. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3580. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3581. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3582. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3583. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3584. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3585. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3586. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3587. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3588. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3589. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3590. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3591. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3592. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3593. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3594. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3595. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3596. \end{tikzpicture}
  3597. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3598. \label{fig:reg-alloc-passes}
  3599. \end{figure}
  3600. \begin{exercise}\normalfont
  3601. Update the \code{print-x86} pass as described in this section.
  3602. %
  3603. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3604. list of passes and the call to \code{compiler-tests}.
  3605. %
  3606. Run the script to test the complete compiler for \LangVar{} that
  3607. performs register allocation.
  3608. \end{exercise}
  3609. \section{Challenge: Move Biasing}
  3610. \label{sec:move-biasing}
  3611. \index{move biasing}
  3612. This section describes an enhancement to the register allocator for
  3613. students looking for an extra challenge or who have a deeper interest
  3614. in register allocation.
  3615. To motivate the need for move biasing we return to the running example
  3616. but this time use all of the general purpose registers. So we have
  3617. the following mapping of color numbers to registers.
  3618. \[
  3619. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3620. \]
  3621. Using the same assignment of variables to color numbers that was
  3622. produced by the register allocator described in the last section, we
  3623. get the following program.
  3624. \begin{center}
  3625. \begin{minipage}{0.3\textwidth}
  3626. \begin{lstlisting}
  3627. movq $1, v
  3628. movq $42, w
  3629. movq v, x
  3630. addq $7, x
  3631. movq x, y
  3632. movq x, z
  3633. addq w, z
  3634. movq y, t
  3635. negq t
  3636. movq z, %rax
  3637. addq t, %rax
  3638. jmp conclusion
  3639. \end{lstlisting}
  3640. \end{minipage}
  3641. $\Rightarrow\qquad$
  3642. \begin{minipage}{0.45\textwidth}
  3643. \begin{lstlisting}
  3644. movq $1, %rdx
  3645. movq $42, %rcx
  3646. movq %rdx, %rdx
  3647. addq $7, %rdx
  3648. movq %rdx, %rsi
  3649. movq %rdx, %rdx
  3650. addq %rcx, %rdx
  3651. movq %rsi, %rcx
  3652. negq %rcx
  3653. movq %rdx, %rax
  3654. addq %rcx, %rax
  3655. jmp conclusion
  3656. \end{lstlisting}
  3657. \end{minipage}
  3658. \end{center}
  3659. In the above output code there are two \key{movq} instructions that
  3660. can be removed because their source and target are the same. However,
  3661. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3662. register, we could instead remove three \key{movq} instructions. We
  3663. can accomplish this by taking into account which variables appear in
  3664. \key{movq} instructions with which other variables.
  3665. We say that two variables $p$ and $q$ are \emph{move
  3666. related}\index{move related} if they participate together in a
  3667. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3668. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3669. for a variable, it should prefer a color that has already been used
  3670. for a move-related variable (assuming that they do not interfere). Of
  3671. course, this preference should not override the preference for
  3672. registers over stack locations. This preference should be used as a
  3673. tie breaker when choosing between registers or when choosing between
  3674. stack locations.
  3675. We recommend representing the move relationships in a graph, similar
  3676. to how we represented interference. The following is the \emph{move
  3677. graph} for our running example.
  3678. \[
  3679. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3680. \node (rax) at (0,0) {$\ttm{rax}$};
  3681. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3682. \node (t) at (0,2) {$\ttm{t}$};
  3683. \node (z) at (3,2) {$\ttm{z}$};
  3684. \node (x) at (6,2) {$\ttm{x}$};
  3685. \node (y) at (3,0) {$\ttm{y}$};
  3686. \node (w) at (6,0) {$\ttm{w}$};
  3687. \node (v) at (9,0) {$\ttm{v}$};
  3688. \draw (v) to (x);
  3689. \draw (x) to (y);
  3690. \draw (x) to (z);
  3691. \draw (y) to (t);
  3692. \end{tikzpicture}
  3693. \]
  3694. Now we replay the graph coloring, pausing to see the coloring of
  3695. \code{y}. Recall the following configuration. The most saturated vertices
  3696. were \code{w} and \code{y}.
  3697. \[
  3698. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3699. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3700. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3701. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3702. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3703. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3704. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3705. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3706. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3707. \draw (t1) to (rax);
  3708. \draw (t1) to (z);
  3709. \draw (z) to (y);
  3710. \draw (z) to (w);
  3711. \draw (x) to (w);
  3712. \draw (y) to (w);
  3713. \draw (v) to (w);
  3714. \draw (v) to (rsp);
  3715. \draw (w) to (rsp);
  3716. \draw (x) to (rsp);
  3717. \draw (y) to (rsp);
  3718. \path[-.,bend left=15] (z) edge node {} (rsp);
  3719. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3720. \draw (rax) to (rsp);
  3721. \end{tikzpicture}
  3722. \]
  3723. %
  3724. Last time we chose to color \code{w} with $0$. But this time we see
  3725. that \code{w} is not move related to any vertex, but \code{y} is move
  3726. related to \code{t}. So we choose to color \code{y} the same color as
  3727. \code{t}, $0$.
  3728. \[
  3729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3730. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3731. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3732. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3733. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3734. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3735. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3736. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3737. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3738. \draw (t1) to (rax);
  3739. \draw (t1) to (z);
  3740. \draw (z) to (y);
  3741. \draw (z) to (w);
  3742. \draw (x) to (w);
  3743. \draw (y) to (w);
  3744. \draw (v) to (w);
  3745. \draw (v) to (rsp);
  3746. \draw (w) to (rsp);
  3747. \draw (x) to (rsp);
  3748. \draw (y) to (rsp);
  3749. \path[-.,bend left=15] (z) edge node {} (rsp);
  3750. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3751. \draw (rax) to (rsp);
  3752. \end{tikzpicture}
  3753. \]
  3754. Now \code{w} is the most saturated, so we color it $2$.
  3755. \[
  3756. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3757. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3758. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3759. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3760. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3761. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3762. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3763. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3764. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3765. \draw (t1) to (rax);
  3766. \draw (t1) to (z);
  3767. \draw (z) to (y);
  3768. \draw (z) to (w);
  3769. \draw (x) to (w);
  3770. \draw (y) to (w);
  3771. \draw (v) to (w);
  3772. \draw (v) to (rsp);
  3773. \draw (w) to (rsp);
  3774. \draw (x) to (rsp);
  3775. \draw (y) to (rsp);
  3776. \path[-.,bend left=15] (z) edge node {} (rsp);
  3777. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3778. \draw (rax) to (rsp);
  3779. \end{tikzpicture}
  3780. \]
  3781. At this point, vertices \code{x} and \code{v} are most saturated, but
  3782. \code{x} is move related to \code{y} and \code{z}, so we color
  3783. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3784. \[
  3785. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3786. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3787. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3788. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3789. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3790. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3791. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3792. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3793. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3794. \draw (t1) to (rax);
  3795. \draw (t) to (z);
  3796. \draw (z) to (y);
  3797. \draw (z) to (w);
  3798. \draw (x) to (w);
  3799. \draw (y) to (w);
  3800. \draw (v) to (w);
  3801. \draw (v) to (rsp);
  3802. \draw (w) to (rsp);
  3803. \draw (x) to (rsp);
  3804. \draw (y) to (rsp);
  3805. \path[-.,bend left=15] (z) edge node {} (rsp);
  3806. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3807. \draw (rax) to (rsp);
  3808. \end{tikzpicture}
  3809. \]
  3810. So we have the following assignment of variables to registers.
  3811. \begin{gather*}
  3812. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3813. \ttm{w} \mapsto \key{\%rsi}, \,
  3814. \ttm{x} \mapsto \key{\%rcx}, \,
  3815. \ttm{y} \mapsto \key{\%rcx}, \,
  3816. \ttm{z} \mapsto \key{\%rdx}, \,
  3817. \ttm{t} \mapsto \key{\%rcx} \}
  3818. \end{gather*}
  3819. We apply this register assignment to the running example, on the left,
  3820. to obtain the code in the middle. The \code{patch-instructions} then
  3821. removes the three trivial moves to obtain the code on the right.
  3822. \begin{minipage}{0.25\textwidth}
  3823. \begin{lstlisting}
  3824. movq $1, v
  3825. movq $42, w
  3826. movq v, x
  3827. addq $7, x
  3828. movq x, y
  3829. movq x, z
  3830. addq w, z
  3831. movq y, t
  3832. negq t
  3833. movq z, %rax
  3834. addq t, %rax
  3835. jmp conclusion
  3836. \end{lstlisting}
  3837. \end{minipage}
  3838. $\Rightarrow\qquad$
  3839. \begin{minipage}{0.25\textwidth}
  3840. \begin{lstlisting}
  3841. movq $1, %rcx
  3842. movq $42, %rsi
  3843. movq %rcx, %rcx
  3844. addq $7, %rcx
  3845. movq %rcx, %rcx
  3846. movq %rcx, %rdx
  3847. addq %rsi, %rdx
  3848. movq %rcx, %rcx
  3849. negq %rcx
  3850. movq %rdx, %rax
  3851. addq %rcx, %rax
  3852. jmp conclusion
  3853. \end{lstlisting}
  3854. \end{minipage}
  3855. $\Rightarrow\qquad$
  3856. \begin{minipage}{0.25\textwidth}
  3857. \begin{lstlisting}
  3858. movq $1, %rcx
  3859. movq $42, %rsi
  3860. addq $7, %rcx
  3861. movq %rcx, %rdx
  3862. addq %rsi, %rdx
  3863. negq %rcx
  3864. movq %rdx, %rax
  3865. addq %rcx, %rax
  3866. jmp conclusion
  3867. \end{lstlisting}
  3868. \end{minipage}
  3869. \begin{exercise}\normalfont
  3870. Change your implementation of \code{allocate-registers} to take move
  3871. biasing into account. Create two new tests that include at least one
  3872. opportunity for move biasing and visually inspect the output x86
  3873. programs to make sure that your move biasing is working properly. Make
  3874. sure that your compiler still passes all of the tests.
  3875. \end{exercise}
  3876. \margincomment{\footnotesize To do: another neat challenge would be to do
  3877. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3878. %% \subsection{Output of the Running Example}
  3879. %% \label{sec:reg-alloc-output}
  3880. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3881. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3882. and move biasing. To demonstrate both the use of registers and the
  3883. stack, we have limited the register allocator to use just two
  3884. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3885. of the \code{main} function, we push \code{rbx} onto the stack because
  3886. it is a callee-saved register and it was assigned to variable by the
  3887. register allocator. We subtract \code{8} from the \code{rsp} at the
  3888. end of the prelude to reserve space for the one spilled variable.
  3889. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3890. Moving on the the \code{start} block, we see how the registers were
  3891. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3892. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3893. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3894. that the prelude saved the callee-save register \code{rbx} onto the
  3895. stack. The spilled variables must be placed lower on the stack than
  3896. the saved callee-save registers, so in this case \code{w} is placed at
  3897. \code{-16(\%rbp)}.
  3898. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3899. done in the prelude. We move the stack pointer up by \code{8} bytes
  3900. (the room for spilled variables), then we pop the old values of
  3901. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3902. \code{retq} to return control to the operating system.
  3903. \begin{figure}[tbp]
  3904. % var_test_28.rkt
  3905. % (use-minimal-set-of-registers! #t)
  3906. % and only rbx rcx
  3907. % tmp 0 rbx
  3908. % z 1 rcx
  3909. % y 0 rbx
  3910. % w 2 16(%rbp)
  3911. % v 0 rbx
  3912. % x 0 rbx
  3913. \begin{lstlisting}
  3914. start:
  3915. movq $1, %rbx
  3916. movq $42, -16(%rbp)
  3917. addq $7, %rbx
  3918. movq %rbx, %rcx
  3919. addq -16(%rbp), %rcx
  3920. negq %rbx
  3921. movq %rcx, %rax
  3922. addq %rbx, %rax
  3923. jmp conclusion
  3924. .globl main
  3925. main:
  3926. pushq %rbp
  3927. movq %rsp, %rbp
  3928. pushq %rbx
  3929. subq $8, %rsp
  3930. jmp start
  3931. conclusion:
  3932. addq $8, %rsp
  3933. popq %rbx
  3934. popq %rbp
  3935. retq
  3936. \end{lstlisting}
  3937. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3938. \label{fig:running-example-x86}
  3939. \end{figure}
  3940. % challenge: prioritize variables based on execution frequencies
  3941. % and the number of uses of a variable
  3942. % challenge: enhance the coloring algorithm using Chaitin's
  3943. % approach of prioritizing high-degree variables
  3944. % by removing low-degree variables (coloring them later)
  3945. % from the interference graph
  3946. \section{Further Reading}
  3947. \label{sec:register-allocation-further-reading}
  3948. Early register allocation algorithms were developed for Fortran
  3949. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  3950. of graph coloring began in the late 1970s and early 1980s with the
  3951. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  3952. algorithm is based on the following observation of
  3953. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  3954. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  3955. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  3956. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  3957. different colors, but since there are less than $k$ of them, there
  3958. will be one or more colors left over to use for coloring $v$ in $G$.
  3959. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  3960. less than $k$ from the graph and recursively colors the rest of the
  3961. graph. Upon returning from the recursion, it colors $v$ with one of
  3962. the available colors and returns. \citet{Chaitin:1982vn} augments
  3963. this algorithm to handle spilling as follows. If there are no vertices
  3964. of degree lower than $k$ then pick a vertex at random, spill it,
  3965. remove it from the graph, and proceed recursively to color the rest of
  3966. the graph.
  3967. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  3968. move-related and that don't interfere with each other, a process
  3969. called \emph{coalescing}. While coalescing decreases the number of
  3970. moves, it can make the graph more difficult to
  3971. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  3972. which two variables are merged only if they have fewer than $k$
  3973. neighbors of high degree. \citet{George:1996aa} observe that
  3974. conservative coalescing is sometimes too conservative and make it more
  3975. aggressive by iterating the coalescing with the removal of low-degree
  3976. vertices.
  3977. %
  3978. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  3979. also propose \emph{biased coloring} in which a variable is assigned to
  3980. the same color as another move-related variable if possible, as
  3981. discussed in Section~\ref{sec:move-biasing}.
  3982. %
  3983. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  3984. performs coalescing, graph coloring, and spill code insertion until
  3985. all variables have been assigned a location.
  3986. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  3987. spills variables that don't have to be: a high-degree variable can be
  3988. colorable if many of its neighbors are assigned the same color.
  3989. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  3990. high-degree vertex is not immediately spilled. Instead the decision is
  3991. deferred until after the recursive call, at which point it is apparent
  3992. whether there is actually an available color or not. We observe that
  3993. this algorithm is equivalent to the smallest-last ordering
  3994. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  3995. be registers and the rest to be stack locations.
  3996. %% biased coloring
  3997. Earlier editions of the compiler course at Indiana University
  3998. \citep{Dybvig:2010aa} were based on the algorithm of
  3999. \citet{Briggs:1994kx}.
  4000. The smallest-last ordering algorithm is one of many \emph{greedy}
  4001. coloring algorithms. A greedy coloring algorithm visits all the
  4002. vertices in a particular order and assigns each one the first
  4003. available color. An \emph{offline} greedy algorithm chooses the
  4004. ordering up-front, prior to assigning colors. The algorithm of
  4005. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4006. ordering does not depend on the colors assigned, so the algorithm
  4007. could be split into two phases. Other orderings are possible. For
  4008. example, \citet{Chow:1984ys} order variables according an estimate of
  4009. runtime cost.
  4010. An \emph{online} greedy coloring algorithm uses information about the
  4011. current assignment of colors to influence the order in which the
  4012. remaining vertices are colored. The saturation-based algorithm
  4013. described in this chapter is one such algorithm. We choose to use
  4014. saturation-based coloring is because it is fun to introduce graph
  4015. coloring via Sudoku.
  4016. A register allocator may choose to map each variable to just one
  4017. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4018. variable to one or more locations. The later can be achieved by
  4019. \emph{live range splitting}, where a variable is replaced by several
  4020. variables that each handle part of its live
  4021. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4022. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4023. %% replacement algorithm, bottom-up local
  4024. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4025. %% Cooper: top-down (priority bassed), bottom-up
  4026. %% top-down
  4027. %% order variables by priority (estimated cost)
  4028. %% caveat: split variables into two groups:
  4029. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4030. %% color the constrained ones first
  4031. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4032. %% cite J. Cocke for an algorithm that colors variables
  4033. %% in a high-degree first ordering
  4034. %Register Allocation via Usage Counts, Freiburghouse CACM
  4035. \citet{Palsberg:2007si} observe that many of the interference graphs
  4036. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4037. that is, every cycle with four or more edges has an edge which is not
  4038. part of the cycle but which connects two vertices on the cycle. Such
  4039. graphs can be optimally colored by the greedy algorithm with a vertex
  4040. ordering determined by maximum cardinality search.
  4041. In situations where compile time is of utmost importance, such as in
  4042. just-in-time compilers, graph coloring algorithms can be too expensive
  4043. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4044. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4045. \chapter{Booleans and Control Flow}
  4046. \label{ch:Rif}
  4047. \index{Boolean}
  4048. \index{control flow}
  4049. \index{conditional expression}
  4050. The \LangInt{} and \LangVar{} languages only have a single kind of
  4051. value, integers. In this chapter we add a second kind of value, the
  4052. Booleans, to create the \LangIf{} language. The Boolean values
  4053. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4054. respectively in Racket. The \LangIf{} language includes several
  4055. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4056. \key{<}, etc.) and the conditional \key{if} expression. With the
  4057. addition of \key{if}, programs can have non-trivial control flow which
  4058. impacts \code{explicate-control} and liveness analysis. Also, because
  4059. we now have two kinds of values, we need to handle programs that apply
  4060. an operation to the wrong kind of value, such as \code{(not 1)}.
  4061. There are two language design options for such situations. One option
  4062. is to signal an error and the other is to provide a wider
  4063. interpretation of the operation. The Racket language uses a mixture of
  4064. these two options, depending on the operation and the kind of
  4065. value. For example, the result of \code{(not 1)} in Racket is
  4066. \code{\#f} because Racket treats non-zero integers as if they were
  4067. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4068. error in Racket because \code{car} expects a pair.
  4069. Typed Racket makes similar design choices as Racket, except much of
  4070. the error detection happens at compile time instead of run time. Typed
  4071. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4072. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4073. because Typed Racket expects the type of the argument to be of the
  4074. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4075. The \LangIf{} language performs type checking during compilation like
  4076. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4077. alternative choice, that is, a dynamically typed language like Racket.
  4078. The \LangIf{} language is a subset of Typed Racket; for some
  4079. operations we are more restrictive, for example, rejecting
  4080. \code{(not 1)}.
  4081. This chapter is organized as follows. We begin by defining the syntax
  4082. and interpreter for the \LangIf{} language
  4083. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4084. checking and build a type checker for \LangIf{}
  4085. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4086. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4087. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4088. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4089. discuss how our compiler passes change to accommodate Booleans and
  4090. conditional control flow. There is one new pass, named \code{shrink},
  4091. that translates some operators into others, thereby reducing the
  4092. number of operators that need to be handled in later passes. The
  4093. largest changes occur in \code{explicate-control}, to translate
  4094. \code{if} expressions into control-flow graphs
  4095. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4096. allocation, the liveness analysis now has multiple basic blocks to
  4097. process and there is the interesting question of how to handle
  4098. conditional jumps.
  4099. \section{The \LangIf{} Language}
  4100. \label{sec:lang-if}
  4101. The concrete syntax of the \LangIf{} language is defined in
  4102. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4103. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4104. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4105. \code{\#f}, and the conditional \code{if} expression. We expand the
  4106. operators to include
  4107. \begin{enumerate}
  4108. \item subtraction on integers,
  4109. \item the logical operators \key{and}, \key{or} and \key{not},
  4110. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4111. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4112. comparing integers.
  4113. \end{enumerate}
  4114. We reorganize the abstract syntax for the primitive operations in
  4115. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4116. them. This means that the grammar no longer checks whether the arity
  4117. of an operators matches the number of arguments. That responsibility
  4118. is moved to the type checker for \LangIf{}, which we introduce in
  4119. Section~\ref{sec:type-check-Rif}.
  4120. \begin{figure}[tp]
  4121. \centering
  4122. \fbox{
  4123. \begin{minipage}{0.96\textwidth}
  4124. \[
  4125. \begin{array}{lcl}
  4126. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4127. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4128. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4129. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4130. &\mid& \itm{bool}
  4131. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4132. \mid (\key{not}\;\Exp) \\
  4133. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4134. \LangIf{} &::=& \Exp
  4135. \end{array}
  4136. \]
  4137. \end{minipage}
  4138. }
  4139. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4140. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4141. \label{fig:Rif-concrete-syntax}
  4142. \end{figure}
  4143. \begin{figure}[tp]
  4144. \centering
  4145. \fbox{
  4146. \begin{minipage}{0.96\textwidth}
  4147. \[
  4148. \begin{array}{lcl}
  4149. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4150. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4151. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4152. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4153. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4154. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4155. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4156. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4157. \end{array}
  4158. \]
  4159. \end{minipage}
  4160. }
  4161. \caption{The abstract syntax of \LangIf{}.}
  4162. \label{fig:Rif-syntax}
  4163. \end{figure}
  4164. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4165. which inherits from the interpreter for \LangVar{}
  4166. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4167. evaluate to the corresponding Boolean values. The conditional
  4168. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4169. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4170. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4171. operations \code{not} and \code{and} behave as you might expect, but
  4172. note that the \code{and} operation is short-circuiting. That is, given
  4173. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4174. evaluated if $e_1$ evaluates to \code{\#f}.
  4175. With the increase in the number of primitive operations, the
  4176. interpreter would become repetitive without some care. We refactor
  4177. the case for \code{Prim}, moving the code that differs with each
  4178. operation into the \code{interp-op} method shown in in
  4179. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4180. separately because of its short-circuiting behavior.
  4181. \begin{figure}[tbp]
  4182. \begin{lstlisting}
  4183. (define interp-Rif-class
  4184. (class interp-Rvar-class
  4185. (super-new)
  4186. (define/public (interp-op op) ...)
  4187. (define/override ((interp-exp env) e)
  4188. (define recur (interp-exp env))
  4189. (match e
  4190. [(Bool b) b]
  4191. [(If cnd thn els)
  4192. (match (recur cnd)
  4193. [#t (recur thn)]
  4194. [#f (recur els)])]
  4195. [(Prim 'and (list e1 e2))
  4196. (match (recur e1)
  4197. [#t (match (recur e2) [#t #t] [#f #f])]
  4198. [#f #f])]
  4199. [(Prim op args)
  4200. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4201. [else ((super interp-exp env) e)]))
  4202. ))
  4203. (define (interp-Rif p)
  4204. (send (new interp-Rif-class) interp-program p))
  4205. \end{lstlisting}
  4206. \caption{Interpreter for the \LangIf{} language. (See
  4207. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4208. \label{fig:interp-Rif}
  4209. \end{figure}
  4210. \begin{figure}[tbp]
  4211. \begin{lstlisting}
  4212. (define/public (interp-op op)
  4213. (match op
  4214. ['+ fx+]
  4215. ['- fx-]
  4216. ['read read-fixnum]
  4217. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4218. ['or (lambda (v1 v2)
  4219. (cond [(and (boolean? v1) (boolean? v2))
  4220. (or v1 v2)]))]
  4221. ['eq? (lambda (v1 v2)
  4222. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4223. (and (boolean? v1) (boolean? v2))
  4224. (and (vector? v1) (vector? v2)))
  4225. (eq? v1 v2)]))]
  4226. ['< (lambda (v1 v2)
  4227. (cond [(and (fixnum? v1) (fixnum? v2))
  4228. (< v1 v2)]))]
  4229. ['<= (lambda (v1 v2)
  4230. (cond [(and (fixnum? v1) (fixnum? v2))
  4231. (<= v1 v2)]))]
  4232. ['> (lambda (v1 v2)
  4233. (cond [(and (fixnum? v1) (fixnum? v2))
  4234. (> v1 v2)]))]
  4235. ['>= (lambda (v1 v2)
  4236. (cond [(and (fixnum? v1) (fixnum? v2))
  4237. (>= v1 v2)]))]
  4238. [else (error 'interp-op "unknown operator")]))
  4239. \end{lstlisting}
  4240. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4241. \label{fig:interp-op-Rif}
  4242. \end{figure}
  4243. \section{Type Checking \LangIf{} Programs}
  4244. \label{sec:type-check-Rif}
  4245. \index{type checking}
  4246. \index{semantic analysis}
  4247. It is helpful to think about type checking in two complementary
  4248. ways. A type checker predicts the type of value that will be produced
  4249. by each expression in the program. For \LangIf{}, we have just two types,
  4250. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4251. \begin{lstlisting}
  4252. (+ 10 (- (+ 12 20)))
  4253. \end{lstlisting}
  4254. produces an \key{Integer} while
  4255. \begin{lstlisting}
  4256. (and (not #f) #t)
  4257. \end{lstlisting}
  4258. produces a \key{Boolean}.
  4259. Another way to think about type checking is that it enforces a set of
  4260. rules about which operators can be applied to which kinds of
  4261. values. For example, our type checker for \LangIf{} signals an error
  4262. for the below expression
  4263. \begin{lstlisting}
  4264. (not (+ 10 (- (+ 12 20))))
  4265. \end{lstlisting}
  4266. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4267. but the type checker enforces the rule that the argument of \code{not}
  4268. must be a \key{Boolean}.
  4269. We implement type checking using classes and methods because they
  4270. provide the open recursion needed to reuse code as we extend the type
  4271. checker in later chapters, analogous to the use of classes and methods
  4272. for the interpreters (Section~\ref{sec:extensible-interp}).
  4273. We separate the type checker for the \LangVar{} fragment into its own
  4274. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4275. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4276. from the type checker for \LangVar{}. These type checkers are in the
  4277. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4278. support code.
  4279. %
  4280. Each type checker is a structurally recursive function over the AST.
  4281. Given an input expression \code{e}, the type checker either signals an
  4282. error or returns an expression and its type (\key{Integer} or
  4283. \key{Boolean}). It returns an expression because there are situations
  4284. in which we want to change or update the expression.
  4285. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4286. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4287. \code{Integer}. To handle variables, the type checker uses the
  4288. environment \code{env} to map variables to types. Consider the case
  4289. for \key{let}. We type check the initializing expression to obtain
  4290. its type \key{T} and then associate type \code{T} with the variable
  4291. \code{x} in the environment used to type check the body of the
  4292. \key{let}. Thus, when the type checker encounters a use of variable
  4293. \code{x}, it can find its type in the environment. Regarding
  4294. primitive operators, we recursively analyze the arguments and then
  4295. invoke \code{type-check-op} to check whether the argument types are
  4296. allowed.
  4297. Several auxiliary methods are used in the type checker. The method
  4298. \code{operator-types} defines a dictionary that maps the operator
  4299. names to their parameter and return types. The \code{type-equal?}
  4300. method determines whether two types are equal, which for now simply
  4301. dispatches to \code{equal?} (deep equality). The
  4302. \code{check-type-equal?} method triggers an error if the two types are
  4303. not equal. The \code{type-check-op} method looks up the operator in
  4304. the \code{operator-types} dictionary and then checks whether the
  4305. argument types are equal to the parameter types. The result is the
  4306. return type of the operator.
  4307. \begin{figure}[tbp]
  4308. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4309. (define type-check-Rvar-class
  4310. (class object%
  4311. (super-new)
  4312. (define/public (operator-types)
  4313. '((+ . ((Integer Integer) . Integer))
  4314. (- . ((Integer) . Integer))
  4315. (read . (() . Integer))))
  4316. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4317. (define/public (check-type-equal? t1 t2 e)
  4318. (unless (type-equal? t1 t2)
  4319. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4320. (define/public (type-check-op op arg-types e)
  4321. (match (dict-ref (operator-types) op)
  4322. [`(,param-types . ,return-type)
  4323. (for ([at arg-types] [pt param-types])
  4324. (check-type-equal? at pt e))
  4325. return-type]
  4326. [else (error 'type-check-op "unrecognized ~a" op)]))
  4327. (define/public (type-check-exp env)
  4328. (lambda (e)
  4329. (match e
  4330. [(Int n) (values (Int n) 'Integer)]
  4331. [(Var x) (values (Var x) (dict-ref env x))]
  4332. [(Let x e body)
  4333. (define-values (e^ Te) ((type-check-exp env) e))
  4334. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4335. (values (Let x e^ b) Tb)]
  4336. [(Prim op es)
  4337. (define-values (new-es ts)
  4338. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4339. (values (Prim op new-es) (type-check-op op ts e))]
  4340. [else (error 'type-check-exp "couldn't match" e)])))
  4341. (define/public (type-check-program e)
  4342. (match e
  4343. [(Program info body)
  4344. (define-values (body^ Tb) ((type-check-exp '()) body))
  4345. (check-type-equal? Tb 'Integer body)
  4346. (Program info body^)]
  4347. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4348. ))
  4349. (define (type-check-Rvar p)
  4350. (send (new type-check-Rvar-class) type-check-program p))
  4351. \end{lstlisting}
  4352. \caption{Type checker for the \LangVar{} language.}
  4353. \label{fig:type-check-Rvar}
  4354. \end{figure}
  4355. \begin{figure}[tbp]
  4356. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4357. (define type-check-Rif-class
  4358. (class type-check-Rvar-class
  4359. (super-new)
  4360. (inherit check-type-equal?)
  4361. (define/override (operator-types)
  4362. (append '((- . ((Integer Integer) . Integer))
  4363. (and . ((Boolean Boolean) . Boolean))
  4364. (or . ((Boolean Boolean) . Boolean))
  4365. (< . ((Integer Integer) . Boolean))
  4366. (<= . ((Integer Integer) . Boolean))
  4367. (> . ((Integer Integer) . Boolean))
  4368. (>= . ((Integer Integer) . Boolean))
  4369. (not . ((Boolean) . Boolean))
  4370. )
  4371. (super operator-types)))
  4372. (define/override (type-check-exp env)
  4373. (lambda (e)
  4374. (match e
  4375. [(Prim 'eq? (list e1 e2))
  4376. (define-values (e1^ T1) ((type-check-exp env) e1))
  4377. (define-values (e2^ T2) ((type-check-exp env) e2))
  4378. (check-type-equal? T1 T2 e)
  4379. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4380. [(Bool b) (values (Bool b) 'Boolean)]
  4381. [(If cnd thn els)
  4382. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4383. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4384. (define-values (els^ Te) ((type-check-exp env) els))
  4385. (check-type-equal? Tc 'Boolean e)
  4386. (check-type-equal? Tt Te e)
  4387. (values (If cnd^ thn^ els^) Te)]
  4388. [else ((super type-check-exp env) e)])))
  4389. ))
  4390. (define (type-check-Rif p)
  4391. (send (new type-check-Rif-class) type-check-program p))
  4392. \end{lstlisting}
  4393. \caption{Type checker for the \LangIf{} language.}
  4394. \label{fig:type-check-Rif}
  4395. \end{figure}
  4396. Next we discuss the type checker for \LangIf{} in
  4397. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4398. two arguments to have the same type. The type of a Boolean constant is
  4399. \code{Boolean}. The condition of an \code{if} must be of
  4400. \code{Boolean} type and the two branches must have the same type. The
  4401. \code{operator-types} function adds dictionary entries for the other
  4402. new operators.
  4403. \begin{exercise}\normalfont
  4404. Create 10 new test programs in \LangIf{}. Half of the programs should
  4405. have a type error. For those programs, create an empty file with the
  4406. same base name but with file extension \code{.tyerr}. For example, if
  4407. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4408. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4409. \code{interp-tests} and \code{compiler-tests} that a type error is
  4410. expected. The other half of the test programs should not have type
  4411. errors.
  4412. In the \code{run-tests.rkt} script, change the second argument of
  4413. \code{interp-tests} and \code{compiler-tests} to
  4414. \code{type-check-Rif}, which causes the type checker to run prior to
  4415. the compiler passes. Temporarily change the \code{passes} to an empty
  4416. list and run the script, thereby checking that the new test programs
  4417. either type check or not as intended.
  4418. \end{exercise}
  4419. \section{The \LangCIf{} Intermediate Language}
  4420. \label{sec:Cif}
  4421. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4422. \LangCIf{} intermediate language. (The concrete syntax is in the
  4423. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4424. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4425. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4426. \key{\#f} to the \Arg{} non-terminal.
  4427. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4428. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4429. statement is a comparison operation and the branches are \code{goto}
  4430. statements, making it straightforward to compile \code{if} statements
  4431. to x86.
  4432. \begin{figure}[tp]
  4433. \fbox{
  4434. \begin{minipage}{0.96\textwidth}
  4435. \small
  4436. \[
  4437. \begin{array}{lcl}
  4438. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4439. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4440. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4441. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4442. &\mid& \UNIOP{\key{'not}}{\Atm}
  4443. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4444. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4445. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4446. \mid \GOTO{\itm{label}} \\
  4447. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4448. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4449. \end{array}
  4450. \]
  4451. \end{minipage}
  4452. }
  4453. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4454. (Figure~\ref{fig:c0-syntax}).}
  4455. \label{fig:c1-syntax}
  4456. \end{figure}
  4457. \section{The \LangXIf{} Language}
  4458. \label{sec:x86-if}
  4459. \index{x86} To implement the new logical operations, the comparison
  4460. operations, and the \key{if} expression, we need to delve further into
  4461. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4462. define the concrete and abstract syntax for the \LangXIf{} subset
  4463. of x86, which includes instructions for logical operations,
  4464. comparisons, and conditional jumps.
  4465. One challenge is that x86 does not provide an instruction that
  4466. directly implements logical negation (\code{not} in \LangIf{} and
  4467. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4468. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4469. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4470. bit of its arguments, and writes the results into its second argument.
  4471. Recall the truth table for exclusive-or:
  4472. \begin{center}
  4473. \begin{tabular}{l|cc}
  4474. & 0 & 1 \\ \hline
  4475. 0 & 0 & 1 \\
  4476. 1 & 1 & 0
  4477. \end{tabular}
  4478. \end{center}
  4479. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4480. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4481. for the bit $1$, the result is the opposite of the second bit. Thus,
  4482. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4483. the first argument:
  4484. \[
  4485. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4486. \qquad\Rightarrow\qquad
  4487. \begin{array}{l}
  4488. \key{movq}~ \Arg\key{,} \Var\\
  4489. \key{xorq}~ \key{\$1,} \Var
  4490. \end{array}
  4491. \]
  4492. \begin{figure}[tp]
  4493. \fbox{
  4494. \begin{minipage}{0.96\textwidth}
  4495. \[
  4496. \begin{array}{lcl}
  4497. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4498. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4499. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4500. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4501. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4502. \key{subq} \; \Arg\key{,} \Arg \mid
  4503. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4504. && \gray{ \key{callq} \; \itm{label} \mid
  4505. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4506. && \gray{ \itm{label}\key{:}\; \Instr }
  4507. \mid \key{xorq}~\Arg\key{,}~\Arg
  4508. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4509. && \key{set}cc~\Arg
  4510. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4511. \mid \key{j}cc~\itm{label}
  4512. \\
  4513. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4514. & & \gray{ \key{main:} \; \Instr\ldots }
  4515. \end{array}
  4516. \]
  4517. \end{minipage}
  4518. }
  4519. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4520. \label{fig:x86-1-concrete}
  4521. \end{figure}
  4522. \begin{figure}[tp]
  4523. \fbox{
  4524. \begin{minipage}{0.98\textwidth}
  4525. \small
  4526. \[
  4527. \begin{array}{lcl}
  4528. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4529. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4530. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4531. \mid \BYTEREG{\itm{bytereg}} \\
  4532. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4533. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4534. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4535. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4536. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4537. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4538. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4539. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4540. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4541. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4542. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4543. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4544. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4545. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4546. \end{array}
  4547. \]
  4548. \end{minipage}
  4549. }
  4550. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4551. \label{fig:x86-1}
  4552. \end{figure}
  4553. Next we consider the x86 instructions that are relevant for compiling
  4554. the comparison operations. The \key{cmpq} instruction compares its two
  4555. arguments to determine whether one argument is less than, equal, or
  4556. greater than the other argument. The \key{cmpq} instruction is unusual
  4557. regarding the order of its arguments and where the result is
  4558. placed. The argument order is backwards: if you want to test whether
  4559. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4560. \key{cmpq} is placed in the special EFLAGS register. This register
  4561. cannot be accessed directly but it can be queried by a number of
  4562. instructions, including the \key{set} instruction. The instruction
  4563. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4564. depending on whether the comparison comes out according to the
  4565. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4566. for less-or-equal, \key{g} for greater, \key{ge} for
  4567. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4568. that its destination argument must be single byte register, such as
  4569. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4570. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4571. instruction can be used to move from a single byte register to a
  4572. normal 64-bit register. The abstract syntax for the \code{set}
  4573. instruction differs from the concrete syntax in that it separates the
  4574. instruction name from the condition code.
  4575. The x86 instruction for conditional jump is relevant to the
  4576. compilation of \key{if} expressions. The instruction
  4577. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4578. the instruction after \itm{label} depending on whether the result in
  4579. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4580. jump instruction falls through to the next instruction. Like the
  4581. abstract syntax for \code{set}, the abstract syntax for conditional
  4582. jump separates the instruction name from the condition code. For
  4583. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4584. the conditional jump instruction relies on the EFLAGS register, it is
  4585. common for it to be immediately preceded by a \key{cmpq} instruction
  4586. to set the EFLAGS register.
  4587. \section{Shrink the \LangIf{} Language}
  4588. \label{sec:shrink-Rif}
  4589. The \LangIf{} language includes several operators that are easily
  4590. expressible with other operators. For example, subtraction is
  4591. expressible using addition and negation.
  4592. \[
  4593. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4594. \]
  4595. Several of the comparison operations are expressible using less-than
  4596. and logical negation.
  4597. \[
  4598. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4599. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4600. \]
  4601. The \key{let} is needed in the above translation to ensure that
  4602. expression $e_1$ is evaluated before $e_2$.
  4603. By performing these translations in the front-end of the compiler, the
  4604. later passes of the compiler do not need to deal with these operators,
  4605. making the passes shorter.
  4606. %% On the other hand, sometimes
  4607. %% these translations make it more difficult to generate the most
  4608. %% efficient code with respect to the number of instructions. However,
  4609. %% these differences typically do not affect the number of accesses to
  4610. %% memory, which is the primary factor that determines execution time on
  4611. %% modern computer architectures.
  4612. \begin{exercise}\normalfont
  4613. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4614. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4615. translating them to other constructs in \LangIf{}.
  4616. %
  4617. Create six test programs that involve these operators.
  4618. %
  4619. In the \code{run-tests.rkt} script, add the following entry for
  4620. \code{shrink} to the list of passes (it should be the only pass at
  4621. this point).
  4622. \begin{lstlisting}
  4623. (list "shrink" shrink interp-Rif type-check-Rif)
  4624. \end{lstlisting}
  4625. This instructs \code{interp-tests} to run the intepreter
  4626. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4627. output of \code{shrink}.
  4628. %
  4629. Run the script to test your compiler on all the test programs.
  4630. \end{exercise}
  4631. \section{Uniquify Variables}
  4632. \label{sec:uniquify-Rif}
  4633. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4634. \code{if} expressions.
  4635. \begin{exercise}\normalfont
  4636. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4637. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4638. \begin{lstlisting}
  4639. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4640. \end{lstlisting}
  4641. Run the script to test your compiler.
  4642. \end{exercise}
  4643. \section{Remove Complex Operands}
  4644. \label{sec:remove-complex-opera-Rif}
  4645. The output language for this pass is \LangIfANF{}
  4646. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4647. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4648. \code{If} is not. All three sub-expressions of an \code{If} are
  4649. allowed to be complex expressions but the operands of \code{not} and
  4650. the comparisons must be atoms.
  4651. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4652. \code{rco-atom} functions according to whether the output needs to be
  4653. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4654. Regarding \code{If}, it is particularly important to \textbf{not}
  4655. replace its condition with a temporary variable because that would
  4656. interfere with the generation of high-quality output in the
  4657. \code{explicate-control} pass.
  4658. \begin{figure}[tp]
  4659. \centering
  4660. \fbox{
  4661. \begin{minipage}{0.96\textwidth}
  4662. \[
  4663. \begin{array}{rcl}
  4664. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4665. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4666. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4667. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4668. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4669. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4670. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4671. \end{array}
  4672. \]
  4673. \end{minipage}
  4674. }
  4675. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4676. \label{fig:Rif-anf-syntax}
  4677. \end{figure}
  4678. \begin{exercise}\normalfont
  4679. %
  4680. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4681. and \code{rco-exp} functions in \code{compiler.rkt}.
  4682. %
  4683. Create three new \LangInt{} programs that exercise the interesting
  4684. code in this pass.
  4685. %
  4686. In the \code{run-tests.rkt} script, add the following entry to the
  4687. list of \code{passes} and then run the script to test your compiler.
  4688. \begin{lstlisting}
  4689. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4690. \end{lstlisting}
  4691. \end{exercise}
  4692. \section{Explicate Control}
  4693. \label{sec:explicate-control-Rif}
  4694. Recall that the purpose of \code{explicate-control} is to make the
  4695. order of evaluation explicit in the syntax of the program. With the
  4696. addition of \key{if} this get more interesting.
  4697. As a motivating example, consider the following program that has an
  4698. \key{if} expression nested in the predicate of another \key{if}.
  4699. % cond_test_41.rkt
  4700. \begin{center}
  4701. \begin{minipage}{0.96\textwidth}
  4702. \begin{lstlisting}
  4703. (let ([x (read)])
  4704. (let ([y (read)])
  4705. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4706. (+ y 2)
  4707. (+ y 10))))
  4708. \end{lstlisting}
  4709. \end{minipage}
  4710. \end{center}
  4711. %
  4712. The naive way to compile \key{if} and the comparison would be to
  4713. handle each of them in isolation, regardless of their context. Each
  4714. comparison would be translated into a \key{cmpq} instruction followed
  4715. by a couple instructions to move the result from the EFLAGS register
  4716. into a general purpose register or stack location. Each \key{if} would
  4717. be translated into a \key{cmpq} instruction followed by a conditional
  4718. jump. The generated code for the inner \key{if} in the above example
  4719. would be as follows.
  4720. \begin{center}
  4721. \begin{minipage}{0.96\textwidth}
  4722. \begin{lstlisting}
  4723. ...
  4724. cmpq $1, x ;; (< x 1)
  4725. setl %al
  4726. movzbq %al, tmp
  4727. cmpq $1, tmp ;; (if ...)
  4728. je then_branch_1
  4729. jmp else_branch_1
  4730. ...
  4731. \end{lstlisting}
  4732. \end{minipage}
  4733. \end{center}
  4734. However, if we take context into account we can do better and reduce
  4735. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4736. Our goal will be compile \key{if} expressions so that the relevant
  4737. comparison instruction appears directly before the conditional jump.
  4738. For example, we want to generate the following code for the inner
  4739. \code{if}.
  4740. \begin{center}
  4741. \begin{minipage}{0.96\textwidth}
  4742. \begin{lstlisting}
  4743. ...
  4744. cmpq $1, x
  4745. je then_branch_1
  4746. jmp else_branch_1
  4747. ...
  4748. \end{lstlisting}
  4749. \end{minipage}
  4750. \end{center}
  4751. One way to achieve this is to reorganize the code at the level of
  4752. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4753. the following code.
  4754. \begin{center}
  4755. \begin{minipage}{0.96\textwidth}
  4756. \begin{lstlisting}
  4757. (let ([x (read)])
  4758. (let ([y (read)])
  4759. (if (< x 1)
  4760. (if (eq? x 0)
  4761. (+ y 2)
  4762. (+ y 10))
  4763. (if (eq? x 2)
  4764. (+ y 2)
  4765. (+ y 10)))))
  4766. \end{lstlisting}
  4767. \end{minipage}
  4768. \end{center}
  4769. Unfortunately, this approach duplicates the two branches from the
  4770. outer \code{if} and a compiler must never duplicate code!
  4771. We need a way to perform the above transformation but without
  4772. duplicating code. That is, we need a way for different parts of a
  4773. program to refer to the same piece of code. At the level of x86
  4774. assembly this is straightforward because we can label the code for
  4775. each branch and insert jumps in all the places that need to execute
  4776. the branch. In our intermediate language, we need to move away from
  4777. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4778. particular, we use a standard program representation called a
  4779. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4780. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4781. labeled sequence of code, called a \emph{basic block}, and each edge
  4782. represents a jump to another block. The \key{CProgram} construct of
  4783. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4784. as an alist mapping labels to basic blocks. Each basic block is
  4785. represented by the $\Tail$ non-terminal.
  4786. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4787. \code{remove-complex-opera*} pass and then the
  4788. \code{explicate-control} pass on the example program. We walk through
  4789. the output program and then discuss the algorithm.
  4790. %
  4791. Following the order of evaluation in the output of
  4792. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4793. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4794. inner \key{if}. In the output of \code{explicate-control}, in the
  4795. block labeled \code{start}, is two assignment statements followed by a
  4796. \code{if} statement that branches to \code{block40} or
  4797. \code{block41}. The blocks associated with those labels contain the
  4798. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4799. respectively. In particular, we start \code{block40} with the
  4800. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4801. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4802. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4803. \code{block41} is similar.
  4804. \begin{figure}[tbp]
  4805. \begin{tabular}{lll}
  4806. \begin{minipage}{0.4\textwidth}
  4807. % cond_test_41.rkt
  4808. \begin{lstlisting}
  4809. (let ([x (read)])
  4810. (let ([y (read)])
  4811. (if (if (< x 1)
  4812. (eq? x 0)
  4813. (eq? x 2))
  4814. (+ y 2)
  4815. (+ y 10))))
  4816. \end{lstlisting}
  4817. \hspace{40pt}$\Downarrow$
  4818. \begin{lstlisting}
  4819. (let ([x (read)])
  4820. (let ([y (read)])
  4821. (if (if (< x 1)
  4822. (eq? x 0)
  4823. (eq? x 2))
  4824. (+ y 2)
  4825. (+ y 10))))
  4826. \end{lstlisting}
  4827. \end{minipage}
  4828. &
  4829. $\Rightarrow$
  4830. &
  4831. \begin{minipage}{0.55\textwidth}
  4832. \begin{lstlisting}
  4833. start:
  4834. x = (read);
  4835. y = (read);
  4836. if (< x 1) goto block40;
  4837. else goto block41;
  4838. block40:
  4839. if (eq? x 0) goto block38;
  4840. else goto block39;
  4841. block41:
  4842. if (eq? x 2) goto block38;
  4843. else goto block39;
  4844. block38:
  4845. return (+ y 2);
  4846. block39:
  4847. return (+ y 10);
  4848. \end{lstlisting}
  4849. \end{minipage}
  4850. \end{tabular}
  4851. \caption{Translation from \LangIf{} to \LangCIf{}
  4852. via the \code{explicate-control}.}
  4853. \label{fig:explicate-control-s1-38}
  4854. \end{figure}
  4855. %% The nice thing about the output of \code{explicate-control} is that
  4856. %% there are no unnecessary comparisons and every comparison is part of a
  4857. %% conditional jump.
  4858. %% The down-side of this output is that it includes
  4859. %% trivial blocks, such as the blocks labeled \code{block92} through
  4860. %% \code{block95}, that only jump to another block. We discuss a solution
  4861. %% to this problem in Section~\ref{sec:opt-jumps}.
  4862. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4863. \code{explicate-control} for \LangVar{} using two mutually recursive
  4864. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4865. former function translates expressions in tail position whereas the
  4866. later function translates expressions on the right-hand-side of a
  4867. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4868. have a new kind of position to deal with: the predicate position of
  4869. the \key{if}. We need another function, \code{explicate-pred}, that
  4870. takes an \LangIf{} expression and two blocks for the then-branch and
  4871. else-branch. The output of \code{explicate-pred} is a block.
  4872. %
  4873. In the following paragraphs we discuss specific cases in the
  4874. \code{explicate-pred} function as well as additions to the
  4875. \code{explicate-tail} and \code{explicate-assign} functions.
  4876. \begin{figure}[tbp]
  4877. \begin{lstlisting}
  4878. (define (explicate-pred cnd thn els)
  4879. (match cnd
  4880. [(Var x) ___]
  4881. [(Let x rhs body) ___]
  4882. [(Prim 'not (list e)) ___]
  4883. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4884. (IfStmt (Prim op arg*) (force (block->goto thn))
  4885. (force (block->goto els)))]
  4886. [(Bool b) (if b thn els)]
  4887. [(If cnd^ thn^ els^) ___]
  4888. [else (error "explicate-pred unhandled case" cnd)]))
  4889. \end{lstlisting}
  4890. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4891. \label{fig:explicate-pred}
  4892. \end{figure}
  4893. The skeleton for the \code{explicate-pred} function is given in
  4894. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4895. that can have type \code{Boolean}. We detail a few cases here and
  4896. leave the rest for the reader. The input to this function is an
  4897. expression and two blocks, \code{thn} and \code{els}, for the two
  4898. branches of the enclosing \key{if}.
  4899. %
  4900. Consider the case for Boolean constants in
  4901. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4902. evaluation\index{partial evaluation} and output either the \code{thn}
  4903. or \code{els} branch depending on whether the constant is true or
  4904. false. This case demonstrates that we sometimes discard the \code{thn}
  4905. or \code{els} blocks that are input to \code{explicate-pred}.
  4906. The case for \key{if} in \code{explicate-pred} is particularly
  4907. illuminating because it deals with the challenges we discussed above
  4908. regarding nested \key{if} expressions
  4909. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4910. \lstinline{els^} branches of the \key{if} inherit their context from
  4911. the current one, that is, predicate context. So you should recursively
  4912. apply \code{explicate-pred} to the \lstinline{thn^} and
  4913. \lstinline{els^} branches. For both of those recursive calls, pass
  4914. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4915. and \code{els} may get used twice, once inside each recursive call. As
  4916. discussed above, to avoid duplicating code, we need to add them to the
  4917. control-flow graph so that we can instead refer to them by name and
  4918. execute them with a \key{goto}. However, as we saw in the cases above
  4919. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4920. get used at all and we don't want to prematurely add them to the
  4921. control-flow graph if they end up being discarded.
  4922. The solution to this conundrum is to use \emph{lazy
  4923. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  4924. adding the blocks to the control-flow graph until the points where we
  4925. know they will be used. Racket provides support for lazy evaluation
  4926. with the
  4927. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4928. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4929. \index{delay} creates a \emph{promise}\index{promise} in which the
  4930. evaluation of the expressions is postponed. When \key{(force}
  4931. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4932. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4933. $e_n$ is cached in the promise and returned. If \code{force} is
  4934. applied again to the same promise, then the cached result is returned.
  4935. If \code{force} is applied to an argument that is not a promise,
  4936. \code{force} simply returns the argument.
  4937. We use lazy evaluation for the input and output blocks of the
  4938. functions \code{explicate-pred} and \code{explicate-assign} and for
  4939. the output block of \code{explicate-tail}. So instead of taking and
  4940. returning blocks, they take and return promises. Furthermore, when we
  4941. come to a situation in which we a block might be used more than once,
  4942. as in the case for \code{if} in \code{explicate-pred}, we transform
  4943. the promise into a new promise that will add the block to the
  4944. control-flow graph and return a \code{goto}. The following auxiliary
  4945. function named \code{block->goto} accomplishes this task. It begins
  4946. with \code{delay} to create a promise. When forced, this promise will
  4947. force the original promise. If that returns a \code{goto} (because the
  4948. block was already added to the control-flow graph), then we return the
  4949. \code{goto}. Otherwise we add the block to the control-flow graph with
  4950. another auxiliary function named \code{add-node}. That function
  4951. returns the label for the new block, which we use to create a
  4952. \code{goto}.
  4953. \begin{lstlisting}
  4954. (define (block->goto block)
  4955. (delay
  4956. (define b (force block))
  4957. (match b
  4958. [(Goto label) (Goto label)]
  4959. [else (Goto (add-node b))])))
  4960. \end{lstlisting}
  4961. Returning to the discussion of \code{explicate-pred}
  4962. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4963. operators. This is one of the base cases of the recursive function so
  4964. we translate the comparison to an \code{if} statement. We apply
  4965. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4966. that will add then to the control-flow graph, which we can immediately
  4967. \code{force} to obtain the two goto's that form the branches of the
  4968. \code{if} statement.
  4969. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4970. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4971. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4972. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4973. %% results from the two recursive calls. We complete the case for
  4974. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4975. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4976. %% the result $B_5$.
  4977. %% \[
  4978. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4979. %% \quad\Rightarrow\quad
  4980. %% B_5
  4981. %% \]
  4982. The \code{explicate-tail} and \code{explicate-assign} functions need
  4983. additional cases for Boolean constants and \key{if}.
  4984. %
  4985. In the cases for \code{if}, the two branches inherit the current
  4986. context, so in \code{explicate-tail} they are in tail position and in
  4987. \code{explicate-assign} they are in assignment position. The
  4988. \code{cont} parameter of \code{explicate-assign} is used in both
  4989. recursive calls, so make sure to use \code{block->goto} on it.
  4990. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4991. %% inherit the current context, so they are in tail position. Thus, the
  4992. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4993. %% \code{explicate-tail}.
  4994. %% %
  4995. %% We need to pass $B_0$ as the accumulator argument for both of these
  4996. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4997. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4998. %% to the control-flow graph and obtain a promised goto $G_0$.
  4999. %% %
  5000. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5001. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5002. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5003. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5004. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5005. %% \[
  5006. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5007. %% \]
  5008. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5009. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5010. %% should not be confused with the labels for the blocks that appear in
  5011. %% the generated code. We initially construct unlabeled blocks; we only
  5012. %% attach labels to blocks when we add them to the control-flow graph, as
  5013. %% we see in the next case.
  5014. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5015. %% function. The context of the \key{if} is an assignment to some
  5016. %% variable $x$ and then the control continues to some promised block
  5017. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5018. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5019. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5020. %% branches of the \key{if} inherit the current context, so they are in
  5021. %% assignment positions. Let $B_2$ be the result of applying
  5022. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5023. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5024. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5025. %% the result of applying \code{explicate-pred} to the predicate
  5026. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5027. %% translates to the promise $B_4$.
  5028. %% \[
  5029. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5030. %% \]
  5031. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5032. The way in which the \code{shrink} pass transforms logical operations
  5033. such as \code{and} and \code{or} can impact the quality of code
  5034. generated by \code{explicate-control}. For example, consider the
  5035. following program.
  5036. % cond_test_21.rkt
  5037. \begin{lstlisting}
  5038. (if (and (eq? (read) 0) (eq? (read) 1))
  5039. 0
  5040. 42)
  5041. \end{lstlisting}
  5042. The \code{and} operation should transform into something that the
  5043. \code{explicate-pred} function can still analyze and descend through to
  5044. reach the underlying \code{eq?} conditions. Ideally, your
  5045. \code{explicate-control} pass should generate code similar to the
  5046. following for the above program.
  5047. \begin{center}
  5048. \begin{lstlisting}
  5049. start:
  5050. tmp1 = (read);
  5051. if (eq? tmp1 0) goto block40;
  5052. else goto block39;
  5053. block40:
  5054. tmp2 = (read);
  5055. if (eq? tmp2 1) goto block38;
  5056. else goto block39;
  5057. block38:
  5058. return 0;
  5059. block39:
  5060. return 42;
  5061. \end{lstlisting}
  5062. \end{center}
  5063. \begin{exercise}\normalfont
  5064. Implement the pass \code{explicate-control} by adding the cases for
  5065. Boolean constants and \key{if} to the \code{explicate-tail} and
  5066. \code{explicate-assign}. Implement the auxiliary function
  5067. \code{explicate-pred} for predicate contexts.
  5068. %
  5069. Create test cases that exercise all of the new cases in the code for
  5070. this pass.
  5071. %
  5072. Add the following entry to the list of \code{passes} in
  5073. \code{run-tests.rkt} and then run this script to test your compiler.
  5074. \begin{lstlisting}
  5075. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5076. \end{lstlisting}
  5077. \end{exercise}
  5078. \section{Select Instructions}
  5079. \label{sec:select-Rif}
  5080. \index{instruction selection}
  5081. The \code{select-instructions} pass translate \LangCIf{} to
  5082. \LangXIfVar{}. Recall that we implement this pass using three
  5083. auxiliary functions, one for each of the non-terminals $\Atm$,
  5084. $\Stmt$, and $\Tail$.
  5085. For $\Atm$, we have new cases for the Booleans. We take the usual
  5086. approach of encoding them as integers, with true as 1 and false as 0.
  5087. \[
  5088. \key{\#t} \Rightarrow \key{1}
  5089. \qquad
  5090. \key{\#f} \Rightarrow \key{0}
  5091. \]
  5092. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5093. be implemented in terms of \code{xorq} as we discussed at the
  5094. beginning of this section. Given an assignment
  5095. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5096. if the left-hand side $\itm{var}$ is
  5097. the same as $\Atm$, then just the \code{xorq} suffices.
  5098. \[
  5099. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5100. \quad\Rightarrow\quad
  5101. \key{xorq}~\key{\$}1\key{,}~\Var
  5102. \]
  5103. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5104. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5105. x86. Then we have
  5106. \[
  5107. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5108. \quad\Rightarrow\quad
  5109. \begin{array}{l}
  5110. \key{movq}~\Arg\key{,}~\Var\\
  5111. \key{xorq}~\key{\$}1\key{,}~\Var
  5112. \end{array}
  5113. \]
  5114. Next consider the cases for \code{eq?} and less-than comparison.
  5115. Translating these operations to x86 is slightly involved due to the
  5116. unusual nature of the \key{cmpq} instruction discussed above. We
  5117. recommend translating an assignment from \code{eq?} into the following
  5118. sequence of three instructions. \\
  5119. \begin{tabular}{lll}
  5120. \begin{minipage}{0.4\textwidth}
  5121. \begin{lstlisting}
  5122. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5123. \end{lstlisting}
  5124. \end{minipage}
  5125. &
  5126. $\Rightarrow$
  5127. &
  5128. \begin{minipage}{0.4\textwidth}
  5129. \begin{lstlisting}
  5130. cmpq |$\Arg_2$|, |$\Arg_1$|
  5131. sete %al
  5132. movzbq %al, |$\Var$|
  5133. \end{lstlisting}
  5134. \end{minipage}
  5135. \end{tabular} \\
  5136. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5137. and \key{if} statements. Both are straightforward to translate to
  5138. x86. A \key{goto} becomes a jump instruction.
  5139. \[
  5140. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5141. \]
  5142. An \key{if} statement becomes a compare instruction followed by a
  5143. conditional jump (for the ``then'' branch) and the fall-through is to
  5144. a regular jump (for the ``else'' branch).\\
  5145. \begin{tabular}{lll}
  5146. \begin{minipage}{0.4\textwidth}
  5147. \begin{lstlisting}
  5148. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5149. else goto |$\ell_2$|;
  5150. \end{lstlisting}
  5151. \end{minipage}
  5152. &
  5153. $\Rightarrow$
  5154. &
  5155. \begin{minipage}{0.4\textwidth}
  5156. \begin{lstlisting}
  5157. cmpq |$\Arg_2$|, |$\Arg_1$|
  5158. je |$\ell_1$|
  5159. jmp |$\ell_2$|
  5160. \end{lstlisting}
  5161. \end{minipage}
  5162. \end{tabular} \\
  5163. \begin{exercise}\normalfont
  5164. Expand your \code{select-instructions} pass to handle the new features
  5165. of the \LangIf{} language.
  5166. %
  5167. Add the following entry to the list of \code{passes} in
  5168. \code{run-tests.rkt}
  5169. \begin{lstlisting}
  5170. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5171. \end{lstlisting}
  5172. %
  5173. Run the script to test your compiler on all the test programs.
  5174. \end{exercise}
  5175. \section{Register Allocation}
  5176. \label{sec:register-allocation-Rif}
  5177. \index{register allocation}
  5178. The changes required for \LangIf{} affect liveness analysis, building the
  5179. interference graph, and assigning homes, but the graph coloring
  5180. algorithm itself does not change.
  5181. \subsection{Liveness Analysis}
  5182. \label{sec:liveness-analysis-Rif}
  5183. \index{liveness analysis}
  5184. Recall that for \LangVar{} we implemented liveness analysis for a single
  5185. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5186. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5187. produces many basic blocks arranged in a control-flow graph. We
  5188. recommend that you create a new auxiliary function named
  5189. \code{uncover-live-CFG} that applies liveness analysis to a
  5190. control-flow graph.
  5191. The first question we is: what order should we process the basic
  5192. blocks in the control-flow graph? Recall that to perform liveness
  5193. analysis on a basic block we need to know its live-after set. If a
  5194. basic block has no successors (i.e. no out-edges in the control flow
  5195. graph), then it has an empty live-after set and we can immediately
  5196. apply liveness analysis to it. If a basic block has some successors,
  5197. then we need to complete liveness analysis on those blocks first. In
  5198. graph theory, a sequence of nodes is in \emph{topological
  5199. order}\index{topological order} if each vertex comes before its
  5200. successors. We need the opposite, so we can transpose the graph
  5201. before computing a topological order.
  5202. %
  5203. Use the \code{tsort} and \code{transpose} functions of the Racket
  5204. \code{graph} package to accomplish this.
  5205. %
  5206. As an aside, a topological ordering is only guaranteed to exist if the
  5207. graph does not contain any cycles. That is indeed the case for the
  5208. control-flow graphs that we generate from \LangIf{} programs.
  5209. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5210. learn how to handle cycles in the control-flow graph.
  5211. You'll need to construct a directed graph to represent the
  5212. control-flow graph. Do not use the \code{directed-graph} of the
  5213. \code{graph} package because that only allows at most one edge between
  5214. each pair of vertices, but a control-flow graph may have multiple
  5215. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5216. the support code implements a graph representation that allows
  5217. multiple edges between a pair of vertices.
  5218. The next question is how to analyze jump instructions. Recall that in
  5219. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5220. \code{label->live} that maps each label to the set of live locations
  5221. at the beginning of its block. We use \code{label->live} to determine
  5222. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5223. that we have many basic blocks, \code{label->live} needs to be updated
  5224. as we process the blocks. In particular, after performing liveness
  5225. analysis on a block, we take the live-before set of its first
  5226. instruction and associate that with the block's label in the
  5227. \code{label->live}.
  5228. In \LangXIfVar{} we also have the conditional jump
  5229. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5230. this instruction is particularly interesting because during
  5231. compilation we do not know which way a conditional jump will go. So
  5232. we do not know whether to use the live-before set for the following
  5233. instruction or the live-before set for the $\itm{label}$. However,
  5234. there is no harm to the correctness of the compiler if we classify
  5235. more locations as live than the ones that are truly live during a
  5236. particular execution of the instruction. Thus, we can take the union
  5237. of the live-before sets from the following instruction and from the
  5238. mapping for $\itm{label}$ in \code{label->live}.
  5239. The auxiliary functions for computing the variables in an
  5240. instruction's argument and for computing the variables read-from ($R$)
  5241. or written-to ($W$) by an instruction need to be updated to handle the
  5242. new kinds of arguments and instructions in \LangXIfVar{}.
  5243. \begin{exercise}\normalfont
  5244. Update the \code{uncover-live} pass and implement the
  5245. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5246. to the control-flow graph. Add the following entry to the list of
  5247. \code{passes} in the \code{run-tests.rkt} script.
  5248. \begin{lstlisting}
  5249. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5250. \end{lstlisting}
  5251. \end{exercise}
  5252. \subsection{Build the Interference Graph}
  5253. \label{sec:build-interference-Rif}
  5254. Many of the new instructions in \LangXIfVar{} can be handled in the
  5255. same way as the instructions in \LangXVar{}. Thus, if your code was
  5256. already quite general, it will not need to be changed to handle the
  5257. new instructions. If you code is not general enough, we recommend that
  5258. you change your code to be more general. For example, you can factor
  5259. out the computing of the the read and write sets for each kind of
  5260. instruction into two auxiliary functions.
  5261. Note that the \key{movzbq} instruction requires some special care,
  5262. similar to the \key{movq} instruction. See rule number 1 in
  5263. Section~\ref{sec:build-interference}.
  5264. \begin{exercise}\normalfont
  5265. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5266. following entries to the list of \code{passes} in the
  5267. \code{run-tests.rkt} script.
  5268. \begin{lstlisting}
  5269. (list "build-interference" build-interference interp-pseudo-x86-1)
  5270. (list "allocate-registers" allocate-registers interp-x86-1)
  5271. \end{lstlisting}
  5272. Run the script to test your compiler on all the \LangIf{} test
  5273. programs.
  5274. \end{exercise}
  5275. \section{Patch Instructions}
  5276. The second argument of the \key{cmpq} instruction must not be an
  5277. immediate value (such as an integer). So if you are comparing two
  5278. immediates, we recommend inserting a \key{movq} instruction to put the
  5279. second argument in \key{rax}. Also, recall that instructions may have
  5280. at most one memory reference.
  5281. %
  5282. The second argument of the \key{movzbq} must be a register.
  5283. %
  5284. There are no special restrictions on the jump instructions.
  5285. \begin{exercise}\normalfont
  5286. %
  5287. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5288. %
  5289. Add the following entry to the list of \code{passes} in
  5290. \code{run-tests.rkt} and then run this script to test your compiler.
  5291. \begin{lstlisting}
  5292. (list "patch-instructions" patch-instructions interp-x86-1)
  5293. \end{lstlisting}
  5294. \end{exercise}
  5295. \begin{figure}[tbp]
  5296. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5297. \node (Rif) at (0,2) {\large \LangIf{}};
  5298. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5299. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5300. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5301. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5302. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5303. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5304. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5305. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5306. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5307. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5308. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5309. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5310. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5311. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5312. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5313. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5314. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5315. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5316. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5317. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5318. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5319. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5320. \end{tikzpicture}
  5321. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5322. \label{fig:Rif-passes}
  5323. \end{figure}
  5324. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5325. compilation of \LangIf{}.
  5326. \section{An Example Translation}
  5327. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5328. \LangIf{} translated to x86, showing the results of
  5329. \code{explicate-control}, \code{select-instructions}, and the final
  5330. x86 assembly code.
  5331. \begin{figure}[tbp]
  5332. \begin{tabular}{lll}
  5333. \begin{minipage}{0.4\textwidth}
  5334. % cond_test_20.rkt
  5335. \begin{lstlisting}
  5336. (if (eq? (read) 1) 42 0)
  5337. \end{lstlisting}
  5338. $\Downarrow$
  5339. \begin{lstlisting}
  5340. start:
  5341. tmp7951 = (read);
  5342. if (eq? tmp7951 1)
  5343. goto block7952;
  5344. else
  5345. goto block7953;
  5346. block7952:
  5347. return 42;
  5348. block7953:
  5349. return 0;
  5350. \end{lstlisting}
  5351. $\Downarrow$
  5352. \begin{lstlisting}
  5353. start:
  5354. callq read_int
  5355. movq %rax, tmp7951
  5356. cmpq $1, tmp7951
  5357. je block7952
  5358. jmp block7953
  5359. block7953:
  5360. movq $0, %rax
  5361. jmp conclusion
  5362. block7952:
  5363. movq $42, %rax
  5364. jmp conclusion
  5365. \end{lstlisting}
  5366. \end{minipage}
  5367. &
  5368. $\Rightarrow\qquad$
  5369. \begin{minipage}{0.4\textwidth}
  5370. \begin{lstlisting}
  5371. start:
  5372. callq read_int
  5373. movq %rax, %rcx
  5374. cmpq $1, %rcx
  5375. je block7952
  5376. jmp block7953
  5377. block7953:
  5378. movq $0, %rax
  5379. jmp conclusion
  5380. block7952:
  5381. movq $42, %rax
  5382. jmp conclusion
  5383. .globl main
  5384. main:
  5385. pushq %rbp
  5386. movq %rsp, %rbp
  5387. pushq %r13
  5388. pushq %r12
  5389. pushq %rbx
  5390. pushq %r14
  5391. subq $0, %rsp
  5392. jmp start
  5393. conclusion:
  5394. addq $0, %rsp
  5395. popq %r14
  5396. popq %rbx
  5397. popq %r12
  5398. popq %r13
  5399. popq %rbp
  5400. retq
  5401. \end{lstlisting}
  5402. \end{minipage}
  5403. \end{tabular}
  5404. \caption{Example compilation of an \key{if} expression to x86.}
  5405. \label{fig:if-example-x86}
  5406. \end{figure}
  5407. \section{Challenge: Remove Jumps}
  5408. \label{sec:opt-jumps}
  5409. %% Recall that in the example output of \code{explicate-control} in
  5410. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5411. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5412. %% block. The first goal of this challenge assignment is to remove those
  5413. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5414. %% \code{explicate-control} on the left and shows the result of bypassing
  5415. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5416. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5417. %% \code{block55}. The optimized code on the right of
  5418. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5419. %% \code{then} branch jumping directly to \code{block55}. The story is
  5420. %% similar for the \code{else} branch, as well as for the two branches in
  5421. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5422. %% have been optimized in this way, there are no longer any jumps to
  5423. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5424. %% \begin{figure}[tbp]
  5425. %% \begin{tabular}{lll}
  5426. %% \begin{minipage}{0.4\textwidth}
  5427. %% \begin{lstlisting}
  5428. %% block62:
  5429. %% tmp54 = (read);
  5430. %% if (eq? tmp54 2) then
  5431. %% goto block59;
  5432. %% else
  5433. %% goto block60;
  5434. %% block61:
  5435. %% tmp53 = (read);
  5436. %% if (eq? tmp53 0) then
  5437. %% goto block57;
  5438. %% else
  5439. %% goto block58;
  5440. %% block60:
  5441. %% goto block56;
  5442. %% block59:
  5443. %% goto block55;
  5444. %% block58:
  5445. %% goto block56;
  5446. %% block57:
  5447. %% goto block55;
  5448. %% block56:
  5449. %% return (+ 700 77);
  5450. %% block55:
  5451. %% return (+ 10 32);
  5452. %% start:
  5453. %% tmp52 = (read);
  5454. %% if (eq? tmp52 1) then
  5455. %% goto block61;
  5456. %% else
  5457. %% goto block62;
  5458. %% \end{lstlisting}
  5459. %% \end{minipage}
  5460. %% &
  5461. %% $\Rightarrow$
  5462. %% &
  5463. %% \begin{minipage}{0.55\textwidth}
  5464. %% \begin{lstlisting}
  5465. %% block62:
  5466. %% tmp54 = (read);
  5467. %% if (eq? tmp54 2) then
  5468. %% goto block55;
  5469. %% else
  5470. %% goto block56;
  5471. %% block61:
  5472. %% tmp53 = (read);
  5473. %% if (eq? tmp53 0) then
  5474. %% goto block55;
  5475. %% else
  5476. %% goto block56;
  5477. %% block56:
  5478. %% return (+ 700 77);
  5479. %% block55:
  5480. %% return (+ 10 32);
  5481. %% start:
  5482. %% tmp52 = (read);
  5483. %% if (eq? tmp52 1) then
  5484. %% goto block61;
  5485. %% else
  5486. %% goto block62;
  5487. %% \end{lstlisting}
  5488. %% \end{minipage}
  5489. %% \end{tabular}
  5490. %% \caption{Optimize jumps by removing trivial blocks.}
  5491. %% \label{fig:optimize-jumps}
  5492. %% \end{figure}
  5493. %% The name of this pass is \code{optimize-jumps}. We recommend
  5494. %% implementing this pass in two phases. The first phrase builds a hash
  5495. %% table that maps labels to possibly improved labels. The second phase
  5496. %% changes the target of each \code{goto} to use the improved label. If
  5497. %% the label is for a trivial block, then the hash table should map the
  5498. %% label to the first non-trivial block that can be reached from this
  5499. %% label by jumping through trivial blocks. If the label is for a
  5500. %% non-trivial block, then the hash table should map the label to itself;
  5501. %% we do not want to change jumps to non-trivial blocks.
  5502. %% The first phase can be accomplished by constructing an empty hash
  5503. %% table, call it \code{short-cut}, and then iterating over the control
  5504. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5505. %% then update the hash table, mapping the block's source to the target
  5506. %% of the \code{goto}. Also, the hash table may already have mapped some
  5507. %% labels to the block's source, to you must iterate through the hash
  5508. %% table and update all of those so that they instead map to the target
  5509. %% of the \code{goto}.
  5510. %% For the second phase, we recommend iterating through the $\Tail$ of
  5511. %% each block in the program, updating the target of every \code{goto}
  5512. %% according to the mapping in \code{short-cut}.
  5513. %% \begin{exercise}\normalfont
  5514. %% Implement the \code{optimize-jumps} pass as a transformation from
  5515. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5516. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5517. %% example programs. Then check that your compiler still passes all of
  5518. %% your tests.
  5519. %% \end{exercise}
  5520. There is an opportunity for optimizing jumps that is apparent in the
  5521. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5522. ends with a jump to \code{block7953} and there are no other jumps to
  5523. \code{block7953} in the rest of the program. In this situation we can
  5524. avoid the runtime overhead of this jump by merging \code{block7953}
  5525. into the preceding block, in this case the \code{start} block.
  5526. Figure~\ref{fig:remove-jumps} shows the output of
  5527. \code{select-instructions} on the left and the result of this
  5528. optimization on the right.
  5529. \begin{figure}[tbp]
  5530. \begin{tabular}{lll}
  5531. \begin{minipage}{0.5\textwidth}
  5532. % cond_test_20.rkt
  5533. \begin{lstlisting}
  5534. start:
  5535. callq read_int
  5536. movq %rax, tmp7951
  5537. cmpq $1, tmp7951
  5538. je block7952
  5539. jmp block7953
  5540. block7953:
  5541. movq $0, %rax
  5542. jmp conclusion
  5543. block7952:
  5544. movq $42, %rax
  5545. jmp conclusion
  5546. \end{lstlisting}
  5547. \end{minipage}
  5548. &
  5549. $\Rightarrow\qquad$
  5550. \begin{minipage}{0.4\textwidth}
  5551. \begin{lstlisting}
  5552. start:
  5553. callq read_int
  5554. movq %rax, tmp7951
  5555. cmpq $1, tmp7951
  5556. je block7952
  5557. movq $0, %rax
  5558. jmp conclusion
  5559. block7952:
  5560. movq $42, %rax
  5561. jmp conclusion
  5562. \end{lstlisting}
  5563. \end{minipage}
  5564. \end{tabular}
  5565. \caption{Merging basic blocks by removing unnecessary jumps.}
  5566. \label{fig:remove-jumps}
  5567. \end{figure}
  5568. \begin{exercise}\normalfont
  5569. %
  5570. Implement a pass named \code{remove-jumps} that merges basic blocks
  5571. into their preceding basic block, when there is only one preceding
  5572. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5573. %
  5574. In the \code{run-tests.rkt} script, add the following entry to the
  5575. list of \code{passes} between \code{allocate-registers}
  5576. and \code{patch-instructions}.
  5577. \begin{lstlisting}
  5578. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5579. \end{lstlisting}
  5580. Run this script to test your compiler.
  5581. %
  5582. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5583. blocks on several test programs.
  5584. \end{exercise}
  5585. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5586. \chapter{Tuples and Garbage Collection}
  5587. \label{ch:Rvec}
  5588. \index{tuple}
  5589. \index{vector}
  5590. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5591. all the IR grammars are spelled out! \\ --Jeremy}
  5592. \margincomment{\scriptsize Be more explicit about how to deal with
  5593. the root stack. \\ --Jeremy}
  5594. In this chapter we study the implementation of mutable tuples, called
  5595. vectors in Racket. This language feature is the first to use the
  5596. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  5597. tuple is indefinite, that is, a tuple lives forever from the
  5598. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5599. is important to reclaim the space associated with a tuple when it is
  5600. no longer needed, which is why we also study \emph{garbage collection}
  5601. \emph{garbage collection} techniques in this chapter.
  5602. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5603. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5604. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5605. \code{void} value. The reason for including the later is that the
  5606. \code{vector-set!} operation returns a value of type
  5607. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5608. called the \code{Unit} type in the programming languages
  5609. literature. Racket's \code{Void} type is inhabited by a single value
  5610. \code{void} which corresponds to \code{unit} or \code{()} in the
  5611. literature~\citep{Pierce:2002hj}.}.
  5612. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5613. copying live objects back and forth between two halves of the
  5614. heap. The garbage collector requires coordination with the compiler so
  5615. that it can see all of the \emph{root} pointers, that is, pointers in
  5616. registers or on the procedure call stack.
  5617. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5618. discuss all the necessary changes and additions to the compiler
  5619. passes, including a new compiler pass named \code{expose-allocation}.
  5620. \section{The \LangVec{} Language}
  5621. \label{sec:r3}
  5622. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5623. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5624. \LangVec{} language includes three new forms: \code{vector} for creating a
  5625. tuple, \code{vector-ref} for reading an element of a tuple, and
  5626. \code{vector-set!} for writing to an element of a tuple. The program
  5627. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5628. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5629. the 3-tuple, demonstrating that tuples are first-class values. The
  5630. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5631. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5632. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5633. 1-tuple. So the result of the program is \code{42}.
  5634. \begin{figure}[tbp]
  5635. \centering
  5636. \fbox{
  5637. \begin{minipage}{0.96\textwidth}
  5638. \[
  5639. \begin{array}{lcl}
  5640. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5641. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5642. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5643. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5644. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5645. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5646. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5647. \mid \LP\key{not}\;\Exp\RP } \\
  5648. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5649. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5650. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5651. \mid \LP\key{vector-length}\;\Exp\RP \\
  5652. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5653. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5654. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5655. \LangVec{} &::=& \Exp
  5656. \end{array}
  5657. \]
  5658. \end{minipage}
  5659. }
  5660. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5661. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5662. \label{fig:Rvec-concrete-syntax}
  5663. \end{figure}
  5664. \begin{figure}[tbp]
  5665. \begin{lstlisting}
  5666. (let ([t (vector 40 #t (vector 2))])
  5667. (if (vector-ref t 1)
  5668. (+ (vector-ref t 0)
  5669. (vector-ref (vector-ref t 2) 0))
  5670. 44))
  5671. \end{lstlisting}
  5672. \caption{Example program that creates tuples and reads from them.}
  5673. \label{fig:vector-eg}
  5674. \end{figure}
  5675. \begin{figure}[tp]
  5676. \centering
  5677. \fbox{
  5678. \begin{minipage}{0.96\textwidth}
  5679. \[
  5680. \begin{array}{lcl}
  5681. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5682. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5683. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5684. \mid \BOOL{\itm{bool}}
  5685. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5686. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5687. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5688. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5689. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5690. \end{array}
  5691. \]
  5692. \end{minipage}
  5693. }
  5694. \caption{The abstract syntax of \LangVec{}.}
  5695. \label{fig:Rvec-syntax}
  5696. \end{figure}
  5697. \index{allocate}
  5698. \index{heap allocate}
  5699. Tuples are our first encounter with heap-allocated data, which raises
  5700. several interesting issues. First, variable binding performs a
  5701. shallow-copy when dealing with tuples, which means that different
  5702. variables can refer to the same tuple, that is, different variables
  5703. can be \emph{aliases} for the same entity. Consider the following
  5704. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5705. Thus, the mutation through \code{t2} is visible when referencing the
  5706. tuple from \code{t1}, so the result of this program is \code{42}.
  5707. \index{alias}\index{mutation}
  5708. \begin{center}
  5709. \begin{minipage}{0.96\textwidth}
  5710. \begin{lstlisting}
  5711. (let ([t1 (vector 3 7)])
  5712. (let ([t2 t1])
  5713. (let ([_ (vector-set! t2 0 42)])
  5714. (vector-ref t1 0))))
  5715. \end{lstlisting}
  5716. \end{minipage}
  5717. \end{center}
  5718. The next issue concerns the lifetime of tuples. Of course, they are
  5719. created by the \code{vector} form, but when does their lifetime end?
  5720. Notice that \LangVec{} does not include an operation for deleting
  5721. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5722. of static scoping. For example, the following program returns
  5723. \code{42} even though the variable \code{w} goes out of scope prior to
  5724. the \code{vector-ref} that reads from the vector it was bound to.
  5725. \begin{center}
  5726. \begin{minipage}{0.96\textwidth}
  5727. \begin{lstlisting}
  5728. (let ([v (vector (vector 44))])
  5729. (let ([x (let ([w (vector 42)])
  5730. (let ([_ (vector-set! v 0 w)])
  5731. 0))])
  5732. (+ x (vector-ref (vector-ref v 0) 0))))
  5733. \end{lstlisting}
  5734. \end{minipage}
  5735. \end{center}
  5736. From the perspective of programmer-observable behavior, tuples live
  5737. forever. Of course, if they really lived forever, then many programs
  5738. would run out of memory.\footnote{The \LangVec{} language does not have
  5739. looping or recursive functions, so it is nigh impossible to write a
  5740. program in \LangVec{} that will run out of memory. However, we add
  5741. recursive functions in the next Chapter!} A Racket implementation
  5742. must therefore perform automatic garbage collection.
  5743. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5744. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5745. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5746. terms of the corresponding operations in Racket. One subtle point is
  5747. that the \code{vector-set!} operation returns the \code{\#<void>}
  5748. value. The \code{\#<void>} value can be passed around just like other
  5749. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5750. compared for equality with another \code{\#<void>} value. However,
  5751. there are no other operations specific to the the \code{\#<void>}
  5752. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5753. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5754. otherwise.
  5755. \begin{figure}[tbp]
  5756. \begin{lstlisting}
  5757. (define interp-Rvec-class
  5758. (class interp-Rif-class
  5759. (super-new)
  5760. (define/override (interp-op op)
  5761. (match op
  5762. ['eq? (lambda (v1 v2)
  5763. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5764. (and (boolean? v1) (boolean? v2))
  5765. (and (vector? v1) (vector? v2))
  5766. (and (void? v1) (void? v2)))
  5767. (eq? v1 v2)]))]
  5768. ['vector vector]
  5769. ['vector-length vector-length]
  5770. ['vector-ref vector-ref]
  5771. ['vector-set! vector-set!]
  5772. [else (super interp-op op)]
  5773. ))
  5774. (define/override ((interp-exp env) e)
  5775. (define recur (interp-exp env))
  5776. (match e
  5777. [(HasType e t) (recur e)]
  5778. [(Void) (void)]
  5779. [else ((super interp-exp env) e)]
  5780. ))
  5781. ))
  5782. (define (interp-Rvec p)
  5783. (send (new interp-Rvec-class) interp-program p))
  5784. \end{lstlisting}
  5785. \caption{Interpreter for the \LangVec{} language.}
  5786. \label{fig:interp-Rvec}
  5787. \end{figure}
  5788. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5789. deserves some explanation. When allocating a vector, we need to know
  5790. which elements of the vector are pointers (i.e. are also vectors). We
  5791. can obtain this information during type checking. The type checker in
  5792. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5793. expression, it also wraps every \key{vector} creation with the form
  5794. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5795. %
  5796. To create the s-expression for the \code{Vector} type in
  5797. Figure~\ref{fig:type-check-Rvec}, we use the
  5798. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5799. operator} \code{,@} to insert the list \code{t*} without its usual
  5800. start and end parentheses. \index{unquote-slicing}
  5801. \begin{figure}[tp]
  5802. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5803. (define type-check-Rvec-class
  5804. (class type-check-Rif-class
  5805. (super-new)
  5806. (inherit check-type-equal?)
  5807. (define/override (type-check-exp env)
  5808. (lambda (e)
  5809. (define recur (type-check-exp env))
  5810. (match e
  5811. [(Void) (values (Void) 'Void)]
  5812. [(Prim 'vector es)
  5813. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5814. (define t `(Vector ,@t*))
  5815. (values (HasType (Prim 'vector e*) t) t)]
  5816. [(Prim 'vector-ref (list e1 (Int i)))
  5817. (define-values (e1^ t) (recur e1))
  5818. (match t
  5819. [`(Vector ,ts ...)
  5820. (unless (and (0 . <= . i) (i . < . (length ts)))
  5821. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5822. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5823. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5824. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5825. (define-values (e-vec t-vec) (recur e1))
  5826. (define-values (e-arg^ t-arg) (recur arg))
  5827. (match t-vec
  5828. [`(Vector ,ts ...)
  5829. (unless (and (0 . <= . i) (i . < . (length ts)))
  5830. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5831. (check-type-equal? (list-ref ts i) t-arg e)
  5832. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5833. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5834. [(Prim 'vector-length (list e))
  5835. (define-values (e^ t) (recur e))
  5836. (match t
  5837. [`(Vector ,ts ...)
  5838. (values (Prim 'vector-length (list e^)) 'Integer)]
  5839. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5840. [(Prim 'eq? (list arg1 arg2))
  5841. (define-values (e1 t1) (recur arg1))
  5842. (define-values (e2 t2) (recur arg2))
  5843. (match* (t1 t2)
  5844. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5845. [(other wise) (check-type-equal? t1 t2 e)])
  5846. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5847. [(HasType (Prim 'vector es) t)
  5848. ((type-check-exp env) (Prim 'vector es))]
  5849. [(HasType e1 t)
  5850. (define-values (e1^ t^) (recur e1))
  5851. (check-type-equal? t t^ e)
  5852. (values (HasType e1^ t) t)]
  5853. [else ((super type-check-exp env) e)]
  5854. )))
  5855. ))
  5856. (define (type-check-Rvec p)
  5857. (send (new type-check-Rvec-class) type-check-program p))
  5858. \end{lstlisting}
  5859. \caption{Type checker for the \LangVec{} language.}
  5860. \label{fig:type-check-Rvec}
  5861. \end{figure}
  5862. \section{Garbage Collection}
  5863. \label{sec:GC}
  5864. Here we study a relatively simple algorithm for garbage collection
  5865. that is the basis of state-of-the-art garbage
  5866. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5867. particular, we describe a two-space copying
  5868. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5869. perform the
  5870. copy~\citep{Cheney:1970aa}.
  5871. \index{copying collector}
  5872. \index{two-space copying collector}
  5873. Figure~\ref{fig:copying-collector} gives a
  5874. coarse-grained depiction of what happens in a two-space collector,
  5875. showing two time steps, prior to garbage collection (on the top) and
  5876. after garbage collection (on the bottom). In a two-space collector,
  5877. the heap is divided into two parts named the FromSpace and the
  5878. ToSpace. Initially, all allocations go to the FromSpace until there is
  5879. not enough room for the next allocation request. At that point, the
  5880. garbage collector goes to work to make more room.
  5881. \index{ToSpace}
  5882. \index{FromSpace}
  5883. The garbage collector must be careful not to reclaim tuples that will
  5884. be used by the program in the future. Of course, it is impossible in
  5885. general to predict what a program will do, but we can over approximate
  5886. the will-be-used tuples by preserving all tuples that could be
  5887. accessed by \emph{any} program given the current computer state. A
  5888. program could access any tuple whose address is in a register or on
  5889. the procedure call stack. These addresses are called the \emph{root
  5890. set}\index{root set}. In addition, a program could access any tuple that is
  5891. transitively reachable from the root set. Thus, it is safe for the
  5892. garbage collector to reclaim the tuples that are not reachable in this
  5893. way.
  5894. So the goal of the garbage collector is twofold:
  5895. \begin{enumerate}
  5896. \item preserve all tuple that are reachable from the root set via a
  5897. path of pointers, that is, the \emph{live} tuples, and
  5898. \item reclaim the memory of everything else, that is, the
  5899. \emph{garbage}.
  5900. \end{enumerate}
  5901. A copying collector accomplishes this by copying all of the live
  5902. objects from the FromSpace into the ToSpace and then performs a sleight
  5903. of hand, treating the ToSpace as the new FromSpace and the old
  5904. FromSpace as the new ToSpace. In the example of
  5905. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5906. root set, one in a register and two on the stack. All of the live
  5907. objects have been copied to the ToSpace (the right-hand side of
  5908. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5909. pointer relationships. For example, the pointer in the register still
  5910. points to a 2-tuple whose first element is a 3-tuple and whose second
  5911. element is a 2-tuple. There are four tuples that are not reachable
  5912. from the root set and therefore do not get copied into the ToSpace.
  5913. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5914. created by a well-typed program in \LangVec{} because it contains a
  5915. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5916. We design the garbage collector to deal with cycles to begin with so
  5917. we will not need to revisit this issue.
  5918. \begin{figure}[tbp]
  5919. \centering
  5920. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5921. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5922. \caption{A copying collector in action.}
  5923. \label{fig:copying-collector}
  5924. \end{figure}
  5925. There are many alternatives to copying collectors (and their bigger
  5926. siblings, the generational collectors) when its comes to garbage
  5927. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5928. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5929. collectors are that allocation is fast (just a comparison and pointer
  5930. increment), there is no fragmentation, cyclic garbage is collected,
  5931. and the time complexity of collection only depends on the amount of
  5932. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5933. main disadvantages of a two-space copying collector is that it uses a
  5934. lot of space and takes a long time to perform the copy, though these
  5935. problems are ameliorated in generational collectors. Racket and
  5936. Scheme programs tend to allocate many small objects and generate a lot
  5937. of garbage, so copying and generational collectors are a good fit.
  5938. Garbage collection is an active research topic, especially concurrent
  5939. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5940. developing new techniques and revisiting old
  5941. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5942. meet every year at the International Symposium on Memory Management to
  5943. present these findings.
  5944. \subsection{Graph Copying via Cheney's Algorithm}
  5945. \label{sec:cheney}
  5946. \index{Cheney's algorithm}
  5947. Let us take a closer look at the copying of the live objects. The
  5948. allocated objects and pointers can be viewed as a graph and we need to
  5949. copy the part of the graph that is reachable from the root set. To
  5950. make sure we copy all of the reachable vertices in the graph, we need
  5951. an exhaustive graph traversal algorithm, such as depth-first search or
  5952. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5953. such algorithms take into account the possibility of cycles by marking
  5954. which vertices have already been visited, so as to ensure termination
  5955. of the algorithm. These search algorithms also use a data structure
  5956. such as a stack or queue as a to-do list to keep track of the vertices
  5957. that need to be visited. We use breadth-first search and a trick
  5958. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5959. and copying tuples into the ToSpace.
  5960. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5961. copy progresses. The queue is represented by a chunk of contiguous
  5962. memory at the beginning of the ToSpace, using two pointers to track
  5963. the front and the back of the queue. The algorithm starts by copying
  5964. all tuples that are immediately reachable from the root set into the
  5965. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5966. old tuple to indicate that it has been visited. We discuss how this
  5967. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5968. pointers inside the copied tuples in the queue still point back to the
  5969. FromSpace. Once the initial queue has been created, the algorithm
  5970. enters a loop in which it repeatedly processes the tuple at the front
  5971. of the queue and pops it off the queue. To process a tuple, the
  5972. algorithm copies all the tuple that are directly reachable from it to
  5973. the ToSpace, placing them at the back of the queue. The algorithm then
  5974. updates the pointers in the popped tuple so they point to the newly
  5975. copied tuples.
  5976. \begin{figure}[tbp]
  5977. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5978. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5979. \label{fig:cheney}
  5980. \end{figure}
  5981. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5982. tuple whose second element is $42$ to the back of the queue. The other
  5983. pointer goes to a tuple that has already been copied, so we do not
  5984. need to copy it again, but we do need to update the pointer to the new
  5985. location. This can be accomplished by storing a \emph{forwarding
  5986. pointer} to the new location in the old tuple, back when we initially
  5987. copied the tuple into the ToSpace. This completes one step of the
  5988. algorithm. The algorithm continues in this way until the front of the
  5989. queue is empty, that is, until the front catches up with the back.
  5990. \subsection{Data Representation}
  5991. \label{sec:data-rep-gc}
  5992. The garbage collector places some requirements on the data
  5993. representations used by our compiler. First, the garbage collector
  5994. needs to distinguish between pointers and other kinds of data. There
  5995. are several ways to accomplish this.
  5996. \begin{enumerate}
  5997. \item Attached a tag to each object that identifies what type of
  5998. object it is~\citep{McCarthy:1960dz}.
  5999. \item Store different types of objects in different
  6000. regions~\citep{Steele:1977ab}.
  6001. \item Use type information from the program to either generate
  6002. type-specific code for collecting or to generate tables that can
  6003. guide the
  6004. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6005. \end{enumerate}
  6006. Dynamically typed languages, such as Lisp, need to tag objects
  6007. anyways, so option 1 is a natural choice for those languages.
  6008. However, \LangVec{} is a statically typed language, so it would be
  6009. unfortunate to require tags on every object, especially small and
  6010. pervasive objects like integers and Booleans. Option 3 is the
  6011. best-performing choice for statically typed languages, but comes with
  6012. a relatively high implementation complexity. To keep this chapter
  6013. within a 2-week time budget, we recommend a combination of options 1
  6014. and 2, using separate strategies for the stack and the heap.
  6015. Regarding the stack, we recommend using a separate stack for pointers,
  6016. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6017. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6018. is, when a local variable needs to be spilled and is of type
  6019. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6020. stack instead of the normal procedure call stack. Furthermore, we
  6021. always spill vector-typed variables if they are live during a call to
  6022. the collector, thereby ensuring that no pointers are in registers
  6023. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6024. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6025. the data layout using a root stack. The root stack contains the two
  6026. pointers from the regular stack and also the pointer in the second
  6027. register.
  6028. \begin{figure}[tbp]
  6029. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6030. \caption{Maintaining a root stack to facilitate garbage collection.}
  6031. \label{fig:shadow-stack}
  6032. \end{figure}
  6033. The problem of distinguishing between pointers and other kinds of data
  6034. also arises inside of each tuple on the heap. We solve this problem by
  6035. attaching a tag, an extra 64-bits, to each
  6036. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6037. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6038. that we have drawn the bits in a big-endian way, from right-to-left,
  6039. with bit location 0 (the least significant bit) on the far right,
  6040. which corresponds to the direction of the x86 shifting instructions
  6041. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6042. is dedicated to specifying which elements of the tuple are pointers,
  6043. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6044. indicates there is a pointer and a 0 bit indicates some other kind of
  6045. data. The pointer mask starts at bit location 7. We have limited
  6046. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6047. the pointer mask. The tag also contains two other pieces of
  6048. information. The length of the tuple (number of elements) is stored in
  6049. bits location 1 through 6. Finally, the bit at location 0 indicates
  6050. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6051. value 1, then this tuple has not yet been copied. If the bit has
  6052. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6053. of a pointer are always zero anyways because our tuples are 8-byte
  6054. aligned.)
  6055. \begin{figure}[tbp]
  6056. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6057. \caption{Representation of tuples in the heap.}
  6058. \label{fig:tuple-rep}
  6059. \end{figure}
  6060. \subsection{Implementation of the Garbage Collector}
  6061. \label{sec:organize-gz}
  6062. \index{prelude}
  6063. An implementation of the copying collector is provided in the
  6064. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6065. interface to the garbage collector that is used by the compiler. The
  6066. \code{initialize} function creates the FromSpace, ToSpace, and root
  6067. stack and should be called in the prelude of the \code{main}
  6068. function. The arguments of \code{initialize} are the root stack size
  6069. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6070. good choice for both. The \code{initialize} function puts the address
  6071. of the beginning of the FromSpace into the global variable
  6072. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6073. the address that is 1-past the last element of the FromSpace. (We use
  6074. half-open intervals to represent chunks of
  6075. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6076. points to the first element of the root stack.
  6077. As long as there is room left in the FromSpace, your generated code
  6078. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6079. %
  6080. The amount of room left in FromSpace is the difference between the
  6081. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6082. function should be called when there is not enough room left in the
  6083. FromSpace for the next allocation. The \code{collect} function takes
  6084. a pointer to the current top of the root stack (one past the last item
  6085. that was pushed) and the number of bytes that need to be
  6086. allocated. The \code{collect} function performs the copying collection
  6087. and leaves the heap in a state such that the next allocation will
  6088. succeed.
  6089. \begin{figure}[tbp]
  6090. \begin{lstlisting}
  6091. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6092. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6093. int64_t* free_ptr;
  6094. int64_t* fromspace_begin;
  6095. int64_t* fromspace_end;
  6096. int64_t** rootstack_begin;
  6097. \end{lstlisting}
  6098. \caption{The compiler's interface to the garbage collector.}
  6099. \label{fig:gc-header}
  6100. \end{figure}
  6101. %% \begin{exercise}
  6102. %% In the file \code{runtime.c} you will find the implementation of
  6103. %% \code{initialize} and a partial implementation of \code{collect}.
  6104. %% The \code{collect} function calls another function, \code{cheney},
  6105. %% to perform the actual copy, and that function is left to the reader
  6106. %% to implement. The following is the prototype for \code{cheney}.
  6107. %% \begin{lstlisting}
  6108. %% static void cheney(int64_t** rootstack_ptr);
  6109. %% \end{lstlisting}
  6110. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6111. %% rootstack (which is an array of pointers). The \code{cheney} function
  6112. %% also communicates with \code{collect} through the global
  6113. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6114. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6115. %% the ToSpace:
  6116. %% \begin{lstlisting}
  6117. %% static int64_t* tospace_begin;
  6118. %% static int64_t* tospace_end;
  6119. %% \end{lstlisting}
  6120. %% The job of the \code{cheney} function is to copy all the live
  6121. %% objects (reachable from the root stack) into the ToSpace, update
  6122. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6123. %% update the root stack so that it points to the objects in the
  6124. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6125. %% and ToSpace.
  6126. %% \end{exercise}
  6127. %% \section{Compiler Passes}
  6128. %% \label{sec:code-generation-gc}
  6129. The introduction of garbage collection has a non-trivial impact on our
  6130. compiler passes. We introduce a new compiler pass named
  6131. \code{expose-allocation}. We make
  6132. significant changes to \code{select-instructions},
  6133. \code{build-interference}, \code{allocate-registers}, and
  6134. \code{print-x86} and make minor changes in several more passes. The
  6135. following program will serve as our running example. It creates two
  6136. tuples, one nested inside the other. Both tuples have length one. The
  6137. program accesses the element in the inner tuple tuple via two vector
  6138. references.
  6139. % tests/s2_17.rkt
  6140. \begin{lstlisting}
  6141. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6142. \end{lstlisting}
  6143. \section{Shrink}
  6144. \label{sec:shrink-Rvec}
  6145. Recall that the \code{shrink} pass translates the primitives operators
  6146. into a smaller set of primitives. Because this pass comes after type
  6147. checking, but before the passes that require the type information in
  6148. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6149. to wrap \code{HasType} around each AST node that it generates.
  6150. \section{Expose Allocation}
  6151. \label{sec:expose-allocation}
  6152. The pass \code{expose-allocation} lowers the \code{vector} creation
  6153. form into a conditional call to the collector followed by the
  6154. allocation. We choose to place the \code{expose-allocation} pass
  6155. before \code{remove-complex-opera*} because the code generated by
  6156. \code{expose-allocation} contains complex operands. We also place
  6157. \code{expose-allocation} before \code{explicate-control} because
  6158. \code{expose-allocation} introduces new variables using \code{let},
  6159. but \code{let} is gone after \code{explicate-control}.
  6160. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6161. extends \LangVec{} with the three new forms that we use in the translation
  6162. of the \code{vector} form.
  6163. \[
  6164. \begin{array}{lcl}
  6165. \Exp &::=& \cdots
  6166. \mid (\key{collect} \,\itm{int})
  6167. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6168. \mid (\key{global-value} \,\itm{name})
  6169. \end{array}
  6170. \]
  6171. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6172. $n$ bytes. It will become a call to the \code{collect} function in
  6173. \code{runtime.c} in \code{select-instructions}. The
  6174. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6175. \index{allocate}
  6176. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6177. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6178. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6179. a global variable, such as \code{free\_ptr}.
  6180. In the following, we show the transformation for the \code{vector}
  6181. form into 1) a sequence of let-bindings for the initializing
  6182. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6183. \code{allocate}, and 4) the initialization of the vector. In the
  6184. following, \itm{len} refers to the length of the vector and
  6185. \itm{bytes} is how many total bytes need to be allocated for the
  6186. vector, which is 8 for the tag plus \itm{len} times 8.
  6187. \begin{lstlisting}
  6188. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6189. |$\Longrightarrow$|
  6190. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6191. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6192. (global-value fromspace_end))
  6193. (void)
  6194. (collect |\itm{bytes}|))])
  6195. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6196. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6197. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6198. |$v$|) ... )))) ...)
  6199. \end{lstlisting}
  6200. In the above, we suppressed all of the \code{has-type} forms in the
  6201. output for the sake of readability. The placement of the initializing
  6202. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6203. sequence of \code{vector-set!} is important, as those expressions may
  6204. trigger garbage collection and we cannot have an allocated but
  6205. uninitialized tuple on the heap during a collection.
  6206. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6207. \code{expose-allocation} pass on our running example.
  6208. \begin{figure}[tbp]
  6209. % tests/s2_17.rkt
  6210. \begin{lstlisting}
  6211. (vector-ref
  6212. (vector-ref
  6213. (let ([vecinit7976
  6214. (let ([vecinit7972 42])
  6215. (let ([collectret7974
  6216. (if (< (+ (global-value free_ptr) 16)
  6217. (global-value fromspace_end))
  6218. (void)
  6219. (collect 16)
  6220. )])
  6221. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6222. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6223. alloc7971)
  6224. )
  6225. )
  6226. )
  6227. ])
  6228. (let ([collectret7978
  6229. (if (< (+ (global-value free_ptr) 16)
  6230. (global-value fromspace_end))
  6231. (void)
  6232. (collect 16)
  6233. )])
  6234. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6235. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6236. alloc7975)
  6237. )
  6238. )
  6239. )
  6240. 0)
  6241. 0)
  6242. \end{lstlisting}
  6243. \caption{Output of the \code{expose-allocation} pass, minus
  6244. all of the \code{has-type} forms.}
  6245. \label{fig:expose-alloc-output}
  6246. \end{figure}
  6247. \section{Remove Complex Operands}
  6248. \label{sec:remove-complex-opera-Rvec}
  6249. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6250. should all be treated as complex operands.
  6251. %% A new case for
  6252. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6253. %% handled carefully to prevent the \code{Prim} node from being separated
  6254. %% from its enclosing \code{HasType}.
  6255. Figure~\ref{fig:Rvec-anf-syntax}
  6256. shows the grammar for the output language \LangVecANF{} of this
  6257. pass, which is \LangVec{} in administrative normal form.
  6258. \begin{figure}[tp]
  6259. \centering
  6260. \fbox{
  6261. \begin{minipage}{0.96\textwidth}
  6262. \small
  6263. \[
  6264. \begin{array}{rcl}
  6265. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6266. \mid \VOID{} \\
  6267. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6268. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6269. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6270. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6271. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6272. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6273. \mid \LP\key{GlobalValue}~\Var\RP\\
  6274. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6275. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6276. \end{array}
  6277. \]
  6278. \end{minipage}
  6279. }
  6280. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6281. \label{fig:Rvec-anf-syntax}
  6282. \end{figure}
  6283. \section{Explicate Control and the \LangCVec{} language}
  6284. \label{sec:explicate-control-r3}
  6285. \begin{figure}[tp]
  6286. \fbox{
  6287. \begin{minipage}{0.96\textwidth}
  6288. \small
  6289. \[
  6290. \begin{array}{lcl}
  6291. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6292. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6293. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6294. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6295. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6296. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6297. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6298. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6299. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6300. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6301. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6302. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6303. \mid \GOTO{\itm{label}} } \\
  6304. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6305. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6306. \end{array}
  6307. \]
  6308. \end{minipage}
  6309. }
  6310. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6311. (Figure~\ref{fig:c1-syntax}).}
  6312. \label{fig:c2-syntax}
  6313. \end{figure}
  6314. The output of \code{explicate-control} is a program in the
  6315. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6316. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6317. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6318. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6319. \key{vector-set!}, and \key{global-value} expressions and the
  6320. \code{collect} statement. The \code{explicate-control} pass can treat
  6321. these new forms much like the other expression forms that we've
  6322. already encoutered.
  6323. \section{Select Instructions and the \LangXGlobal{} Language}
  6324. \label{sec:select-instructions-gc}
  6325. \index{instruction selection}
  6326. %% void (rep as zero)
  6327. %% allocate
  6328. %% collect (callq collect)
  6329. %% vector-ref
  6330. %% vector-set!
  6331. %% global (postpone)
  6332. In this pass we generate x86 code for most of the new operations that
  6333. were needed to compile tuples, including \code{Allocate},
  6334. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6335. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6336. the later has a different concrete syntax (see
  6337. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6338. \index{x86}
  6339. The \code{vector-ref} and \code{vector-set!} forms translate into
  6340. \code{movq} instructions. (The plus one in the offset is to get past
  6341. the tag at the beginning of the tuple representation.)
  6342. \begin{lstlisting}
  6343. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6344. |$\Longrightarrow$|
  6345. movq |$\itm{vec}'$|, %r11
  6346. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6347. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6348. |$\Longrightarrow$|
  6349. movq |$\itm{vec}'$|, %r11
  6350. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6351. movq $0, |$\itm{lhs'}$|
  6352. \end{lstlisting}
  6353. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6354. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6355. register \code{r11} ensures that offset expression
  6356. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6357. removing \code{r11} from consideration by the register allocating.
  6358. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6359. \code{rax}. Then the generated code for \code{vector-set!} would be
  6360. \begin{lstlisting}
  6361. movq |$\itm{vec}'$|, %rax
  6362. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6363. movq $0, |$\itm{lhs}'$|
  6364. \end{lstlisting}
  6365. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6366. \code{patch-instructions} would insert a move through \code{rax}
  6367. as follows.
  6368. \begin{lstlisting}
  6369. movq |$\itm{vec}'$|, %rax
  6370. movq |$\itm{arg}'$|, %rax
  6371. movq %rax, |$8(n+1)$|(%rax)
  6372. movq $0, |$\itm{lhs}'$|
  6373. \end{lstlisting}
  6374. But the above sequence of instructions does not work because we're
  6375. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6376. $\itm{arg}'$) at the same time!
  6377. We compile the \code{allocate} form to operations on the
  6378. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6379. is the next free address in the FromSpace, so we copy it into
  6380. \code{r11} and then move it forward by enough space for the tuple
  6381. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6382. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6383. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6384. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6385. tag is organized. We recommend using the Racket operations
  6386. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6387. during compilation. The type annotation in the \code{vector} form is
  6388. used to determine the pointer mask region of the tag.
  6389. \begin{lstlisting}
  6390. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6391. |$\Longrightarrow$|
  6392. movq free_ptr(%rip), %r11
  6393. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6394. movq $|$\itm{tag}$|, 0(%r11)
  6395. movq %r11, |$\itm{lhs}'$|
  6396. \end{lstlisting}
  6397. The \code{collect} form is compiled to a call to the \code{collect}
  6398. function in the runtime. The arguments to \code{collect} are 1) the
  6399. top of the root stack and 2) the number of bytes that need to be
  6400. allocated. We use another dedicated register, \code{r15}, to
  6401. store the pointer to the top of the root stack. So \code{r15} is not
  6402. available for use by the register allocator.
  6403. \begin{lstlisting}
  6404. (collect |$\itm{bytes}$|)
  6405. |$\Longrightarrow$|
  6406. movq %r15, %rdi
  6407. movq $|\itm{bytes}|, %rsi
  6408. callq collect
  6409. \end{lstlisting}
  6410. \begin{figure}[tp]
  6411. \fbox{
  6412. \begin{minipage}{0.96\textwidth}
  6413. \[
  6414. \begin{array}{lcl}
  6415. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6416. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6417. & & \gray{ \key{main:} \; \Instr\ldots }
  6418. \end{array}
  6419. \]
  6420. \end{minipage}
  6421. }
  6422. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6423. \label{fig:x86-2-concrete}
  6424. \end{figure}
  6425. \begin{figure}[tp]
  6426. \fbox{
  6427. \begin{minipage}{0.96\textwidth}
  6428. \small
  6429. \[
  6430. \begin{array}{lcl}
  6431. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6432. \mid \BYTEREG{\Reg}} \\
  6433. &\mid& (\key{Global}~\Var) \\
  6434. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6435. \end{array}
  6436. \]
  6437. \end{minipage}
  6438. }
  6439. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6440. \label{fig:x86-2}
  6441. \end{figure}
  6442. The concrete and abstract syntax of the \LangXGlobal{} language is
  6443. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6444. differs from \LangXIf{} just in the addition of the form for global
  6445. variables.
  6446. %
  6447. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6448. \code{select-instructions} pass on the running example.
  6449. \begin{figure}[tbp]
  6450. \centering
  6451. % tests/s2_17.rkt
  6452. \begin{minipage}[t]{0.5\textwidth}
  6453. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6454. block35:
  6455. movq free_ptr(%rip), alloc9024
  6456. addq $16, free_ptr(%rip)
  6457. movq alloc9024, %r11
  6458. movq $131, 0(%r11)
  6459. movq alloc9024, %r11
  6460. movq vecinit9025, 8(%r11)
  6461. movq $0, initret9026
  6462. movq alloc9024, %r11
  6463. movq 8(%r11), tmp9034
  6464. movq tmp9034, %r11
  6465. movq 8(%r11), %rax
  6466. jmp conclusion
  6467. block36:
  6468. movq $0, collectret9027
  6469. jmp block35
  6470. block38:
  6471. movq free_ptr(%rip), alloc9020
  6472. addq $16, free_ptr(%rip)
  6473. movq alloc9020, %r11
  6474. movq $3, 0(%r11)
  6475. movq alloc9020, %r11
  6476. movq vecinit9021, 8(%r11)
  6477. movq $0, initret9022
  6478. movq alloc9020, vecinit9025
  6479. movq free_ptr(%rip), tmp9031
  6480. movq tmp9031, tmp9032
  6481. addq $16, tmp9032
  6482. movq fromspace_end(%rip), tmp9033
  6483. cmpq tmp9033, tmp9032
  6484. jl block36
  6485. jmp block37
  6486. block37:
  6487. movq %r15, %rdi
  6488. movq $16, %rsi
  6489. callq 'collect
  6490. jmp block35
  6491. block39:
  6492. movq $0, collectret9023
  6493. jmp block38
  6494. \end{lstlisting}
  6495. \end{minipage}
  6496. \begin{minipage}[t]{0.45\textwidth}
  6497. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6498. start:
  6499. movq $42, vecinit9021
  6500. movq free_ptr(%rip), tmp9028
  6501. movq tmp9028, tmp9029
  6502. addq $16, tmp9029
  6503. movq fromspace_end(%rip), tmp9030
  6504. cmpq tmp9030, tmp9029
  6505. jl block39
  6506. jmp block40
  6507. block40:
  6508. movq %r15, %rdi
  6509. movq $16, %rsi
  6510. callq 'collect
  6511. jmp block38
  6512. \end{lstlisting}
  6513. \end{minipage}
  6514. \caption{Output of the \code{select-instructions} pass.}
  6515. \label{fig:select-instr-output-gc}
  6516. \end{figure}
  6517. \clearpage
  6518. \section{Register Allocation}
  6519. \label{sec:reg-alloc-gc}
  6520. \index{register allocation}
  6521. As discussed earlier in this chapter, the garbage collector needs to
  6522. access all the pointers in the root set, that is, all variables that
  6523. are vectors. It will be the responsibility of the register allocator
  6524. to make sure that:
  6525. \begin{enumerate}
  6526. \item the root stack is used for spilling vector-typed variables, and
  6527. \item if a vector-typed variable is live during a call to the
  6528. collector, it must be spilled to ensure it is visible to the
  6529. collector.
  6530. \end{enumerate}
  6531. The later responsibility can be handled during construction of the
  6532. interference graph, by adding interference edges between the call-live
  6533. vector-typed variables and all the callee-saved registers. (They
  6534. already interfere with the caller-saved registers.) The type
  6535. information for variables is in the \code{Program} form, so we
  6536. recommend adding another parameter to the \code{build-interference}
  6537. function to communicate this alist.
  6538. The spilling of vector-typed variables to the root stack can be
  6539. handled after graph coloring, when choosing how to assign the colors
  6540. (integers) to registers and stack locations. The \code{Program} output
  6541. of this pass changes to also record the number of spills to the root
  6542. stack.
  6543. % build-interference
  6544. %
  6545. % callq
  6546. % extra parameter for var->type assoc. list
  6547. % update 'program' and 'if'
  6548. % allocate-registers
  6549. % allocate spilled vectors to the rootstack
  6550. % don't change color-graph
  6551. \section{Print x86}
  6552. \label{sec:print-x86-gc}
  6553. \index{prelude}\index{conclusion}
  6554. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6555. \code{print-x86} pass on the running example. In the prelude and
  6556. conclusion of the \code{main} function, we treat the root stack very
  6557. much like the regular stack in that we move the root stack pointer
  6558. (\code{r15}) to make room for the spills to the root stack, except
  6559. that the root stack grows up instead of down. For the running
  6560. example, there was just one spill so we increment \code{r15} by 8
  6561. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6562. One issue that deserves special care is that there may be a call to
  6563. \code{collect} prior to the initializing assignments for all the
  6564. variables in the root stack. We do not want the garbage collector to
  6565. accidentally think that some uninitialized variable is a pointer that
  6566. needs to be followed. Thus, we zero-out all locations on the root
  6567. stack in the prelude of \code{main}. In
  6568. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6569. %
  6570. \lstinline{movq $0, (%r15)}
  6571. %
  6572. accomplishes this task. The garbage collector tests each root to see
  6573. if it is null prior to dereferencing it.
  6574. \begin{figure}[htbp]
  6575. \begin{minipage}[t]{0.5\textwidth}
  6576. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6577. block35:
  6578. movq free_ptr(%rip), %rcx
  6579. addq $16, free_ptr(%rip)
  6580. movq %rcx, %r11
  6581. movq $131, 0(%r11)
  6582. movq %rcx, %r11
  6583. movq -8(%r15), %rax
  6584. movq %rax, 8(%r11)
  6585. movq $0, %rdx
  6586. movq %rcx, %r11
  6587. movq 8(%r11), %rcx
  6588. movq %rcx, %r11
  6589. movq 8(%r11), %rax
  6590. jmp conclusion
  6591. block36:
  6592. movq $0, %rcx
  6593. jmp block35
  6594. block38:
  6595. movq free_ptr(%rip), %rcx
  6596. addq $16, free_ptr(%rip)
  6597. movq %rcx, %r11
  6598. movq $3, 0(%r11)
  6599. movq %rcx, %r11
  6600. movq %rbx, 8(%r11)
  6601. movq $0, %rdx
  6602. movq %rcx, -8(%r15)
  6603. movq free_ptr(%rip), %rcx
  6604. addq $16, %rcx
  6605. movq fromspace_end(%rip), %rdx
  6606. cmpq %rdx, %rcx
  6607. jl block36
  6608. movq %r15, %rdi
  6609. movq $16, %rsi
  6610. callq collect
  6611. jmp block35
  6612. block39:
  6613. movq $0, %rcx
  6614. jmp block38
  6615. \end{lstlisting}
  6616. \end{minipage}
  6617. \begin{minipage}[t]{0.45\textwidth}
  6618. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6619. start:
  6620. movq $42, %rbx
  6621. movq free_ptr(%rip), %rdx
  6622. addq $16, %rdx
  6623. movq fromspace_end(%rip), %rcx
  6624. cmpq %rcx, %rdx
  6625. jl block39
  6626. movq %r15, %rdi
  6627. movq $16, %rsi
  6628. callq collect
  6629. jmp block38
  6630. .globl main
  6631. main:
  6632. pushq %rbp
  6633. movq %rsp, %rbp
  6634. pushq %r13
  6635. pushq %r12
  6636. pushq %rbx
  6637. pushq %r14
  6638. subq $0, %rsp
  6639. movq $16384, %rdi
  6640. movq $16384, %rsi
  6641. callq initialize
  6642. movq rootstack_begin(%rip), %r15
  6643. movq $0, (%r15)
  6644. addq $8, %r15
  6645. jmp start
  6646. conclusion:
  6647. subq $8, %r15
  6648. addq $0, %rsp
  6649. popq %r14
  6650. popq %rbx
  6651. popq %r12
  6652. popq %r13
  6653. popq %rbp
  6654. retq
  6655. \end{lstlisting}
  6656. \end{minipage}
  6657. \caption{Output of the \code{print-x86} pass.}
  6658. \label{fig:print-x86-output-gc}
  6659. \end{figure}
  6660. \begin{figure}[p]
  6661. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6662. \node (Rvec) at (0,2) {\large \LangVec{}};
  6663. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6664. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6665. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6666. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6667. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6668. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6669. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6670. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6671. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6672. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6673. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6674. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6675. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6676. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6677. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6678. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6679. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6680. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6681. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6682. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6683. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6684. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6685. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6686. \end{tikzpicture}
  6687. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6688. \label{fig:Rvec-passes}
  6689. \end{figure}
  6690. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6691. for the compilation of \LangVec{}.
  6692. \section{Challenge: Simple Structures}
  6693. \label{sec:simple-structures}
  6694. \index{struct}
  6695. \index{structure}
  6696. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6697. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6698. Recall that a \code{struct} in Typed Racket is a user-defined data
  6699. type that contains named fields and that is heap allocated, similar to
  6700. a vector. The following is an example of a structure definition, in
  6701. this case the definition of a \code{point} type.
  6702. \begin{lstlisting}
  6703. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6704. \end{lstlisting}
  6705. \begin{figure}[tbp]
  6706. \centering
  6707. \fbox{
  6708. \begin{minipage}{0.96\textwidth}
  6709. \[
  6710. \begin{array}{lcl}
  6711. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6712. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6713. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6714. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6715. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6716. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6717. \mid (\key{and}\;\Exp\;\Exp)
  6718. \mid (\key{or}\;\Exp\;\Exp)
  6719. \mid (\key{not}\;\Exp) } \\
  6720. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6721. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6722. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6723. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6724. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6725. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6726. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6727. \LangStruct{} &::=& \Def \ldots \; \Exp
  6728. \end{array}
  6729. \]
  6730. \end{minipage}
  6731. }
  6732. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6733. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6734. \label{fig:r3s-concrete-syntax}
  6735. \end{figure}
  6736. An instance of a structure is created using function call syntax, with
  6737. the name of the structure in the function position:
  6738. \begin{lstlisting}
  6739. (point 7 12)
  6740. \end{lstlisting}
  6741. Function-call syntax is also used to read the value in a field of a
  6742. structure. The function name is formed by the structure name, a dash,
  6743. and the field name. The following example uses \code{point-x} and
  6744. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6745. instances.
  6746. \begin{center}
  6747. \begin{lstlisting}
  6748. (let ([pt1 (point 7 12)])
  6749. (let ([pt2 (point 4 3)])
  6750. (+ (- (point-x pt1) (point-x pt2))
  6751. (- (point-y pt1) (point-y pt2)))))
  6752. \end{lstlisting}
  6753. \end{center}
  6754. Similarly, to write to a field of a structure, use its set function,
  6755. whose name starts with \code{set-}, followed by the structure name,
  6756. then a dash, then the field name, and concluded with an exclamation
  6757. mark. The following example uses \code{set-point-x!} to change the
  6758. \code{x} field from \code{7} to \code{42}.
  6759. \begin{center}
  6760. \begin{lstlisting}
  6761. (let ([pt (point 7 12)])
  6762. (let ([_ (set-point-x! pt 42)])
  6763. (point-x pt)))
  6764. \end{lstlisting}
  6765. \end{center}
  6766. \begin{exercise}\normalfont
  6767. Extend your compiler with support for simple structures, compiling
  6768. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6769. structures and test your compiler.
  6770. \end{exercise}
  6771. \section{Challenge: Generational Collection}
  6772. The copying collector described in Section~\ref{sec:GC} can incur
  6773. significant runtime overhead because the call to \code{collect} takes
  6774. time proportional to all of the live data. One way to reduce this
  6775. overhead is to reduce how much data is inspected in each call to
  6776. \code{collect}. In particular, researchers have observed that recently
  6777. allocated data is more likely to become garbage then data that has
  6778. survived one or more previous calls to \code{collect}. This insight
  6779. motivated the creation of \emph{generational garbage collectors}
  6780. \index{generational garbage collector} that
  6781. 1) segregates data according to its age into two or more generations,
  6782. 2) allocates less space for younger generations, so collecting them is
  6783. faster, and more space for the older generations, and 3) performs
  6784. collection on the younger generations more frequently then for older
  6785. generations~\citep{Wilson:1992fk}.
  6786. For this challenge assignment, the goal is to adapt the copying
  6787. collector implemented in \code{runtime.c} to use two generations, one
  6788. for young data and one for old data. Each generation consists of a
  6789. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6790. \code{collect} function to use the two generations.
  6791. \begin{enumerate}
  6792. \item Copy the young generation's FromSpace to its ToSpace then switch
  6793. the role of the ToSpace and FromSpace
  6794. \item If there is enough space for the requested number of bytes in
  6795. the young FromSpace, then return from \code{collect}.
  6796. \item If there is not enough space in the young FromSpace for the
  6797. requested bytes, then move the data from the young generation to the
  6798. old one with the following steps:
  6799. \begin{enumerate}
  6800. \item If there is enough room in the old FromSpace, copy the young
  6801. FromSpace to the old FromSpace and then return.
  6802. \item If there is not enough room in the old FromSpace, then collect
  6803. the old generation by copying the old FromSpace to the old ToSpace
  6804. and swap the roles of the old FromSpace and ToSpace.
  6805. \item If there is enough room now, copy the young FromSpace to the
  6806. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6807. and ToSpace for the old generation. Copy the young FromSpace and
  6808. the old FromSpace into the larger FromSpace for the old
  6809. generation and then return.
  6810. \end{enumerate}
  6811. \end{enumerate}
  6812. We recommend that you generalize the \code{cheney} function so that it
  6813. can be used for all the copies mentioned above: between the young
  6814. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6815. between the young FromSpace and old FromSpace. This can be
  6816. accomplished by adding parameters to \code{cheney} that replace its
  6817. use of the global variables \code{fromspace\_begin},
  6818. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6819. Note that the collection of the young generation does not traverse the
  6820. old generation. This introduces a potential problem: there may be
  6821. young data that is only reachable through pointers in the old
  6822. generation. If these pointers are not taken into account, the
  6823. collector could throw away young data that is live! One solution,
  6824. called \emph{pointer recording}, is to maintain a set of all the
  6825. pointers from the old generation into the new generation and consider
  6826. this set as part of the root set. To maintain this set, the compiler
  6827. must insert extra instructions around every \code{vector-set!}. If the
  6828. vector being modified is in the old generation, and if the value being
  6829. written is a pointer into the new generation, than that pointer must
  6830. be added to the set. Also, if the value being overwritten was a
  6831. pointer into the new generation, then that pointer should be removed
  6832. from the set.
  6833. \begin{exercise}\normalfont
  6834. Adapt the \code{collect} function in \code{runtime.c} to implement
  6835. generational garbage collection, as outlined in this section.
  6836. Update the code generation for \code{vector-set!} to implement
  6837. pointer recording. Make sure that your new compiler and runtime
  6838. passes your test suite.
  6839. \end{exercise}
  6840. % Further Reading
  6841. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6842. \chapter{Functions}
  6843. \label{ch:Rfun}
  6844. \index{function}
  6845. This chapter studies the compilation of functions similar to those
  6846. found in the C language. This corresponds to a subset of Typed Racket
  6847. in which only top-level function definitions are allowed. This kind of
  6848. function is an important stepping stone to implementing
  6849. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6850. is the topic of Chapter~\ref{ch:Rlam}.
  6851. \section{The \LangFun{} Language}
  6852. The concrete and abstract syntax for function definitions and function
  6853. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6854. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6855. \LangFun{} begin with zero or more function definitions. The function
  6856. names from these definitions are in-scope for the entire program,
  6857. including all other function definitions (so the ordering of function
  6858. definitions does not matter). The concrete syntax for function
  6859. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6860. where the first expression must
  6861. evaluate to a function and the rest are the arguments.
  6862. The abstract syntax for function application is
  6863. $\APPLY{\Exp}{\Exp\ldots}$.
  6864. %% The syntax for function application does not include an explicit
  6865. %% keyword, which is error prone when using \code{match}. To alleviate
  6866. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6867. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6868. Functions are first-class in the sense that a function pointer
  6869. \index{function pointer} is data and can be stored in memory or passed
  6870. as a parameter to another function. Thus, we introduce a function
  6871. type, written
  6872. \begin{lstlisting}
  6873. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6874. \end{lstlisting}
  6875. for a function whose $n$ parameters have the types $\Type_1$ through
  6876. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6877. these functions (with respect to Racket functions) is that they are
  6878. not lexically scoped. That is, the only external entities that can be
  6879. referenced from inside a function body are other globally-defined
  6880. functions. The syntax of \LangFun{} prevents functions from being nested
  6881. inside each other.
  6882. \begin{figure}[tp]
  6883. \centering
  6884. \fbox{
  6885. \begin{minipage}{0.96\textwidth}
  6886. \small
  6887. \[
  6888. \begin{array}{lcl}
  6889. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6890. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6891. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6892. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6893. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6894. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6895. \mid (\key{and}\;\Exp\;\Exp)
  6896. \mid (\key{or}\;\Exp\;\Exp)
  6897. \mid (\key{not}\;\Exp)} \\
  6898. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6899. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6900. (\key{vector-ref}\;\Exp\;\Int)} \\
  6901. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6902. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6903. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6904. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6905. \LangFun{} &::=& \Def \ldots \; \Exp
  6906. \end{array}
  6907. \]
  6908. \end{minipage}
  6909. }
  6910. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6911. \label{fig:Rfun-concrete-syntax}
  6912. \end{figure}
  6913. \begin{figure}[tp]
  6914. \centering
  6915. \fbox{
  6916. \begin{minipage}{0.96\textwidth}
  6917. \small
  6918. \[
  6919. \begin{array}{lcl}
  6920. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6921. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6922. &\mid& \gray{ \BOOL{\itm{bool}}
  6923. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6924. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6925. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6926. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6927. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6928. \end{array}
  6929. \]
  6930. \end{minipage}
  6931. }
  6932. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6933. \label{fig:Rfun-syntax}
  6934. \end{figure}
  6935. The program in Figure~\ref{fig:Rfun-function-example} is a
  6936. representative example of defining and using functions in \LangFun{}. We
  6937. define a function \code{map-vec} that applies some other function
  6938. \code{f} to both elements of a vector and returns a new
  6939. vector containing the results. We also define a function \code{add1}.
  6940. The program applies
  6941. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6942. \code{(vector 1 42)}, from which we return the \code{42}.
  6943. \begin{figure}[tbp]
  6944. \begin{lstlisting}
  6945. (define (map-vec [f : (Integer -> Integer)]
  6946. [v : (Vector Integer Integer)])
  6947. : (Vector Integer Integer)
  6948. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6949. (define (add1 [x : Integer]) : Integer
  6950. (+ x 1))
  6951. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6952. \end{lstlisting}
  6953. \caption{Example of using functions in \LangFun{}.}
  6954. \label{fig:Rfun-function-example}
  6955. \end{figure}
  6956. The definitional interpreter for \LangFun{} is in
  6957. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6958. responsible for setting up the mutual recursion between the top-level
  6959. function definitions. We use the classic back-patching \index{back-patching}
  6960. approach that uses mutable variables and makes two passes over the function
  6961. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6962. top-level environment using a mutable cons cell for each function
  6963. definition. Note that the \code{lambda} value for each function is
  6964. incomplete; it does not yet include the environment. Once the
  6965. top-level environment is constructed, we then iterate over it and
  6966. update the \code{lambda} values to use the top-level environment.
  6967. \begin{figure}[tp]
  6968. \begin{lstlisting}
  6969. (define interp-Rfun-class
  6970. (class interp-Rvec-class
  6971. (super-new)
  6972. (define/override ((interp-exp env) e)
  6973. (define recur (interp-exp env))
  6974. (match e
  6975. [(Var x) (unbox (dict-ref env x))]
  6976. [(Let x e body)
  6977. (define new-env (dict-set env x (box (recur e))))
  6978. ((interp-exp new-env) body)]
  6979. [(Apply fun args)
  6980. (define fun-val (recur fun))
  6981. (define arg-vals (for/list ([e args]) (recur e)))
  6982. (match fun-val
  6983. [`(function (,xs ...) ,body ,fun-env)
  6984. (define params-args (for/list ([x xs] [arg arg-vals])
  6985. (cons x (box arg))))
  6986. (define new-env (append params-args fun-env))
  6987. ((interp-exp new-env) body)]
  6988. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6989. [else ((super interp-exp env) e)]
  6990. ))
  6991. (define/public (interp-def d)
  6992. (match d
  6993. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6994. (cons f (box `(function ,xs ,body ())))]))
  6995. (define/override (interp-program p)
  6996. (match p
  6997. [(ProgramDefsExp info ds body)
  6998. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6999. (for/list ([f (in-dict-values top-level)])
  7000. (set-box! f (match (unbox f)
  7001. [`(function ,xs ,body ())
  7002. `(function ,xs ,body ,top-level)])))
  7003. ((interp-exp top-level) body))]))
  7004. ))
  7005. (define (interp-Rfun p)
  7006. (send (new interp-Rfun-class) interp-program p))
  7007. \end{lstlisting}
  7008. \caption{Interpreter for the \LangFun{} language.}
  7009. \label{fig:interp-Rfun}
  7010. \end{figure}
  7011. \margincomment{TODO: explain type checker}
  7012. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  7013. \begin{figure}[tp]
  7014. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7015. (define type-check-Rfun-class
  7016. (class type-check-Rvec-class
  7017. (super-new)
  7018. (inherit check-type-equal?)
  7019. (define/public (type-check-apply env e es)
  7020. (define-values (e^ ty) ((type-check-exp env) e))
  7021. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7022. ((type-check-exp env) e)))
  7023. (match ty
  7024. [`(,ty^* ... -> ,rt)
  7025. (for ([arg-ty ty*] [param-ty ty^*])
  7026. (check-type-equal? arg-ty param-ty (Apply e es)))
  7027. (values e^ e* rt)]))
  7028. (define/override (type-check-exp env)
  7029. (lambda (e)
  7030. (match e
  7031. [(FunRef f)
  7032. (values (FunRef f) (dict-ref env f))]
  7033. [(Apply e es)
  7034. (define-values (e^ es^ rt) (type-check-apply env e es))
  7035. (values (Apply e^ es^) rt)]
  7036. [(Call e es)
  7037. (define-values (e^ es^ rt) (type-check-apply env e es))
  7038. (values (Call e^ es^) rt)]
  7039. [else ((super type-check-exp env) e)])))
  7040. (define/public (type-check-def env)
  7041. (lambda (e)
  7042. (match e
  7043. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7044. (define new-env (append (map cons xs ps) env))
  7045. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7046. (check-type-equal? ty^ rt body)
  7047. (Def f p:t* rt info body^)])))
  7048. (define/public (fun-def-type d)
  7049. (match d
  7050. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7051. (define/override (type-check-program e)
  7052. (match e
  7053. [(ProgramDefsExp info ds body)
  7054. (define new-env (for/list ([d ds])
  7055. (cons (Def-name d) (fun-def-type d))))
  7056. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7057. (define-values (body^ ty) ((type-check-exp new-env) body))
  7058. (check-type-equal? ty 'Integer body)
  7059. (ProgramDefsExp info ds^ body^)]))))
  7060. (define (type-check-Rfun p)
  7061. (send (new type-check-Rfun-class) type-check-program p))
  7062. \end{lstlisting}
  7063. \caption{Type checker for the \LangFun{} language.}
  7064. \label{fig:type-check-Rfun}
  7065. \end{figure}
  7066. \section{Functions in x86}
  7067. \label{sec:fun-x86}
  7068. \margincomment{\tiny Make sure callee-saved registers are discussed
  7069. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7070. \margincomment{\tiny Talk about the return address on the
  7071. stack and what callq and retq does.\\ --Jeremy }
  7072. The x86 architecture provides a few features to support the
  7073. implementation of functions. We have already seen that x86 provides
  7074. labels so that one can refer to the location of an instruction, as is
  7075. needed for jump instructions. Labels can also be used to mark the
  7076. beginning of the instructions for a function. Going further, we can
  7077. obtain the address of a label by using the \key{leaq} instruction and
  7078. PC-relative addressing. For example, the following puts the
  7079. address of the \code{add1} label into the \code{rbx} register.
  7080. \begin{lstlisting}
  7081. leaq add1(%rip), %rbx
  7082. \end{lstlisting}
  7083. The instruction pointer register \key{rip} (aka. the program counter
  7084. \index{program counter}) always points to the next instruction to be
  7085. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7086. linker computes the distance $d$ between the address of \code{add1}
  7087. and where the \code{rip} would be at that moment and then changes
  7088. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7089. the address of \code{add1}.
  7090. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7091. jump to a function whose location is given by a label. To support
  7092. function calls in this chapter we instead will be jumping to a
  7093. function whose location is given by an address in a register, that is,
  7094. we need to make an \emph{indirect function call}. The x86 syntax for
  7095. this is a \code{callq} instruction but with an asterisk before the
  7096. register name.\index{indirect function call}
  7097. \begin{lstlisting}
  7098. callq *%rbx
  7099. \end{lstlisting}
  7100. \subsection{Calling Conventions}
  7101. \index{calling conventions}
  7102. The \code{callq} instruction provides partial support for implementing
  7103. functions: it pushes the return address on the stack and it jumps to
  7104. the target. However, \code{callq} does not handle
  7105. \begin{enumerate}
  7106. \item parameter passing,
  7107. \item pushing frames on the procedure call stack and popping them off,
  7108. or
  7109. \item determining how registers are shared by different functions.
  7110. \end{enumerate}
  7111. Regarding (1) parameter passing, recall that the following six
  7112. registers are used to pass arguments to a function, in this order.
  7113. \begin{lstlisting}
  7114. rdi rsi rdx rcx r8 r9
  7115. \end{lstlisting}
  7116. If there are
  7117. more than six arguments, then the convention is to use space on the
  7118. frame of the caller for the rest of the arguments. However, to ease
  7119. the implementation of efficient tail calls
  7120. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7121. arguments.
  7122. %
  7123. Also recall that the register \code{rax} is for the return value of
  7124. the function.
  7125. \index{prelude}\index{conclusion}
  7126. Regarding (2) frames \index{frame} and the procedure call stack,
  7127. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7128. the stack grows down, with each function call using a chunk of space
  7129. called a frame. The caller sets the stack pointer, register
  7130. \code{rsp}, to the last data item in its frame. The callee must not
  7131. change anything in the caller's frame, that is, anything that is at or
  7132. above the stack pointer. The callee is free to use locations that are
  7133. below the stack pointer.
  7134. Recall that we are storing variables of vector type on the root stack.
  7135. So the prelude needs to move the root stack pointer \code{r15} up and
  7136. the conclusion needs to move the root stack pointer back down. Also,
  7137. the prelude must initialize to \code{0} this frame's slots in the root
  7138. stack to signal to the garbage collector that those slots do not yet
  7139. contain a pointer to a vector. Otherwise the garbage collector will
  7140. interpret the garbage bits in those slots as memory addresses and try
  7141. to traverse them, causing serious mayhem!
  7142. Regarding (3) the sharing of registers between different functions,
  7143. recall from Section~\ref{sec:calling-conventions} that the registers
  7144. are divided into two groups, the caller-saved registers and the
  7145. callee-saved registers. The caller should assume that all the
  7146. caller-saved registers get overwritten with arbitrary values by the
  7147. callee. That is why we recommend in
  7148. Section~\ref{sec:calling-conventions} that variables that are live
  7149. during a function call should not be assigned to caller-saved
  7150. registers.
  7151. On the flip side, if the callee wants to use a callee-saved register,
  7152. the callee must save the contents of those registers on their stack
  7153. frame and then put them back prior to returning to the caller. That
  7154. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7155. the register allocator assigns a variable to a callee-saved register,
  7156. then the prelude of the \code{main} function must save that register
  7157. to the stack and the conclusion of \code{main} must restore it. This
  7158. recommendation now generalizes to all functions.
  7159. Also recall that the base pointer, register \code{rbp}, is used as a
  7160. point-of-reference within a frame, so that each local variable can be
  7161. accessed at a fixed offset from the base pointer
  7162. (Section~\ref{sec:x86}).
  7163. %
  7164. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7165. and callee frames.
  7166. \begin{figure}[tbp]
  7167. \centering
  7168. \begin{tabular}{r|r|l|l} \hline
  7169. Caller View & Callee View & Contents & Frame \\ \hline
  7170. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7171. 0(\key{\%rbp}) & & old \key{rbp} \\
  7172. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7173. \ldots & & \ldots \\
  7174. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7175. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7176. \ldots & & \ldots \\
  7177. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7178. %% & & \\
  7179. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7180. %% & \ldots & \ldots \\
  7181. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7182. \hline
  7183. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7184. & 0(\key{\%rbp}) & old \key{rbp} \\
  7185. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7186. & \ldots & \ldots \\
  7187. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7188. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7189. & \ldots & \ldots \\
  7190. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7191. \end{tabular}
  7192. \caption{Memory layout of caller and callee frames.}
  7193. \label{fig:call-frames}
  7194. \end{figure}
  7195. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7196. %% local variables and for storing the values of callee-saved registers
  7197. %% (we shall refer to all of these collectively as ``locals''), and that
  7198. %% at the beginning of a function we move the stack pointer \code{rsp}
  7199. %% down to make room for them.
  7200. %% We recommend storing the local variables
  7201. %% first and then the callee-saved registers, so that the local variables
  7202. %% can be accessed using \code{rbp} the same as before the addition of
  7203. %% functions.
  7204. %% To make additional room for passing arguments, we shall
  7205. %% move the stack pointer even further down. We count how many stack
  7206. %% arguments are needed for each function call that occurs inside the
  7207. %% body of the function and find their maximum. Adding this number to the
  7208. %% number of locals gives us how much the \code{rsp} should be moved at
  7209. %% the beginning of the function. In preparation for a function call, we
  7210. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7211. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7212. %% so on.
  7213. %% Upon calling the function, the stack arguments are retrieved by the
  7214. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7215. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7216. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7217. %% the layout of the caller and callee frames. Notice how important it is
  7218. %% that we correctly compute the maximum number of arguments needed for
  7219. %% function calls; if that number is too small then the arguments and
  7220. %% local variables will smash into each other!
  7221. \subsection{Efficient Tail Calls}
  7222. \label{sec:tail-call}
  7223. In general, the amount of stack space used by a program is determined
  7224. by the longest chain of nested function calls. That is, if function
  7225. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7226. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7227. $n$ can grow quite large in the case of recursive or mutually
  7228. recursive functions. However, in some cases we can arrange to use only
  7229. constant space, i.e. $O(1)$, instead of $O(n)$.
  7230. If a function call is the last action in a function body, then that
  7231. call is said to be a \emph{tail call}\index{tail call}.
  7232. For example, in the following
  7233. program, the recursive call to \code{tail-sum} is a tail call.
  7234. \begin{center}
  7235. \begin{lstlisting}
  7236. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7237. (if (eq? n 0)
  7238. r
  7239. (tail-sum (- n 1) (+ n r))))
  7240. (+ (tail-sum 5 0) 27)
  7241. \end{lstlisting}
  7242. \end{center}
  7243. At a tail call, the frame of the caller is no longer needed, so we
  7244. can pop the caller's frame before making the tail call. With this
  7245. approach, a recursive function that only makes tail calls will only
  7246. use $O(1)$ stack space. Functional languages like Racket typically
  7247. rely heavily on recursive functions, so they typically guarantee that
  7248. all tail calls will be optimized in this way.
  7249. \index{frame}
  7250. However, some care is needed with regards to argument passing in tail
  7251. calls. As mentioned above, for arguments beyond the sixth, the
  7252. convention is to use space in the caller's frame for passing
  7253. arguments. But for a tail call we pop the caller's frame and can no
  7254. longer use it. Another alternative is to use space in the callee's
  7255. frame for passing arguments. However, this option is also problematic
  7256. because the caller and callee's frame overlap in memory. As we begin
  7257. to copy the arguments from their sources in the caller's frame, the
  7258. target locations in the callee's frame might overlap with the sources
  7259. for later arguments! We solve this problem by not using the stack for
  7260. passing more than six arguments but instead using the heap, as we
  7261. describe in the Section~\ref{sec:limit-functions-r4}.
  7262. As mentioned above, for a tail call we pop the caller's frame prior to
  7263. making the tail call. The instructions for popping a frame are the
  7264. instructions that we usually place in the conclusion of a
  7265. function. Thus, we also need to place such code immediately before
  7266. each tail call. These instructions include restoring the callee-saved
  7267. registers, so it is good that the argument passing registers are all
  7268. caller-saved registers.
  7269. One last note regarding which instruction to use to make the tail
  7270. call. When the callee is finished, it should not return to the current
  7271. function, but it should return to the function that called the current
  7272. one. Thus, the return address that is already on the stack is the
  7273. right one, and we should not use \key{callq} to make the tail call, as
  7274. that would unnecessarily overwrite the return address. Instead we can
  7275. simply use the \key{jmp} instruction. Like the indirect function call,
  7276. we write an \emph{indirect jump}\index{indirect jump} with a register
  7277. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7278. jump target because the preceding conclusion overwrites just about
  7279. everything else.
  7280. \begin{lstlisting}
  7281. jmp *%rax
  7282. \end{lstlisting}
  7283. \section{Shrink \LangFun{}}
  7284. \label{sec:shrink-r4}
  7285. The \code{shrink} pass performs a minor modification to ease the
  7286. later passes. This pass introduces an explicit \code{main} function
  7287. and changes the top \code{ProgramDefsExp} form to
  7288. \code{ProgramDefs} as follows.
  7289. \begin{lstlisting}
  7290. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7291. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7292. \end{lstlisting}
  7293. where $\itm{mainDef}$ is
  7294. \begin{lstlisting}
  7295. (Def 'main '() 'Integer '() |$\Exp'$|)
  7296. \end{lstlisting}
  7297. \section{Reveal Functions and the \LangFunRef{} language}
  7298. \label{sec:reveal-functions-r4}
  7299. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7300. respect: it conflates the use of function names and local
  7301. variables. This is a problem because we need to compile the use of a
  7302. function name differently than the use of a local variable; we need to
  7303. use \code{leaq} to convert the function name (a label in x86) to an
  7304. address in a register. Thus, it is a good idea to create a new pass
  7305. that changes function references from just a symbol $f$ to
  7306. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7307. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7308. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7309. \begin{figure}[tp]
  7310. \centering
  7311. \fbox{
  7312. \begin{minipage}{0.96\textwidth}
  7313. \[
  7314. \begin{array}{lcl}
  7315. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7316. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7317. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7318. \end{array}
  7319. \]
  7320. \end{minipage}
  7321. }
  7322. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7323. (Figure~\ref{fig:Rfun-syntax}).}
  7324. \label{fig:f1-syntax}
  7325. \end{figure}
  7326. %% Distinguishing between calls in tail position and non-tail position
  7327. %% requires the pass to have some notion of context. We recommend using
  7328. %% two mutually recursive functions, one for processing expressions in
  7329. %% tail position and another for the rest.
  7330. Placing this pass after \code{uniquify} will make sure that there are
  7331. no local variables and functions that share the same name. On the
  7332. other hand, \code{reveal-functions} needs to come before the
  7333. \code{explicate-control} pass because that pass helps us compile
  7334. \code{FunRef} forms into assignment statements.
  7335. \section{Limit Functions}
  7336. \label{sec:limit-functions-r4}
  7337. Recall that we wish to limit the number of function parameters to six
  7338. so that we do not need to use the stack for argument passing, which
  7339. makes it easier to implement efficient tail calls. However, because
  7340. the input language \LangFun{} supports arbitrary numbers of function
  7341. arguments, we have some work to do!
  7342. This pass transforms functions and function calls that involve more
  7343. than six arguments to pass the first five arguments as usual, but it
  7344. packs the rest of the arguments into a vector and passes it as the
  7345. sixth argument.
  7346. Each function definition with too many parameters is transformed as
  7347. follows.
  7348. \begin{lstlisting}
  7349. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7350. |$\Rightarrow$|
  7351. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7352. \end{lstlisting}
  7353. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7354. the occurrences of the later parameters with vector references.
  7355. \begin{lstlisting}
  7356. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7357. \end{lstlisting}
  7358. For function calls with too many arguments, the \code{limit-functions}
  7359. pass transforms them in the following way.
  7360. \begin{tabular}{lll}
  7361. \begin{minipage}{0.2\textwidth}
  7362. \begin{lstlisting}
  7363. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7364. \end{lstlisting}
  7365. \end{minipage}
  7366. &
  7367. $\Rightarrow$
  7368. &
  7369. \begin{minipage}{0.4\textwidth}
  7370. \begin{lstlisting}
  7371. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7372. \end{lstlisting}
  7373. \end{minipage}
  7374. \end{tabular}
  7375. \section{Remove Complex Operands}
  7376. \label{sec:rco-r4}
  7377. The primary decisions to make for this pass is whether to classify
  7378. \code{FunRef} and \code{Apply} as either atomic or complex
  7379. expressions. Recall that a simple expression will eventually end up as
  7380. just an immediate argument of an x86 instruction. Function
  7381. application will be translated to a sequence of instructions, so
  7382. \code{Apply} must be classified as complex expression.
  7383. On the other hand, the arguments of \code{Apply} should be
  7384. atomic expressions.
  7385. %
  7386. Regarding \code{FunRef}, as discussed above, the function label needs
  7387. to be converted to an address using the \code{leaq} instruction. Thus,
  7388. even though \code{FunRef} seems rather simple, it needs to be
  7389. classified as a complex expression so that we generate an assignment
  7390. statement with a left-hand side that can serve as the target of the
  7391. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7392. output language \LangFunANF{} of this pass.
  7393. \begin{figure}[tp]
  7394. \centering
  7395. \fbox{
  7396. \begin{minipage}{0.96\textwidth}
  7397. \small
  7398. \[
  7399. \begin{array}{rcl}
  7400. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7401. \mid \VOID{} } \\
  7402. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7403. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7404. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7405. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7406. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7407. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7408. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7409. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7410. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7411. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7412. \end{array}
  7413. \]
  7414. \end{minipage}
  7415. }
  7416. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7417. \label{fig:Rfun-anf-syntax}
  7418. \end{figure}
  7419. \section{Explicate Control and the \LangCFun{} language}
  7420. \label{sec:explicate-control-r4}
  7421. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7422. output of \key{explicate-control}. (The concrete syntax is given in
  7423. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7424. functions for assignment and tail contexts should be updated with
  7425. cases for \code{Apply} and \code{FunRef} and the function for
  7426. predicate context should be updated for \code{Apply} but not
  7427. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7428. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7429. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7430. defining a new auxiliary function for processing function definitions.
  7431. This code is similar to the case for \code{Program} in \LangVec{}. The
  7432. top-level \code{explicate-control} function that handles the
  7433. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7434. all the function definitions.
  7435. \begin{figure}[tp]
  7436. \fbox{
  7437. \begin{minipage}{0.96\textwidth}
  7438. \small
  7439. \[
  7440. \begin{array}{lcl}
  7441. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7442. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7443. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7444. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7445. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7446. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7447. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7448. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7449. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7450. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7451. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7452. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7453. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7454. \mid \GOTO{\itm{label}} } \\
  7455. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7456. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7457. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7458. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7459. \end{array}
  7460. \]
  7461. \end{minipage}
  7462. }
  7463. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7464. \label{fig:c3-syntax}
  7465. \end{figure}
  7466. \section{Select Instructions and the \LangXIndCall{} Language}
  7467. \label{sec:select-r4}
  7468. \index{instruction selection}
  7469. The output of select instructions is a program in the \LangXIndCall{}
  7470. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7471. \index{x86}
  7472. \begin{figure}[tp]
  7473. \fbox{
  7474. \begin{minipage}{0.96\textwidth}
  7475. \small
  7476. \[
  7477. \begin{array}{lcl}
  7478. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7479. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7480. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7481. \Instr &::=& \ldots
  7482. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7483. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7484. \Block &::= & \Instr\ldots \\
  7485. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7486. \LangXIndCall{} &::= & \Def\ldots
  7487. \end{array}
  7488. \]
  7489. \end{minipage}
  7490. }
  7491. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7492. \label{fig:x86-3-concrete}
  7493. \end{figure}
  7494. \begin{figure}[tp]
  7495. \fbox{
  7496. \begin{minipage}{0.96\textwidth}
  7497. \small
  7498. \[
  7499. \begin{array}{lcl}
  7500. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7501. \mid \BYTEREG{\Reg} } \\
  7502. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7503. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7504. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7505. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7506. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7507. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7508. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7509. \end{array}
  7510. \]
  7511. \end{minipage}
  7512. }
  7513. \caption{The abstract syntax of \LangXIndCall{} (extends
  7514. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7515. \label{fig:x86-3}
  7516. \end{figure}
  7517. An assignment of a function reference to a variable becomes a
  7518. load-effective-address instruction as follows: \\
  7519. \begin{tabular}{lcl}
  7520. \begin{minipage}{0.35\textwidth}
  7521. \begin{lstlisting}
  7522. |$\itm{lhs}$| = (fun-ref |$f$|);
  7523. \end{lstlisting}
  7524. \end{minipage}
  7525. &
  7526. $\Rightarrow$\qquad\qquad
  7527. &
  7528. \begin{minipage}{0.3\textwidth}
  7529. \begin{lstlisting}
  7530. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7531. \end{lstlisting}
  7532. \end{minipage}
  7533. \end{tabular} \\
  7534. Regarding function definitions, we need to remove the parameters and
  7535. instead perform parameter passing using the conventions discussed in
  7536. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7537. registers. We recommend turning the parameters into local variables
  7538. and generating instructions at the beginning of the function to move
  7539. from the argument passing registers to these local variables.
  7540. \begin{lstlisting}
  7541. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7542. |$\Rightarrow$|
  7543. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7544. \end{lstlisting}
  7545. The $G'$ control-flow graph is the same as $G$ except that the
  7546. \code{start} block is modified to add the instructions for moving from
  7547. the argument registers to the parameter variables. So the \code{start}
  7548. block of $G$ shown on the left is changed to the code on the right.
  7549. \begin{center}
  7550. \begin{minipage}{0.3\textwidth}
  7551. \begin{lstlisting}
  7552. start:
  7553. |$\itm{instr}_1$|
  7554. |$\vdots$|
  7555. |$\itm{instr}_n$|
  7556. \end{lstlisting}
  7557. \end{minipage}
  7558. $\Rightarrow$
  7559. \begin{minipage}{0.3\textwidth}
  7560. \begin{lstlisting}
  7561. start:
  7562. movq %rdi, |$x_1$|
  7563. movq %rsi, |$x_2$|
  7564. |$\vdots$|
  7565. |$\itm{instr}_1$|
  7566. |$\vdots$|
  7567. |$\itm{instr}_n$|
  7568. \end{lstlisting}
  7569. \end{minipage}
  7570. \end{center}
  7571. By changing the parameters to local variables, we are giving the
  7572. register allocator control over which registers or stack locations to
  7573. use for them. If you implemented the move-biasing challenge
  7574. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7575. assign the parameter variables to the corresponding argument register,
  7576. in which case the \code{patch-instructions} pass will remove the
  7577. \code{movq} instruction. This happens in the example translation in
  7578. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7579. the \code{add} function.
  7580. %
  7581. Also, note that the register allocator will perform liveness analysis
  7582. on this sequence of move instructions and build the interference
  7583. graph. So, for example, $x_1$ will be marked as interfering with
  7584. \code{rsi} and that will prevent the assignment of $x_1$ to
  7585. \code{rsi}, which is good, because that would overwrite the argument
  7586. that needs to move into $x_2$.
  7587. Next, consider the compilation of function calls. In the mirror image
  7588. of handling the parameters of function definitions, the arguments need
  7589. to be moved to the argument passing registers. The function call
  7590. itself is performed with an indirect function call. The return value
  7591. from the function is stored in \code{rax}, so it needs to be moved
  7592. into the \itm{lhs}.
  7593. \begin{lstlisting}
  7594. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7595. |$\Rightarrow$|
  7596. movq |$\itm{arg}_1$|, %rdi
  7597. movq |$\itm{arg}_2$|, %rsi
  7598. |$\vdots$|
  7599. callq *|\itm{fun}|
  7600. movq %rax, |\itm{lhs}|
  7601. \end{lstlisting}
  7602. The \code{IndirectCallq} AST node includes an integer for the arity of
  7603. the function, i.e., the number of parameters. That information is
  7604. useful in the \code{uncover-live} pass for determining which
  7605. argument-passing registers are potentially read during the call.
  7606. For tail calls, the parameter passing is the same as non-tail calls:
  7607. generate instructions to move the arguments into to the argument
  7608. passing registers. After that we need to pop the frame from the
  7609. procedure call stack. However, we do not yet know how big the frame
  7610. is; that gets determined during register allocation. So instead of
  7611. generating those instructions here, we invent a new instruction that
  7612. means ``pop the frame and then do an indirect jump'', which we name
  7613. \code{TailJmp}. The abstract syntax for this instruction includes an
  7614. argument that specifies where to jump and an integer that represents
  7615. the arity of the function being called.
  7616. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7617. using the label \code{start} for the initial block of a program, and
  7618. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7619. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7620. can be compiled to an assignment to \code{rax} followed by a jump to
  7621. \code{conclusion}. With the addition of function definitions, we will
  7622. have a starting block and conclusion for each function, but their
  7623. labels need to be unique. We recommend prepending the function's name
  7624. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7625. labels. (Alternatively, one could \code{gensym} labels for the start
  7626. and conclusion and store them in the $\itm{info}$ field of the
  7627. function definition.)
  7628. \section{Register Allocation}
  7629. \label{sec:register-allocation-r4}
  7630. \subsection{Liveness Analysis}
  7631. \label{sec:liveness-analysis-r4}
  7632. \index{liveness analysis}
  7633. %% The rest of the passes need only minor modifications to handle the new
  7634. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7635. %% \code{leaq}.
  7636. The \code{IndirectCallq} instruction should be treated like
  7637. \code{Callq} regarding its written locations $W$, in that they should
  7638. include all the caller-saved registers. Recall that the reason for
  7639. that is to force call-live variables to be assigned to callee-saved
  7640. registers or to be spilled to the stack.
  7641. Regarding the set of read locations $R$ the arity field of
  7642. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7643. argument-passing registers should be considered as read by those
  7644. instructions.
  7645. \subsection{Build Interference Graph}
  7646. \label{sec:build-interference-r4}
  7647. With the addition of function definitions, we compute an interference
  7648. graph for each function (not just one for the whole program).
  7649. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7650. spill vector-typed variables that are live during a call to the
  7651. \code{collect}. With the addition of functions to our language, we
  7652. need to revisit this issue. Many functions perform allocation and
  7653. therefore have calls to the collector inside of them. Thus, we should
  7654. not only spill a vector-typed variable when it is live during a call
  7655. to \code{collect}, but we should spill the variable if it is live
  7656. during any function call. Thus, in the \code{build-interference} pass,
  7657. we recommend adding interference edges between call-live vector-typed
  7658. variables and the callee-saved registers (in addition to the usual
  7659. addition of edges between call-live variables and the caller-saved
  7660. registers).
  7661. \subsection{Allocate Registers}
  7662. The primary change to the \code{allocate-registers} pass is adding an
  7663. auxiliary function for handling definitions (the \Def{} non-terminal
  7664. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7665. logic is the same as described in
  7666. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7667. allocation is performed many times, once for each function definition,
  7668. instead of just once for the whole program.
  7669. \section{Patch Instructions}
  7670. In \code{patch-instructions}, you should deal with the x86
  7671. idiosyncrasy that the destination argument of \code{leaq} must be a
  7672. register. Additionally, you should ensure that the argument of
  7673. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7674. code generation more convenient, because we trample many registers
  7675. before the tail call (as explained in the next section).
  7676. \section{Print x86}
  7677. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7678. \code{IndirectCallq} are straightforward: output their concrete
  7679. syntax.
  7680. \begin{lstlisting}
  7681. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7682. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7683. \end{lstlisting}
  7684. The \code{TailJmp} node requires a bit work. A straightforward
  7685. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7686. before the jump we need to pop the current frame. This sequence of
  7687. instructions is the same as the code for the conclusion of a function,
  7688. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7689. Regarding function definitions, you will need to generate a prelude
  7690. and conclusion for each one. This code is similar to the prelude and
  7691. conclusion that you generated for the \code{main} function in
  7692. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7693. should carry out the following steps.
  7694. \begin{enumerate}
  7695. \item Start with \code{.global} and \code{.align} directives followed
  7696. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7697. example.)
  7698. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7699. pointer.
  7700. \item Push to the stack all of the callee-saved registers that were
  7701. used for register allocation.
  7702. \item Move the stack pointer \code{rsp} down by the size of the stack
  7703. frame for this function, which depends on the number of regular
  7704. spills. (Aligned to 16 bytes.)
  7705. \item Move the root stack pointer \code{r15} up by the size of the
  7706. root-stack frame for this function, which depends on the number of
  7707. spilled vectors. \label{root-stack-init}
  7708. \item Initialize to zero all of the entries in the root-stack frame.
  7709. \item Jump to the start block.
  7710. \end{enumerate}
  7711. The prelude of the \code{main} function has one additional task: call
  7712. the \code{initialize} function to set up the garbage collector and
  7713. move the value of the global \code{rootstack\_begin} in
  7714. \code{r15}. This should happen before step \ref{root-stack-init}
  7715. above, which depends on \code{r15}.
  7716. The conclusion of every function should do the following.
  7717. \begin{enumerate}
  7718. \item Move the stack pointer back up by the size of the stack frame
  7719. for this function.
  7720. \item Restore the callee-saved registers by popping them from the
  7721. stack.
  7722. \item Move the root stack pointer back down by the size of the
  7723. root-stack frame for this function.
  7724. \item Restore \code{rbp} by popping it from the stack.
  7725. \item Return to the caller with the \code{retq} instruction.
  7726. \end{enumerate}
  7727. \begin{exercise}\normalfont
  7728. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7729. Create 5 new programs that use functions, including examples that pass
  7730. functions and return functions from other functions, recursive
  7731. functions, functions that create vectors, and functions that make tail
  7732. calls. Test your compiler on these new programs and all of your
  7733. previously created test programs.
  7734. \end{exercise}
  7735. \begin{figure}[tbp]
  7736. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7737. \node (Rfun) at (0,2) {\large \LangFun{}};
  7738. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7739. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7740. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7741. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7742. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7743. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7744. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7745. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7746. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7747. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7748. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7749. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7750. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7751. \path[->,bend left=15] (Rfun) edge [above] node
  7752. {\ttfamily\footnotesize shrink} (Rfun-1);
  7753. \path[->,bend left=15] (Rfun-1) edge [above] node
  7754. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7755. \path[->,bend left=15] (Rfun-2) edge [right] node
  7756. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7757. \path[->,bend left=15] (F1-1) edge [below] node
  7758. {\ttfamily\footnotesize limit-functions} (F1-2);
  7759. \path[->,bend right=15] (F1-2) edge [above] node
  7760. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7761. \path[->,bend right=15] (F1-3) edge [above] node
  7762. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7763. \path[->,bend left=15] (F1-4) edge [right] node
  7764. {\ttfamily\footnotesize explicate-control} (C3-2);
  7765. \path[->,bend right=15] (C3-2) edge [left] node
  7766. {\ttfamily\footnotesize select-instr.} (x86-2);
  7767. \path[->,bend left=15] (x86-2) edge [left] node
  7768. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7769. \path[->,bend right=15] (x86-2-1) edge [below] node
  7770. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7771. \path[->,bend right=15] (x86-2-2) edge [left] node
  7772. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7773. \path[->,bend left=15] (x86-3) edge [above] node
  7774. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7775. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7776. \end{tikzpicture}
  7777. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7778. \label{fig:Rfun-passes}
  7779. \end{figure}
  7780. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7781. compiling \LangFun{} to x86.
  7782. \section{An Example Translation}
  7783. \label{sec:functions-example}
  7784. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7785. function in \LangFun{} to x86. The figure also includes the results of the
  7786. \code{explicate-control} and \code{select-instructions} passes.
  7787. \begin{figure}[htbp]
  7788. \begin{tabular}{ll}
  7789. \begin{minipage}{0.5\textwidth}
  7790. % s3_2.rkt
  7791. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7792. (define (add [x : Integer] [y : Integer])
  7793. : Integer
  7794. (+ x y))
  7795. (add 40 2)
  7796. \end{lstlisting}
  7797. $\Downarrow$
  7798. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7799. (define (add86 [x87 : Integer]
  7800. [y88 : Integer]) : Integer
  7801. add86start:
  7802. return (+ x87 y88);
  7803. )
  7804. (define (main) : Integer ()
  7805. mainstart:
  7806. tmp89 = (fun-ref add86);
  7807. (tail-call tmp89 40 2)
  7808. )
  7809. \end{lstlisting}
  7810. \end{minipage}
  7811. &
  7812. $\Rightarrow$
  7813. \begin{minipage}{0.5\textwidth}
  7814. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7815. (define (add86) : Integer
  7816. add86start:
  7817. movq %rdi, x87
  7818. movq %rsi, y88
  7819. movq x87, %rax
  7820. addq y88, %rax
  7821. jmp add11389conclusion
  7822. )
  7823. (define (main) : Integer
  7824. mainstart:
  7825. leaq (fun-ref add86), tmp89
  7826. movq $40, %rdi
  7827. movq $2, %rsi
  7828. tail-jmp tmp89
  7829. )
  7830. \end{lstlisting}
  7831. $\Downarrow$
  7832. \end{minipage}
  7833. \end{tabular}
  7834. \begin{tabular}{ll}
  7835. \begin{minipage}{0.3\textwidth}
  7836. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7837. .globl add86
  7838. .align 16
  7839. add86:
  7840. pushq %rbp
  7841. movq %rsp, %rbp
  7842. jmp add86start
  7843. add86start:
  7844. movq %rdi, %rax
  7845. addq %rsi, %rax
  7846. jmp add86conclusion
  7847. add86conclusion:
  7848. popq %rbp
  7849. retq
  7850. \end{lstlisting}
  7851. \end{minipage}
  7852. &
  7853. \begin{minipage}{0.5\textwidth}
  7854. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7855. .globl main
  7856. .align 16
  7857. main:
  7858. pushq %rbp
  7859. movq %rsp, %rbp
  7860. movq $16384, %rdi
  7861. movq $16384, %rsi
  7862. callq initialize
  7863. movq rootstack_begin(%rip), %r15
  7864. jmp mainstart
  7865. mainstart:
  7866. leaq add86(%rip), %rcx
  7867. movq $40, %rdi
  7868. movq $2, %rsi
  7869. movq %rcx, %rax
  7870. popq %rbp
  7871. jmp *%rax
  7872. mainconclusion:
  7873. popq %rbp
  7874. retq
  7875. \end{lstlisting}
  7876. \end{minipage}
  7877. \end{tabular}
  7878. \caption{Example compilation of a simple function to x86.}
  7879. \label{fig:add-fun}
  7880. \end{figure}
  7881. % Challenge idea: inlining! (simple version)
  7882. % Further Reading
  7883. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7884. \chapter{Lexically Scoped Functions}
  7885. \label{ch:Rlam}
  7886. \index{lambda}
  7887. \index{lexical scoping}
  7888. This chapter studies lexically scoped functions as they appear in
  7889. functional languages such as Racket. By lexical scoping we mean that a
  7890. function's body may refer to variables whose binding site is outside
  7891. of the function, in an enclosing scope.
  7892. %
  7893. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7894. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7895. \key{lambda} form. The body of the \key{lambda}, refers to three
  7896. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7897. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7898. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7899. parameter of function \code{f}. The \key{lambda} is returned from the
  7900. function \code{f}. The main expression of the program includes two
  7901. calls to \code{f} with different arguments for \code{x}, first
  7902. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7903. to variables \code{g} and \code{h}. Even though these two functions
  7904. were created by the same \code{lambda}, they are really different
  7905. functions because they use different values for \code{x}. Applying
  7906. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7907. \code{15} produces \code{22}. The result of this program is \code{42}.
  7908. \begin{figure}[btp]
  7909. % s4_6.rkt
  7910. \begin{lstlisting}
  7911. (define (f [x : Integer]) : (Integer -> Integer)
  7912. (let ([y 4])
  7913. (lambda: ([z : Integer]) : Integer
  7914. (+ x (+ y z)))))
  7915. (let ([g (f 5)])
  7916. (let ([h (f 3)])
  7917. (+ (g 11) (h 15))))
  7918. \end{lstlisting}
  7919. \caption{Example of a lexically scoped function.}
  7920. \label{fig:lexical-scoping}
  7921. \end{figure}
  7922. The approach that we take for implementing lexically scoped
  7923. functions is to compile them into top-level function definitions,
  7924. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7925. provide special treatment for variable occurrences such as \code{x}
  7926. and \code{y} in the body of the \code{lambda} of
  7927. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7928. refer to variables defined outside of it. To identify such variable
  7929. occurrences, we review the standard notion of free variable.
  7930. \begin{definition}
  7931. A variable is \emph{free in expression} $e$ if the variable occurs
  7932. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7933. variable}
  7934. \end{definition}
  7935. For example, in the expression \code{(+ x (+ y z))} the variables
  7936. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7937. only \code{x} and \code{y} are free in the following expression
  7938. because \code{z} is bound by the \code{lambda}.
  7939. \begin{lstlisting}
  7940. (lambda: ([z : Integer]) : Integer
  7941. (+ x (+ y z)))
  7942. \end{lstlisting}
  7943. So the free variables of a \code{lambda} are the ones that will need
  7944. special treatment. We need to arrange for some way to transport, at
  7945. runtime, the values of those variables from the point where the
  7946. \code{lambda} was created to the point where the \code{lambda} is
  7947. applied. An efficient solution to the problem, due to
  7948. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7949. free variables together with the function pointer for the lambda's
  7950. code, an arrangement called a \emph{flat closure} (which we shorten to
  7951. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7952. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7953. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7954. pointers. The function pointer resides at index $0$ and the
  7955. values for the free variables will fill in the rest of the vector.
  7956. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7957. how closures work. It's a three-step dance. The program first calls
  7958. function \code{f}, which creates a closure for the \code{lambda}. The
  7959. closure is a vector whose first element is a pointer to the top-level
  7960. function that we will generate for the \code{lambda}, the second
  7961. element is the value of \code{x}, which is \code{5}, and the third
  7962. element is \code{4}, the value of \code{y}. The closure does not
  7963. contain an element for \code{z} because \code{z} is not a free
  7964. variable of the \code{lambda}. Creating the closure is step 1 of the
  7965. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7966. shown in Figure~\ref{fig:closures}.
  7967. %
  7968. The second call to \code{f} creates another closure, this time with
  7969. \code{3} in the second slot (for \code{x}). This closure is also
  7970. returned from \code{f} but bound to \code{h}, which is also shown in
  7971. Figure~\ref{fig:closures}.
  7972. \begin{figure}[tbp]
  7973. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7974. \caption{Example closure representation for the \key{lambda}'s
  7975. in Figure~\ref{fig:lexical-scoping}.}
  7976. \label{fig:closures}
  7977. \end{figure}
  7978. Continuing with the example, consider the application of \code{g} to
  7979. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7980. obtain the function pointer in the first element of the closure and
  7981. call it, passing in the closure itself and then the regular arguments,
  7982. in this case \code{11}. This technique for applying a closure is step
  7983. 2 of the dance.
  7984. %
  7985. But doesn't this \code{lambda} only take 1 argument, for parameter
  7986. \code{z}? The third and final step of the dance is generating a
  7987. top-level function for a \code{lambda}. We add an additional
  7988. parameter for the closure and we insert a \code{let} at the beginning
  7989. of the function for each free variable, to bind those variables to the
  7990. appropriate elements from the closure parameter.
  7991. %
  7992. This three-step dance is known as \emph{closure conversion}. We
  7993. discuss the details of closure conversion in
  7994. Section~\ref{sec:closure-conversion} and the code generated from the
  7995. example in Section~\ref{sec:example-lambda}. But first we define the
  7996. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7997. \section{The \LangLam{} Language}
  7998. \label{sec:r5}
  7999. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8000. functions and lexical scoping, is defined in
  8001. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8002. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8003. syntax for function application.
  8004. \begin{figure}[tp]
  8005. \centering
  8006. \fbox{
  8007. \begin{minipage}{0.96\textwidth}
  8008. \small
  8009. \[
  8010. \begin{array}{lcl}
  8011. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  8012. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  8013. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  8014. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8015. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8016. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8017. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8018. \mid (\key{and}\;\Exp\;\Exp)
  8019. \mid (\key{or}\;\Exp\;\Exp)
  8020. \mid (\key{not}\;\Exp) } \\
  8021. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8022. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8023. (\key{vector-ref}\;\Exp\;\Int)} \\
  8024. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8025. \mid (\Exp \; \Exp\ldots) } \\
  8026. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8027. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8028. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8029. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8030. \end{array}
  8031. \]
  8032. \end{minipage}
  8033. }
  8034. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8035. with \key{lambda}.}
  8036. \label{fig:Rlam-concrete-syntax}
  8037. \end{figure}
  8038. \begin{figure}[tp]
  8039. \centering
  8040. \fbox{
  8041. \begin{minipage}{0.96\textwidth}
  8042. \small
  8043. \[
  8044. \begin{array}{lcl}
  8045. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8046. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8047. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8048. &\mid& \gray{ \BOOL{\itm{bool}}
  8049. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8050. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8051. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8052. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8053. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8054. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8055. \end{array}
  8056. \]
  8057. \end{minipage}
  8058. }
  8059. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8060. \label{fig:Rlam-syntax}
  8061. \end{figure}
  8062. \index{interpreter}
  8063. \label{sec:interp-Rlambda}
  8064. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8065. \LangLam{}. The case for \key{lambda} saves the current environment
  8066. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8067. the environment from the \key{lambda}, the \code{lam-env}, when
  8068. interpreting the body of the \key{lambda}. The \code{lam-env}
  8069. environment is extended with the mapping of parameters to argument
  8070. values.
  8071. \begin{figure}[tbp]
  8072. \begin{lstlisting}
  8073. (define interp-Rlambda-class
  8074. (class interp-Rfun-class
  8075. (super-new)
  8076. (define/override (interp-op op)
  8077. (match op
  8078. ['procedure-arity
  8079. (lambda (v)
  8080. (match v
  8081. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8082. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8083. [else (super interp-op op)]))
  8084. (define/override ((interp-exp env) e)
  8085. (define recur (interp-exp env))
  8086. (match e
  8087. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8088. `(function ,xs ,body ,env)]
  8089. [else ((super interp-exp env) e)]))
  8090. ))
  8091. (define (interp-Rlambda p)
  8092. (send (new interp-Rlambda-class) interp-program p))
  8093. \end{lstlisting}
  8094. \caption{Interpreter for \LangLam{}.}
  8095. \label{fig:interp-Rlambda}
  8096. \end{figure}
  8097. \label{sec:type-check-r5}
  8098. \index{type checking}
  8099. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8100. \key{lambda} form. The body of the \key{lambda} is checked in an
  8101. environment that includes the current environment (because it is
  8102. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8103. require the body's type to match the declared return type.
  8104. \begin{figure}[tbp]
  8105. \begin{lstlisting}
  8106. (define (type-check-Rlambda env)
  8107. (lambda (e)
  8108. (match e
  8109. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8110. (define-values (new-body bodyT)
  8111. ((type-check-exp (append (map cons xs Ts) env)) body))
  8112. (define ty `(,@Ts -> ,rT))
  8113. (cond
  8114. [(equal? rT bodyT)
  8115. (values (HasType (Lambda params rT new-body) ty) ty)]
  8116. [else
  8117. (error "mismatch in return type" bodyT rT)])]
  8118. ...
  8119. )))
  8120. \end{lstlisting}
  8121. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8122. \label{fig:type-check-Rlambda}
  8123. \end{figure}
  8124. \section{Reveal Functions and the $F_2$ language}
  8125. \label{sec:reveal-functions-r5}
  8126. To support the \code{procedure-arity} operator we need to communicate
  8127. the arity of a function to the point of closure creation. We can
  8128. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8129. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8130. output of this pass is the language $F_2$, whose syntax is defined in
  8131. Figure~\ref{fig:f2-syntax}.
  8132. \begin{figure}[tp]
  8133. \centering
  8134. \fbox{
  8135. \begin{minipage}{0.96\textwidth}
  8136. \[
  8137. \begin{array}{lcl}
  8138. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8139. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8140. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8141. \end{array}
  8142. \]
  8143. \end{minipage}
  8144. }
  8145. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8146. (Figure~\ref{fig:Rlam-syntax}).}
  8147. \label{fig:f2-syntax}
  8148. \end{figure}
  8149. \section{Closure Conversion}
  8150. \label{sec:closure-conversion}
  8151. \index{closure conversion}
  8152. The compiling of lexically-scoped functions into top-level function
  8153. definitions is accomplished in the pass \code{convert-to-closures}
  8154. that comes after \code{reveal-functions} and before
  8155. \code{limit-functions}.
  8156. As usual, we implement the pass as a recursive function over the
  8157. AST. All of the action is in the cases for \key{Lambda} and
  8158. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8159. that creates a closure, that is, a vector whose first element is a
  8160. function pointer and the rest of the elements are the free variables
  8161. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8162. using \code{vector} so that we can distinguish closures from vectors
  8163. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8164. the generated code below, the \itm{name} is a unique symbol generated
  8165. to identify the function and the \itm{arity} is the number of
  8166. parameters (the length of \itm{ps}).
  8167. \begin{lstlisting}
  8168. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8169. |$\Rightarrow$|
  8170. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8171. \end{lstlisting}
  8172. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8173. create a top-level function definition for each \key{Lambda}, as
  8174. shown below.\\
  8175. \begin{minipage}{0.8\textwidth}
  8176. \begin{lstlisting}
  8177. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8178. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8179. ...
  8180. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8181. |\itm{body'}|)...))
  8182. \end{lstlisting}
  8183. \end{minipage}\\
  8184. The \code{clos} parameter refers to the closure. Translate the type
  8185. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8186. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8187. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8188. underscore \code{\_} is a dummy type that we use because it is rather
  8189. difficult to give a type to the function in the closure's
  8190. type.\footnote{To give an accurate type to a closure, we would need to
  8191. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8192. The dummy type is considered to be equal to any other type during type
  8193. checking. The sequence of \key{Let} forms bind the free variables to
  8194. their values obtained from the closure.
  8195. Closure conversion turns functions into vectors, so the type
  8196. annotations in the program must also be translated. We recommend
  8197. defining a auxiliary recursive function for this purpose. Function
  8198. types should be translated as follows.
  8199. \begin{lstlisting}
  8200. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8201. |$\Rightarrow$|
  8202. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8203. \end{lstlisting}
  8204. The above type says that the first thing in the vector is a function
  8205. pointer. The first parameter of the function pointer is a vector (a
  8206. closure) and the rest of the parameters are the ones from the original
  8207. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8208. the closure omits the types of the free variables because 1) those
  8209. types are not available in this context and 2) we do not need them in
  8210. the code that is generated for function application.
  8211. We transform function application into code that retrieves the
  8212. function pointer from the closure and then calls the function, passing
  8213. in the closure as the first argument. We bind $e'$ to a temporary
  8214. variable to avoid code duplication.
  8215. \begin{lstlisting}
  8216. (Apply |$e$| |\itm{es}|)
  8217. |$\Rightarrow$|
  8218. (Let |\itm{tmp}| |$e'$|
  8219. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8220. \end{lstlisting}
  8221. There is also the question of what to do with references top-level
  8222. function definitions. To maintain a uniform translation of function
  8223. application, we turn function references into closures.
  8224. \begin{tabular}{lll}
  8225. \begin{minipage}{0.3\textwidth}
  8226. \begin{lstlisting}
  8227. (FunRefArity |$f$| |$n$|)
  8228. \end{lstlisting}
  8229. \end{minipage}
  8230. &
  8231. $\Rightarrow$
  8232. &
  8233. \begin{minipage}{0.5\textwidth}
  8234. \begin{lstlisting}
  8235. (Closure |$n$| (FunRef |$f$|) '())
  8236. \end{lstlisting}
  8237. \end{minipage}
  8238. \end{tabular} \\
  8239. %
  8240. The top-level function definitions need to be updated as well to take
  8241. an extra closure parameter.
  8242. \section{An Example Translation}
  8243. \label{sec:example-lambda}
  8244. Figure~\ref{fig:lexical-functions-example} shows the result of
  8245. \code{reveal-functions} and \code{convert-to-closures} for the example
  8246. program demonstrating lexical scoping that we discussed at the
  8247. beginning of this chapter.
  8248. \begin{figure}[tbp]
  8249. \begin{minipage}{0.8\textwidth}
  8250. % tests/lambda_test_6.rkt
  8251. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8252. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8253. (let ([y8 4])
  8254. (lambda: ([z9 : Integer]) : Integer
  8255. (+ x7 (+ y8 z9)))))
  8256. (define (main) : Integer
  8257. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8258. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8259. (+ (g0 11) (h1 15)))))
  8260. \end{lstlisting}
  8261. $\Rightarrow$
  8262. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8263. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8264. (let ([y8 4])
  8265. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8266. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8267. (let ([x7 (vector-ref fvs3 1)])
  8268. (let ([y8 (vector-ref fvs3 2)])
  8269. (+ x7 (+ y8 z9)))))
  8270. (define (main) : Integer
  8271. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8272. ((vector-ref clos5 0) clos5 5))])
  8273. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8274. ((vector-ref clos6 0) clos6 3))])
  8275. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8276. \end{lstlisting}
  8277. \end{minipage}
  8278. \caption{Example of closure conversion.}
  8279. \label{fig:lexical-functions-example}
  8280. \end{figure}
  8281. \begin{exercise}\normalfont
  8282. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8283. Create 5 new programs that use \key{lambda} functions and make use of
  8284. lexical scoping. Test your compiler on these new programs and all of
  8285. your previously created test programs.
  8286. \end{exercise}
  8287. \section{Expose Allocation}
  8288. \label{sec:expose-allocation-r5}
  8289. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8290. that allocates and initializes a vector, similar to the translation of
  8291. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8292. The only difference is replacing the use of
  8293. \ALLOC{\itm{len}}{\itm{type}} with
  8294. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8295. \section{Explicate Control and \LangCLam{}}
  8296. \label{sec:explicate-r5}
  8297. The output language of \code{explicate-control} is \LangCLam{} whose
  8298. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8299. difference with respect to \LangCFun{} is the addition of the
  8300. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8301. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8302. similar to the handling of other expressions such as primitive
  8303. operators.
  8304. \begin{figure}[tp]
  8305. \fbox{
  8306. \begin{minipage}{0.96\textwidth}
  8307. \small
  8308. \[
  8309. \begin{array}{lcl}
  8310. \Exp &::= & \ldots
  8311. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8312. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8313. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8314. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8315. \mid \GOTO{\itm{label}} } \\
  8316. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8317. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8318. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8319. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8320. \end{array}
  8321. \]
  8322. \end{minipage}
  8323. }
  8324. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8325. \label{fig:c4-syntax}
  8326. \end{figure}
  8327. \section{Select Instructions}
  8328. \label{sec:select-instructions-Rlambda}
  8329. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8330. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8331. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8332. that you should place the \itm{arity} in the tag that is stored at
  8333. position $0$ of the vector. Recall that in
  8334. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8335. was not used. We store the arity in the $5$ bits starting at position
  8336. $58$.
  8337. Compile the \code{procedure-arity} operator into a sequence of
  8338. instructions that access the tag from position $0$ of the vector and
  8339. extract the $5$-bits starting at position $58$ from the tag.
  8340. \begin{figure}[p]
  8341. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8342. \node (Rfun) at (0,2) {\large \LangFun{}};
  8343. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8344. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8345. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8346. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8347. \node (F1-3) at (6,0) {\large $F_1$};
  8348. \node (F1-4) at (3,0) {\large $F_1$};
  8349. \node (F1-5) at (0,0) {\large $F_1$};
  8350. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8351. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8352. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8353. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8354. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8355. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8356. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8357. \path[->,bend left=15] (Rfun) edge [above] node
  8358. {\ttfamily\footnotesize shrink} (Rfun-2);
  8359. \path[->,bend left=15] (Rfun-2) edge [above] node
  8360. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8361. \path[->,bend left=15] (Rfun-3) edge [right] node
  8362. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8363. \path[->,bend left=15] (F1-1) edge [below] node
  8364. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8365. \path[->,bend right=15] (F1-2) edge [above] node
  8366. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8367. \path[->,bend right=15] (F1-3) edge [above] node
  8368. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8369. \path[->,bend right=15] (F1-4) edge [above] node
  8370. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8371. \path[->,bend right=15] (F1-5) edge [right] node
  8372. {\ttfamily\footnotesize explicate-control} (C3-2);
  8373. \path[->,bend left=15] (C3-2) edge [left] node
  8374. {\ttfamily\footnotesize select-instr.} (x86-2);
  8375. \path[->,bend right=15] (x86-2) edge [left] node
  8376. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8377. \path[->,bend right=15] (x86-2-1) edge [below] node
  8378. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8379. \path[->,bend right=15] (x86-2-2) edge [left] node
  8380. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8381. \path[->,bend left=15] (x86-3) edge [above] node
  8382. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8383. \path[->,bend left=15] (x86-4) edge [right] node
  8384. {\ttfamily\footnotesize print-x86} (x86-5);
  8385. \end{tikzpicture}
  8386. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8387. functions.}
  8388. \label{fig:Rlambda-passes}
  8389. \end{figure}
  8390. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8391. for the compilation of \LangLam{}.
  8392. \clearpage
  8393. \section{Challenge: Optimize Closures}
  8394. \label{sec:optimize-closures}
  8395. In this chapter we compiled lexically-scoped functions into a
  8396. relatively efficient representation: flat closures. However, even this
  8397. representation comes with some overhead. For example, consider the
  8398. following program with a function \code{tail-sum} that does not have
  8399. any free variables and where all the uses of \code{tail-sum} are in
  8400. applications where we know that only \code{tail-sum} is being applied
  8401. (and not any other functions).
  8402. \begin{center}
  8403. \begin{minipage}{0.95\textwidth}
  8404. \begin{lstlisting}
  8405. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8406. (if (eq? n 0)
  8407. r
  8408. (tail-sum (- n 1) (+ n r))))
  8409. (+ (tail-sum 5 0) 27)
  8410. \end{lstlisting}
  8411. \end{minipage}
  8412. \end{center}
  8413. As described in this chapter, we uniformly apply closure conversion to
  8414. all functions, obtaining the following output for this program.
  8415. \begin{center}
  8416. \begin{minipage}{0.95\textwidth}
  8417. \begin{lstlisting}
  8418. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8419. (if (eq? n2 0)
  8420. r3
  8421. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8422. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8423. (define (main) : Integer
  8424. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8425. ((vector-ref clos6 0) clos6 5 0)) 27))
  8426. \end{lstlisting}
  8427. \end{minipage}
  8428. \end{center}
  8429. In the previous Chapter, there would be no allocation in the program
  8430. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8431. the above program allocates memory for each \code{closure} and the
  8432. calls to \code{tail-sum} are indirect. These two differences incur
  8433. considerable overhead in a program such as this one, where the
  8434. allocations and indirect calls occur inside a tight loop.
  8435. One might think that this problem is trivial to solve: can't we just
  8436. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8437. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8438. e'_n$)} instead of treating it like a call to a closure? We would
  8439. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8440. %
  8441. However, this problem is not so trivial because a global function may
  8442. ``escape'' and become involved in applications that also involve
  8443. closures. Consider the following example in which the application
  8444. \code{(f 41)} needs to be compiled into a closure application, because
  8445. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8446. function might also get bound to \code{f}.
  8447. \begin{lstlisting}
  8448. (define (add1 [x : Integer]) : Integer
  8449. (+ x 1))
  8450. (let ([y (read)])
  8451. (let ([f (if (eq? (read) 0)
  8452. add1
  8453. (lambda: ([x : Integer]) : Integer (- x y)))])
  8454. (f 41)))
  8455. \end{lstlisting}
  8456. If a global function name is used in any way other than as the
  8457. operator in a direct call, then we say that the function
  8458. \emph{escapes}. If a global function does not escape, then we do not
  8459. need to perform closure conversion on the function.
  8460. \begin{exercise}\normalfont
  8461. Implement an auxiliary function for detecting which global
  8462. functions escape. Using that function, implement an improved version
  8463. of closure conversion that does not apply closure conversion to
  8464. global functions that do not escape but instead compiles them as
  8465. regular functions. Create several new test cases that check whether
  8466. you properly detect whether global functions escape or not.
  8467. \end{exercise}
  8468. So far we have reduced the overhead of calling global functions, but
  8469. it would also be nice to reduce the overhead of calling a
  8470. \code{lambda} when we can determine at compile time which
  8471. \code{lambda} will be called. We refer to such calls as \emph{known
  8472. calls}. Consider the following example in which a \code{lambda} is
  8473. bound to \code{f} and then applied.
  8474. \begin{lstlisting}
  8475. (let ([y (read)])
  8476. (let ([f (lambda: ([x : Integer]) : Integer
  8477. (+ x y))])
  8478. (f 21)))
  8479. \end{lstlisting}
  8480. Closure conversion compiles \code{(f 21)} into an indirect call:
  8481. \begin{lstlisting}
  8482. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8483. (let ([y2 (vector-ref fvs6 1)])
  8484. (+ x3 y2)))
  8485. (define (main) : Integer
  8486. (let ([y2 (read)])
  8487. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8488. ((vector-ref f4 0) f4 21))))
  8489. \end{lstlisting}
  8490. but we can instead compile the application \code{(f 21)} into a direct call
  8491. to \code{lambda5}:
  8492. \begin{lstlisting}
  8493. (define (main) : Integer
  8494. (let ([y2 (read)])
  8495. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8496. ((fun-ref lambda5) f4 21))))
  8497. \end{lstlisting}
  8498. The problem of determining which lambda will be called from a
  8499. particular application is quite challenging in general and the topic
  8500. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8501. following exercise we recommend that you compile an application to a
  8502. direct call when the operator is a variable and the variable is
  8503. \code{let}-bound to a closure. This can be accomplished by maintaining
  8504. an environment mapping \code{let}-bound variables to function names.
  8505. Extend the environment whenever you encounter a closure on the
  8506. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8507. to the name of the global function for the closure. This pass should
  8508. come after closure conversion.
  8509. \begin{exercise}\normalfont
  8510. Implement a compiler pass, named \code{optimize-known-calls}, that
  8511. compiles known calls into direct calls. Verify that your compiler is
  8512. successful in this regard on several example programs.
  8513. \end{exercise}
  8514. These exercises only scratches the surface of optimizing of
  8515. closures. A good next step for the interested reader is to look at the
  8516. work of \citet{Keep:2012ab}.
  8517. \section{Further Reading}
  8518. The notion of lexically scoped anonymous functions predates modern
  8519. computers by about a decade. They were invented by
  8520. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8521. foundation for logic. Anonymous functions were included in the
  8522. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8523. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8524. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8525. compile Scheme programs. However, environments were represented as
  8526. linked lists, so variable lookup was linear in the size of the
  8527. environment. In this chapter we represent environments using flat
  8528. closures, which were invented by
  8529. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8530. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8531. closures, variable lookup is constant time but the time to create a
  8532. closure is proportional to the number of its free variables. Flat
  8533. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8534. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8535. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8536. \chapter{Dynamic Typing}
  8537. \label{ch:Rdyn}
  8538. \index{dynamic typing}
  8539. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8540. typed language that is a subset of Racket. This is in contrast to the
  8541. previous chapters, which have studied the compilation of Typed
  8542. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8543. expression may produce a value of a different type each time it is
  8544. executed. Consider the following example with a conditional \code{if}
  8545. expression that may return a Boolean or an integer depending on the
  8546. input to the program.
  8547. % part of dynamic_test_25.rkt
  8548. \begin{lstlisting}
  8549. (not (if (eq? (read) 1) #f 0))
  8550. \end{lstlisting}
  8551. Languages that allow expressions to produce different kinds of values
  8552. are called \emph{polymorphic}, a word composed of the Greek roots
  8553. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8554. are several kinds of polymorphism in programming languages, such as
  8555. subtype polymorphism and parametric
  8556. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8557. study in this chapter does not have a special name but it is the kind
  8558. that arises in dynamically typed languages.
  8559. Another characteristic of dynamically typed languages is that
  8560. primitive operations, such as \code{not}, are often defined to operate
  8561. on many different types of values. In fact, in Racket, the \code{not}
  8562. operator produces a result for any kind of value: given \code{\#f} it
  8563. returns \code{\#t} and given anything else it returns \code{\#f}.
  8564. Furthermore, even when primitive operations restrict their inputs to
  8565. values of a certain type, this restriction is enforced at runtime
  8566. instead of during compilation. For example, the following vector
  8567. reference results in a run-time contract violation because the index
  8568. must be in integer, not a Boolean such as \code{\#t}.
  8569. \begin{lstlisting}
  8570. (vector-ref (vector 42) #t)
  8571. \end{lstlisting}
  8572. \begin{figure}[tp]
  8573. \centering
  8574. \fbox{
  8575. \begin{minipage}{0.97\textwidth}
  8576. \[
  8577. \begin{array}{rcl}
  8578. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8579. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8580. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8581. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8582. &\mid& \key{\#t} \mid \key{\#f}
  8583. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8584. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8585. \mid \CUNIOP{\key{not}}{\Exp} \\
  8586. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8587. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8588. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8589. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8590. &\mid& \LP\Exp \; \Exp\ldots\RP
  8591. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8592. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8593. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8594. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8595. \LangDyn{} &::=& \Def\ldots\; \Exp
  8596. \end{array}
  8597. \]
  8598. \end{minipage}
  8599. }
  8600. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8601. \label{fig:r7-concrete-syntax}
  8602. \end{figure}
  8603. \begin{figure}[tp]
  8604. \centering
  8605. \fbox{
  8606. \begin{minipage}{0.96\textwidth}
  8607. \small
  8608. \[
  8609. \begin{array}{lcl}
  8610. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8611. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8612. &\mid& \BOOL{\itm{bool}}
  8613. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8614. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8615. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8616. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8617. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8618. \end{array}
  8619. \]
  8620. \end{minipage}
  8621. }
  8622. \caption{The abstract syntax of \LangDyn{}.}
  8623. \label{fig:r7-syntax}
  8624. \end{figure}
  8625. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8626. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8627. \ref{fig:r7-syntax}.
  8628. %
  8629. There is no type checker for \LangDyn{} because it is not a statically
  8630. typed language (it's dynamically typed!).
  8631. The definitional interpreter for \LangDyn{} is presented in
  8632. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8633. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8634. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8635. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8636. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8637. value} that combines an underlying value with a tag that identifies
  8638. what kind of value it is. We define the following struct
  8639. to represented tagged values.
  8640. \begin{lstlisting}
  8641. (struct Tagged (value tag) #:transparent)
  8642. \end{lstlisting}
  8643. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8644. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8645. but don't always capture all the information that a type does. For
  8646. example, a vector of type \code{(Vector Any Any)} is tagged with
  8647. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8648. is tagged with \code{Procedure}.
  8649. Next consider the match case for \code{vector-ref}. The
  8650. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8651. is used to ensure that the first argument is a vector and the second
  8652. is an integer. If they are not, a \code{trapped-error} is raised.
  8653. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8654. interpreter raises a \code{trapped-error} error, the compiled code
  8655. must also signal an error by exiting with return code \code{255}. A
  8656. \code{trapped-error} is also raised if the index is not less than
  8657. length of the vector.
  8658. \begin{figure}[tbp]
  8659. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8660. (define ((interp-Rdyn-exp env) ast)
  8661. (define recur (interp-Rdyn-exp env))
  8662. (match ast
  8663. [(Var x) (lookup x env)]
  8664. [(Int n) (Tagged n 'Integer)]
  8665. [(Bool b) (Tagged b 'Boolean)]
  8666. [(Lambda xs rt body)
  8667. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8668. [(Prim 'vector es)
  8669. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8670. [(Prim 'vector-ref (list e1 e2))
  8671. (define vec (recur e1)) (define i (recur e2))
  8672. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8673. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8674. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8675. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8676. [(Prim 'vector-set! (list e1 e2 e3))
  8677. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8678. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8679. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8680. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8681. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8682. (Tagged (void) 'Void)]
  8683. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8684. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8685. [(Prim 'or (list e1 e2))
  8686. (define v1 (recur e1))
  8687. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8688. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8689. [(Prim op (list e1))
  8690. #:when (set-member? type-predicates op)
  8691. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8692. [(Prim op es)
  8693. (define args (map recur es))
  8694. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8695. (unless (for/or ([expected-tags (op-tags op)])
  8696. (equal? expected-tags tags))
  8697. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8698. (tag-value
  8699. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8700. [(If q t f)
  8701. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8702. [(Apply f es)
  8703. (define new-f (recur f)) (define args (map recur es))
  8704. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8705. (match f-val
  8706. [`(function ,xs ,body ,lam-env)
  8707. (unless (eq? (length xs) (length args))
  8708. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8709. (define new-env (append (map cons xs args) lam-env))
  8710. ((interp-Rdyn-exp new-env) body)]
  8711. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8712. \end{lstlisting}
  8713. \caption{Interpreter for the \LangDyn{} language.}
  8714. \label{fig:interp-Rdyn}
  8715. \end{figure}
  8716. \begin{figure}[tbp]
  8717. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8718. (define (interp-op op)
  8719. (match op
  8720. ['+ fx+]
  8721. ['- fx-]
  8722. ['read read-fixnum]
  8723. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8724. ['< (lambda (v1 v2)
  8725. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8726. ['<= (lambda (v1 v2)
  8727. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8728. ['> (lambda (v1 v2)
  8729. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8730. ['>= (lambda (v1 v2)
  8731. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8732. ['boolean? boolean?]
  8733. ['integer? fixnum?]
  8734. ['void? void?]
  8735. ['vector? vector?]
  8736. ['vector-length vector-length]
  8737. ['procedure? (match-lambda
  8738. [`(functions ,xs ,body ,env) #t] [else #f])]
  8739. [else (error 'interp-op "unknown operator" op)]))
  8740. (define (op-tags op)
  8741. (match op
  8742. ['+ '((Integer Integer))]
  8743. ['- '((Integer Integer) (Integer))]
  8744. ['read '(())]
  8745. ['not '((Boolean))]
  8746. ['< '((Integer Integer))]
  8747. ['<= '((Integer Integer))]
  8748. ['> '((Integer Integer))]
  8749. ['>= '((Integer Integer))]
  8750. ['vector-length '((Vector))]))
  8751. (define type-predicates
  8752. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8753. (define (tag-value v)
  8754. (cond [(boolean? v) (Tagged v 'Boolean)]
  8755. [(fixnum? v) (Tagged v 'Integer)]
  8756. [(procedure? v) (Tagged v 'Procedure)]
  8757. [(vector? v) (Tagged v 'Vector)]
  8758. [(void? v) (Tagged v 'Void)]
  8759. [else (error 'tag-value "unidentified value ~a" v)]))
  8760. (define (check-tag val expected ast)
  8761. (define tag (Tagged-tag val))
  8762. (unless (eq? tag expected)
  8763. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8764. \end{lstlisting}
  8765. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8766. \label{fig:interp-Rdyn-aux}
  8767. \end{figure}
  8768. \clearpage
  8769. \section{Representation of Tagged Values}
  8770. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8771. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8772. values at the bit level. Because almost every operation in \LangDyn{}
  8773. involves manipulating tagged values, the representation must be
  8774. efficient. Recall that all of our values are 64 bits. We shall steal
  8775. the 3 right-most bits to encode the tag. We use $001$ to identify
  8776. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8777. and $101$ for the void value. We define the following auxiliary
  8778. function for mapping types to tag codes.
  8779. \begin{align*}
  8780. \itm{tagof}(\key{Integer}) &= 001 \\
  8781. \itm{tagof}(\key{Boolean}) &= 100 \\
  8782. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8783. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8784. \itm{tagof}(\key{Void}) &= 101
  8785. \end{align*}
  8786. This stealing of 3 bits comes at some price: our integers are reduced
  8787. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8788. affect vectors and procedures because those values are addresses, and
  8789. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8790. they are always $000$. Thus, we do not lose information by overwriting
  8791. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8792. to recover the original address.
  8793. To make tagged values into first-class entities, we can give them a
  8794. type, called \code{Any}, and define operations such as \code{Inject}
  8795. and \code{Project} for creating and using them, yielding the \LangAny{}
  8796. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8797. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8798. in greater detail.
  8799. \section{The \LangAny{} Language}
  8800. \label{sec:Rany-lang}
  8801. \begin{figure}[tp]
  8802. \centering
  8803. \fbox{
  8804. \begin{minipage}{0.96\textwidth}
  8805. \small
  8806. \[
  8807. \begin{array}{lcl}
  8808. \Type &::= & \ldots \mid \key{Any} \\
  8809. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8810. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8811. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8812. \mid \code{procedure?} \mid \code{void?} \\
  8813. \Exp &::=& \ldots
  8814. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8815. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8816. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8817. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8818. \end{array}
  8819. \]
  8820. \end{minipage}
  8821. }
  8822. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8823. \label{fig:Rany-syntax}
  8824. \end{figure}
  8825. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8826. (The concrete syntax of \LangAny{} is in the Appendix,
  8827. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8828. converts the value produced by expression $e$ of type $T$ into a
  8829. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8830. produced by expression $e$ into a value of type $T$ or else halts the
  8831. program if the type tag is not equivalent to $T$.
  8832. %
  8833. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8834. restricted to a flat type $\FType$, which simplifies the
  8835. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8836. The \code{any-vector} operators adapt the vector operations so that
  8837. they can be applied to a value of type \code{Any}. They also
  8838. generalize the vector operations in that the index is not restricted
  8839. to be a literal integer in the grammar but is allowed to be any
  8840. expression.
  8841. The type predicates such as \key{boolean?} expect their argument to
  8842. produce a tagged value; they return \key{\#t} if the tag corresponds
  8843. to the predicate and they return \key{\#f} otherwise.
  8844. The type checker for \LangAny{} is shown in
  8845. Figures~\ref{fig:type-check-Rany-part-1} and
  8846. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8847. Figure~\ref{fig:type-check-Rany-aux}.
  8848. %
  8849. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8850. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8851. in Figure~\ref{fig:apply-project}.
  8852. \begin{figure}[btp]
  8853. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8854. (define type-check-Rany-class
  8855. (class type-check-Rlambda-class
  8856. (super-new)
  8857. (inherit check-type-equal?)
  8858. (define/override (type-check-exp env)
  8859. (lambda (e)
  8860. (define recur (type-check-exp env))
  8861. (match e
  8862. [(Inject e1 ty)
  8863. (unless (flat-ty? ty)
  8864. (error 'type-check "may only inject from flat type, not ~a" ty))
  8865. (define-values (new-e1 e-ty) (recur e1))
  8866. (check-type-equal? e-ty ty e)
  8867. (values (Inject new-e1 ty) 'Any)]
  8868. [(Project e1 ty)
  8869. (unless (flat-ty? ty)
  8870. (error 'type-check "may only project to flat type, not ~a" ty))
  8871. (define-values (new-e1 e-ty) (recur e1))
  8872. (check-type-equal? e-ty 'Any e)
  8873. (values (Project new-e1 ty) ty)]
  8874. [(Prim 'any-vector-length (list e1))
  8875. (define-values (e1^ t1) (recur e1))
  8876. (check-type-equal? t1 'Any e)
  8877. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8878. [(Prim 'any-vector-ref (list e1 e2))
  8879. (define-values (e1^ t1) (recur e1))
  8880. (define-values (e2^ t2) (recur e2))
  8881. (check-type-equal? t1 'Any e)
  8882. (check-type-equal? t2 'Integer e)
  8883. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8884. [(Prim 'any-vector-set! (list e1 e2 e3))
  8885. (define-values (e1^ t1) (recur e1))
  8886. (define-values (e2^ t2) (recur e2))
  8887. (define-values (e3^ t3) (recur e3))
  8888. (check-type-equal? t1 'Any e)
  8889. (check-type-equal? t2 'Integer e)
  8890. (check-type-equal? t3 'Any e)
  8891. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8892. \end{lstlisting}
  8893. \caption{Type checker for the \LangAny{} language, part 1.}
  8894. \label{fig:type-check-Rany-part-1}
  8895. \end{figure}
  8896. \begin{figure}[btp]
  8897. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8898. [(ValueOf e ty)
  8899. (define-values (new-e e-ty) (recur e))
  8900. (values (ValueOf new-e ty) ty)]
  8901. [(Prim pred (list e1))
  8902. #:when (set-member? (type-predicates) pred)
  8903. (define-values (new-e1 e-ty) (recur e1))
  8904. (check-type-equal? e-ty 'Any e)
  8905. (values (Prim pred (list new-e1)) 'Boolean)]
  8906. [(If cnd thn els)
  8907. (define-values (cnd^ Tc) (recur cnd))
  8908. (define-values (thn^ Tt) (recur thn))
  8909. (define-values (els^ Te) (recur els))
  8910. (check-type-equal? Tc 'Boolean cnd)
  8911. (check-type-equal? Tt Te e)
  8912. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8913. [(Exit) (values (Exit) '_)]
  8914. [(Prim 'eq? (list arg1 arg2))
  8915. (define-values (e1 t1) (recur arg1))
  8916. (define-values (e2 t2) (recur arg2))
  8917. (match* (t1 t2)
  8918. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8919. [(other wise) (check-type-equal? t1 t2 e)])
  8920. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8921. [else ((super type-check-exp env) e)])))
  8922. ))
  8923. \end{lstlisting}
  8924. \caption{Type checker for the \LangAny{} language, part 2.}
  8925. \label{fig:type-check-Rany-part-2}
  8926. \end{figure}
  8927. \begin{figure}[tbp]
  8928. \begin{lstlisting}
  8929. (define/override (operator-types)
  8930. (append
  8931. '((integer? . ((Any) . Boolean))
  8932. (vector? . ((Any) . Boolean))
  8933. (procedure? . ((Any) . Boolean))
  8934. (void? . ((Any) . Boolean))
  8935. (tag-of-any . ((Any) . Integer))
  8936. (make-any . ((_ Integer) . Any))
  8937. )
  8938. (super operator-types)))
  8939. (define/public (type-predicates)
  8940. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8941. (define/public (combine-types t1 t2)
  8942. (match (list t1 t2)
  8943. [(list '_ t2) t2]
  8944. [(list t1 '_) t1]
  8945. [(list `(Vector ,ts1 ...)
  8946. `(Vector ,ts2 ...))
  8947. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8948. (combine-types t1 t2)))]
  8949. [(list `(,ts1 ... -> ,rt1)
  8950. `(,ts2 ... -> ,rt2))
  8951. `(,@(for/list ([t1 ts1] [t2 ts2])
  8952. (combine-types t1 t2))
  8953. -> ,(combine-types rt1 rt2))]
  8954. [else t1]))
  8955. (define/public (flat-ty? ty)
  8956. (match ty
  8957. [(or `Integer `Boolean '_ `Void) #t]
  8958. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8959. [`(,ts ... -> ,rt)
  8960. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8961. [else #f]))
  8962. \end{lstlisting}
  8963. \caption{Auxiliary methods for type checking \LangAny{}.}
  8964. \label{fig:type-check-Rany-aux}
  8965. \end{figure}
  8966. \begin{figure}[btp]
  8967. \begin{lstlisting}
  8968. (define interp-Rany-class
  8969. (class interp-Rlambda-class
  8970. (super-new)
  8971. (define/override (interp-op op)
  8972. (match op
  8973. ['boolean? (match-lambda
  8974. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8975. [else #f])]
  8976. ['integer? (match-lambda
  8977. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8978. [else #f])]
  8979. ['vector? (match-lambda
  8980. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8981. [else #f])]
  8982. ['procedure? (match-lambda
  8983. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8984. [else #f])]
  8985. ['eq? (match-lambda*
  8986. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8987. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8988. [ls (apply (super interp-op op) ls)])]
  8989. ['any-vector-ref (lambda (v i)
  8990. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8991. ['any-vector-set! (lambda (v i a)
  8992. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8993. ['any-vector-length (lambda (v)
  8994. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8995. [else (super interp-op op)]))
  8996. (define/override ((interp-exp env) e)
  8997. (define recur (interp-exp env))
  8998. (match e
  8999. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9000. [(Project e ty2) (apply-project (recur e) ty2)]
  9001. [else ((super interp-exp env) e)]))
  9002. ))
  9003. (define (interp-Rany p)
  9004. (send (new interp-Rany-class) interp-program p))
  9005. \end{lstlisting}
  9006. \caption{Interpreter for \LangAny{}.}
  9007. \label{fig:interp-Rany}
  9008. \end{figure}
  9009. \begin{figure}[tbp]
  9010. \begin{lstlisting}
  9011. (define/public (apply-inject v tg) (Tagged v tg))
  9012. (define/public (apply-project v ty2)
  9013. (define tag2 (any-tag ty2))
  9014. (match v
  9015. [(Tagged v1 tag1)
  9016. (cond
  9017. [(eq? tag1 tag2)
  9018. (match ty2
  9019. [`(Vector ,ts ...)
  9020. (define l1 ((interp-op 'vector-length) v1))
  9021. (cond
  9022. [(eq? l1 (length ts)) v1]
  9023. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9024. l1 (length ts))])]
  9025. [`(,ts ... -> ,rt)
  9026. (match v1
  9027. [`(function ,xs ,body ,env)
  9028. (cond [(eq? (length xs) (length ts)) v1]
  9029. [else
  9030. (error 'apply-project "arity mismatch ~a != ~a"
  9031. (length xs) (length ts))])]
  9032. [else (error 'apply-project "expected function not ~a" v1)])]
  9033. [else v1])]
  9034. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9035. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9036. \end{lstlisting}
  9037. \caption{Auxiliary functions for injection and projection.}
  9038. \label{fig:apply-project}
  9039. \end{figure}
  9040. \clearpage
  9041. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9042. \label{sec:compile-r7}
  9043. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9044. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9045. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9046. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9047. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9048. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9049. the Boolean \code{\#t}, which must be injected to produce an
  9050. expression of type \key{Any}.
  9051. %
  9052. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9053. addition, is representative of compilation for many primitive
  9054. operations: the arguments have type \key{Any} and must be projected to
  9055. \key{Integer} before the addition can be performed.
  9056. The compilation of \key{lambda} (third row of
  9057. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9058. produce type annotations: we simply use \key{Any}.
  9059. %
  9060. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9061. has to account for some differences in behavior between \LangDyn{} and
  9062. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9063. kind of values can be used in various places. For example, the
  9064. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9065. the arguments need not be of the same type (in that case the
  9066. result is \code{\#f}).
  9067. \begin{figure}[btp]
  9068. \centering
  9069. \begin{tabular}{|lll|} \hline
  9070. \begin{minipage}{0.27\textwidth}
  9071. \begin{lstlisting}
  9072. #t
  9073. \end{lstlisting}
  9074. \end{minipage}
  9075. &
  9076. $\Rightarrow$
  9077. &
  9078. \begin{minipage}{0.65\textwidth}
  9079. \begin{lstlisting}
  9080. (inject #t Boolean)
  9081. \end{lstlisting}
  9082. \end{minipage}
  9083. \\[2ex]\hline
  9084. \begin{minipage}{0.27\textwidth}
  9085. \begin{lstlisting}
  9086. (+ |$e_1$| |$e_2$|)
  9087. \end{lstlisting}
  9088. \end{minipage}
  9089. &
  9090. $\Rightarrow$
  9091. &
  9092. \begin{minipage}{0.65\textwidth}
  9093. \begin{lstlisting}
  9094. (inject
  9095. (+ (project |$e'_1$| Integer)
  9096. (project |$e'_2$| Integer))
  9097. Integer)
  9098. \end{lstlisting}
  9099. \end{minipage}
  9100. \\[2ex]\hline
  9101. \begin{minipage}{0.27\textwidth}
  9102. \begin{lstlisting}
  9103. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9104. \end{lstlisting}
  9105. \end{minipage}
  9106. &
  9107. $\Rightarrow$
  9108. &
  9109. \begin{minipage}{0.65\textwidth}
  9110. \begin{lstlisting}
  9111. (inject
  9112. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9113. (Any|$\ldots$|Any -> Any))
  9114. \end{lstlisting}
  9115. \end{minipage}
  9116. \\[2ex]\hline
  9117. \begin{minipage}{0.27\textwidth}
  9118. \begin{lstlisting}
  9119. (|$e_0$| |$e_1 \ldots e_n$|)
  9120. \end{lstlisting}
  9121. \end{minipage}
  9122. &
  9123. $\Rightarrow$
  9124. &
  9125. \begin{minipage}{0.65\textwidth}
  9126. \begin{lstlisting}
  9127. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9128. \end{lstlisting}
  9129. \end{minipage}
  9130. \\[2ex]\hline
  9131. \begin{minipage}{0.27\textwidth}
  9132. \begin{lstlisting}
  9133. (vector-ref |$e_1$| |$e_2$|)
  9134. \end{lstlisting}
  9135. \end{minipage}
  9136. &
  9137. $\Rightarrow$
  9138. &
  9139. \begin{minipage}{0.65\textwidth}
  9140. \begin{lstlisting}
  9141. (any-vector-ref |$e_1'$| |$e_2'$|)
  9142. \end{lstlisting}
  9143. \end{minipage}
  9144. \\[2ex]\hline
  9145. \begin{minipage}{0.27\textwidth}
  9146. \begin{lstlisting}
  9147. (if |$e_1$| |$e_2$| |$e_3$|)
  9148. \end{lstlisting}
  9149. \end{minipage}
  9150. &
  9151. $\Rightarrow$
  9152. &
  9153. \begin{minipage}{0.65\textwidth}
  9154. \begin{lstlisting}
  9155. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9156. \end{lstlisting}
  9157. \end{minipage}
  9158. \\[2ex]\hline
  9159. \begin{minipage}{0.27\textwidth}
  9160. \begin{lstlisting}
  9161. (eq? |$e_1$| |$e_2$|)
  9162. \end{lstlisting}
  9163. \end{minipage}
  9164. &
  9165. $\Rightarrow$
  9166. &
  9167. \begin{minipage}{0.65\textwidth}
  9168. \begin{lstlisting}
  9169. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9170. \end{lstlisting}
  9171. \end{minipage}
  9172. \\[2ex]\hline
  9173. \begin{minipage}{0.27\textwidth}
  9174. \begin{lstlisting}
  9175. (not |$e_1$|)
  9176. \end{lstlisting}
  9177. \end{minipage}
  9178. &
  9179. $\Rightarrow$
  9180. &
  9181. \begin{minipage}{0.65\textwidth}
  9182. \begin{lstlisting}
  9183. (if (eq? |$e'_1$| (inject #f Boolean))
  9184. (inject #t Boolean) (inject #f Boolean))
  9185. \end{lstlisting}
  9186. \end{minipage}
  9187. \\[2ex]\hline
  9188. \end{tabular}
  9189. \caption{Cast Insertion}
  9190. \label{fig:compile-r7-Rany}
  9191. \end{figure}
  9192. \section{Reveal Casts}
  9193. \label{sec:reveal-casts-Rany}
  9194. % TODO: define R'_6
  9195. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9196. into an \code{if} expression that checks whether the value's tag
  9197. matches the target type; if it does, the value is converted to a value
  9198. of the target type by removing the tag; if it does not, the program
  9199. exits. To perform these actions we need a new primitive operation,
  9200. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9201. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9202. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9203. underlying value from a tagged value. The \code{ValueOf} form
  9204. includes the type for the underlying value which is used by the type
  9205. checker. Finally, the \code{Exit} form ends the execution of the
  9206. program.
  9207. If the target type of the projection is \code{Boolean} or
  9208. \code{Integer}, then \code{Project} can be translated as follows.
  9209. \begin{center}
  9210. \begin{minipage}{1.0\textwidth}
  9211. \begin{lstlisting}
  9212. (Project |$e$| |$\FType$|)
  9213. |$\Rightarrow$|
  9214. (Let |$\itm{tmp}$| |$e'$|
  9215. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9216. (Int |$\itm{tagof}(\FType)$|)))
  9217. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9218. (Exit)))
  9219. \end{lstlisting}
  9220. \end{minipage}
  9221. \end{center}
  9222. If the target type of the projection is a vector or function type,
  9223. then there is a bit more work to do. For vectors, check that the
  9224. length of the vector type matches the length of the vector (using the
  9225. \code{vector-length} primitive). For functions, check that the number
  9226. of parameters in the function type matches the function's arity (using
  9227. \code{procedure-arity}).
  9228. Regarding \code{inject}, we recommend compiling it to a slightly
  9229. lower-level primitive operation named \code{make-any}. This operation
  9230. takes a tag instead of a type.
  9231. \begin{center}
  9232. \begin{minipage}{1.0\textwidth}
  9233. \begin{lstlisting}
  9234. (Inject |$e$| |$\FType$|)
  9235. |$\Rightarrow$|
  9236. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9237. \end{lstlisting}
  9238. \end{minipage}
  9239. \end{center}
  9240. The type predicates (\code{boolean?}, etc.) can be translated into
  9241. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9242. translation of \code{Project}.
  9243. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9244. combine the projection action with the vector operation. Also, the
  9245. read and write operations allow arbitrary expressions for the index so
  9246. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9247. cannot guarantee that the index is within bounds. Thus, we insert code
  9248. to perform bounds checking at runtime. The translation for
  9249. \code{any-vector-ref} is as follows and the other two operations are
  9250. translated in a similar way.
  9251. \begin{lstlisting}
  9252. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9253. |$\Rightarrow$|
  9254. (Let |$v$| |$e'_1$|
  9255. (Let |$i$| |$e'_2$|
  9256. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9257. (If (Prim '< (list (Var |$i$|)
  9258. (Prim 'any-vector-length (list (Var |$v$|)))))
  9259. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9260. (Exit))))
  9261. \end{lstlisting}
  9262. \section{Remove Complex Operands}
  9263. \label{sec:rco-Rany}
  9264. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9265. The subexpression of \code{ValueOf} must be atomic.
  9266. \section{Explicate Control and \LangCAny{}}
  9267. \label{sec:explicate-Rany}
  9268. The output of \code{explicate-control} is the \LangCAny{} language whose
  9269. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9270. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9271. expression becomes a $\Tail$. Also, note that the index argument of
  9272. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9273. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9274. \begin{figure}[tp]
  9275. \fbox{
  9276. \begin{minipage}{0.96\textwidth}
  9277. \small
  9278. \[
  9279. \begin{array}{lcl}
  9280. \Exp &::= & \ldots
  9281. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9282. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9283. &\mid& \VALUEOF{\Exp}{\FType} \\
  9284. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9285. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9286. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9287. \mid \GOTO{\itm{label}} } \\
  9288. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9289. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9290. \mid \LP\key{Exit}\RP \\
  9291. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9292. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9293. \end{array}
  9294. \]
  9295. \end{minipage}
  9296. }
  9297. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9298. \label{fig:c5-syntax}
  9299. \end{figure}
  9300. \section{Select Instructions}
  9301. \label{sec:select-Rany}
  9302. In the \code{select-instructions} pass we translate the primitive
  9303. operations on the \code{Any} type to x86 instructions that involve
  9304. manipulating the 3 tag bits of the tagged value.
  9305. \paragraph{Make-any}
  9306. We recommend compiling the \key{make-any} primitive as follows if the
  9307. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9308. shifts the destination to the left by the number of bits specified its
  9309. source argument (in this case $3$, the length of the tag) and it
  9310. preserves the sign of the integer. We use the \key{orq} instruction to
  9311. combine the tag and the value to form the tagged value. \\
  9312. \begin{lstlisting}
  9313. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9314. |$\Rightarrow$|
  9315. movq |$e'$|, |\itm{lhs'}|
  9316. salq $3, |\itm{lhs'}|
  9317. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9318. \end{lstlisting}
  9319. The instruction selection for vectors and procedures is different
  9320. because their is no need to shift them to the left. The rightmost 3
  9321. bits are already zeros as described at the beginning of this
  9322. chapter. So we just combine the value and the tag using \key{orq}. \\
  9323. \begin{lstlisting}
  9324. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9325. |$\Rightarrow$|
  9326. movq |$e'$|, |\itm{lhs'}|
  9327. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9328. \end{lstlisting}
  9329. \paragraph{Tag-of-any}
  9330. Recall that the \code{tag-of-any} operation extracts the type tag from
  9331. a value of type \code{Any}. The type tag is the bottom three bits, so
  9332. we obtain the tag by taking the bitwise-and of the value with $111$
  9333. ($7$ in decimal).
  9334. \begin{lstlisting}
  9335. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9336. |$\Rightarrow$|
  9337. movq |$e'$|, |\itm{lhs'}|
  9338. andq $7, |\itm{lhs'}|
  9339. \end{lstlisting}
  9340. \paragraph{ValueOf}
  9341. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9342. depending on whether the type $T$ is a pointer (vector or procedure)
  9343. or not (Integer or Boolean). The following shows the instruction
  9344. selection for Integer and Boolean. We produce an untagged value by
  9345. shifting it to the right by 3 bits.
  9346. \begin{lstlisting}
  9347. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9348. |$\Rightarrow$|
  9349. movq |$e'$|, |\itm{lhs'}|
  9350. sarq $3, |\itm{lhs'}|
  9351. \end{lstlisting}
  9352. %
  9353. In the case for vectors and procedures, there is no need to
  9354. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9355. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9356. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9357. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9358. then apply \code{andq} with the tagged value to get the desired
  9359. result. \\
  9360. \begin{lstlisting}
  9361. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9362. |$\Rightarrow$|
  9363. movq $|$-8$|, |\itm{lhs'}|
  9364. andq |$e'$|, |\itm{lhs'}|
  9365. \end{lstlisting}
  9366. %% \paragraph{Type Predicates} We leave it to the reader to
  9367. %% devise a sequence of instructions to implement the type predicates
  9368. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9369. \paragraph{Any-vector-length}
  9370. \begin{lstlisting}
  9371. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9372. |$\Longrightarrow$|
  9373. movq |$\neg 111$|, %r11
  9374. andq |$a_1'$|, %r11
  9375. movq 0(%r11), %r11
  9376. andq $126, %r11
  9377. sarq $1, %r11
  9378. movq %r11, |$\itm{lhs'}$|
  9379. \end{lstlisting}
  9380. \paragraph{Any-vector-ref}
  9381. The index may be an arbitrary atom so instead of computing the offset
  9382. at compile time, instructions need to be generated to compute the
  9383. offset at runtime as follows. Note the use of the new instruction
  9384. \code{imulq}.
  9385. \begin{center}
  9386. \begin{minipage}{0.96\textwidth}
  9387. \begin{lstlisting}
  9388. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9389. |$\Longrightarrow$|
  9390. movq |$\neg 111$|, %r11
  9391. andq |$a_1'$|, %r11
  9392. movq |$a_2'$|, %rax
  9393. addq $1, %rax
  9394. imulq $8, %rax
  9395. addq %rax, %r11
  9396. movq 0(%r11) |$\itm{lhs'}$|
  9397. \end{lstlisting}
  9398. \end{minipage}
  9399. \end{center}
  9400. \paragraph{Any-vector-set!}
  9401. The code generation for \code{any-vector-set!} is similar to the other
  9402. \code{any-vector} operations.
  9403. \section{Register Allocation for \LangAny{}}
  9404. \label{sec:register-allocation-Rany}
  9405. \index{register allocation}
  9406. There is an interesting interaction between tagged values and garbage
  9407. collection that has an impact on register allocation. A variable of
  9408. type \code{Any} might refer to a vector and therefore it might be a
  9409. root that needs to be inspected and copied during garbage
  9410. collection. Thus, we need to treat variables of type \code{Any} in a
  9411. similar way to variables of type \code{Vector} for purposes of
  9412. register allocation. In particular,
  9413. \begin{itemize}
  9414. \item If a variable of type \code{Any} is live during a function call,
  9415. then it must be spilled. This can be accomplished by changing
  9416. \code{build-interference} to mark all variables of type \code{Any}
  9417. that are live after a \code{callq} as interfering with all the
  9418. registers.
  9419. \item If a variable of type \code{Any} is spilled, it must be spilled
  9420. to the root stack instead of the normal procedure call stack.
  9421. \end{itemize}
  9422. Another concern regarding the root stack is that the garbage collector
  9423. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9424. tagged value that points to a tuple, and (3) a tagged value that is
  9425. not a tuple. We enable this differentiation by choosing not to use the
  9426. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9427. reserved for identifying plain old pointers to tuples. That way, if
  9428. one of the first three bits is set, then we have a tagged value and
  9429. inspecting the tag can differentiation between vectors ($010$) and the
  9430. other kinds of values.
  9431. \begin{exercise}\normalfont
  9432. Expand your compiler to handle \LangAny{} as discussed in the last few
  9433. sections. Create 5 new programs that use the \code{Any} type and the
  9434. new operations (\code{inject}, \code{project}, \code{boolean?},
  9435. etc.). Test your compiler on these new programs and all of your
  9436. previously created test programs.
  9437. \end{exercise}
  9438. \begin{exercise}\normalfont
  9439. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9440. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9441. by removing type annotations. Add 5 more tests programs that
  9442. specifically rely on the language being dynamically typed. That is,
  9443. they should not be legal programs in a statically typed language, but
  9444. nevertheless, they should be valid \LangDyn{} programs that run to
  9445. completion without error.
  9446. \end{exercise}
  9447. \begin{figure}[p]
  9448. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9449. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9450. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9451. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9452. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9453. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9454. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9455. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9456. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9457. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9458. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9459. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9460. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9461. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9462. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9463. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9464. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9465. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9466. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9467. \path[->,bend left=15] (Rfun) edge [above] node
  9468. {\ttfamily\footnotesize shrink} (Rfun-2);
  9469. \path[->,bend left=15] (Rfun-2) edge [above] node
  9470. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9471. \path[->,bend left=15] (Rfun-3) edge [above] node
  9472. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9473. \path[->,bend right=15] (Rfun-4) edge [left] node
  9474. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9475. \path[->,bend left=15] (Rfun-5) edge [above] node
  9476. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9477. \path[->,bend left=15] (Rfun-6) edge [left] node
  9478. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9479. \path[->,bend left=15] (Rfun-7) edge [below] node
  9480. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9481. \path[->,bend right=15] (F1-2) edge [above] node
  9482. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9483. \path[->,bend right=15] (F1-3) edge [above] node
  9484. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9485. \path[->,bend right=15] (F1-4) edge [above] node
  9486. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9487. \path[->,bend right=15] (F1-5) edge [right] node
  9488. {\ttfamily\footnotesize explicate-control} (C3-2);
  9489. \path[->,bend left=15] (C3-2) edge [left] node
  9490. {\ttfamily\footnotesize select-instr.} (x86-2);
  9491. \path[->,bend right=15] (x86-2) edge [left] node
  9492. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9493. \path[->,bend right=15] (x86-2-1) edge [below] node
  9494. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9495. \path[->,bend right=15] (x86-2-2) edge [left] node
  9496. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9497. \path[->,bend left=15] (x86-3) edge [above] node
  9498. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9499. \path[->,bend left=15] (x86-4) edge [right] node
  9500. {\ttfamily\footnotesize print-x86} (x86-5);
  9501. \end{tikzpicture}
  9502. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9503. \label{fig:Rdyn-passes}
  9504. \end{figure}
  9505. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9506. for the compilation of \LangDyn{}.
  9507. % Further Reading
  9508. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9509. \chapter{Loops and Assignment}
  9510. \label{ch:Rwhile}
  9511. % TODO: define R'_8
  9512. % TODO: multi-graph
  9513. In this chapter we study two features that are the hallmarks of
  9514. imperative programming languages: loops and assignments to local
  9515. variables. The following example demonstrates these new features by
  9516. computing the sum of the first five positive integers.
  9517. % similar to loop_test_1.rkt
  9518. \begin{lstlisting}
  9519. (let ([sum 0])
  9520. (let ([i 5])
  9521. (begin
  9522. (while (> i 0)
  9523. (begin
  9524. (set! sum (+ sum i))
  9525. (set! i (- i 1))))
  9526. sum)))
  9527. \end{lstlisting}
  9528. The \code{while} loop consists of a condition and a body.
  9529. %
  9530. The \code{set!} consists of a variable and a right-hand-side expression.
  9531. %
  9532. The primary purpose of both the \code{while} loop and \code{set!} is
  9533. to cause side effects, so it is convenient to also include in a
  9534. language feature for sequencing side effects: the \code{begin}
  9535. expression. It consists of one or more subexpressions that are
  9536. evaluated left-to-right.
  9537. \section{The \LangLoop{} Language}
  9538. \begin{figure}[tp]
  9539. \centering
  9540. \fbox{
  9541. \begin{minipage}{0.96\textwidth}
  9542. \small
  9543. \[
  9544. \begin{array}{lcl}
  9545. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9546. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9547. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9548. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9549. \mid (\key{and}\;\Exp\;\Exp)
  9550. \mid (\key{or}\;\Exp\;\Exp)
  9551. \mid (\key{not}\;\Exp) } \\
  9552. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9553. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9554. (\key{vector-ref}\;\Exp\;\Int)} \\
  9555. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9556. \mid (\Exp \; \Exp\ldots) } \\
  9557. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9558. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9559. &\mid& \CSETBANG{\Var}{\Exp}
  9560. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9561. \mid \CWHILE{\Exp}{\Exp} \\
  9562. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9563. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9564. \end{array}
  9565. \]
  9566. \end{minipage}
  9567. }
  9568. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9569. \label{fig:Rwhile-concrete-syntax}
  9570. \end{figure}
  9571. \begin{figure}[tp]
  9572. \centering
  9573. \fbox{
  9574. \begin{minipage}{0.96\textwidth}
  9575. \small
  9576. \[
  9577. \begin{array}{lcl}
  9578. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9579. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9580. &\mid& \gray{ \BOOL{\itm{bool}}
  9581. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9582. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9583. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9584. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9585. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9586. \mid \WHILE{\Exp}{\Exp} \\
  9587. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9588. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9589. \end{array}
  9590. \]
  9591. \end{minipage}
  9592. }
  9593. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9594. \label{fig:Rwhile-syntax}
  9595. \end{figure}
  9596. The concrete syntax of \LangLoop{} is defined in
  9597. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9598. in Figure~\ref{fig:Rwhile-syntax}.
  9599. %
  9600. The definitional interpreter for \LangLoop{} is shown in
  9601. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9602. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9603. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9604. support assignment to variables and to make their lifetimes indefinite
  9605. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9606. box the value that is bound to each variable (in \code{Let}) and
  9607. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9608. the value.
  9609. %
  9610. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9611. variable in the environment to obtain a boxed value and then we change
  9612. it using \code{set-box!} to the result of evaluating the right-hand
  9613. side. The result value of a \code{SetBang} is \code{void}.
  9614. %
  9615. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9616. if the result is true, 2) evaluate the body.
  9617. The result value of a \code{while} loop is also \code{void}.
  9618. %
  9619. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9620. subexpressions \itm{es} for their effects and then evaluates
  9621. and returns the result from \itm{body}.
  9622. \begin{figure}[tbp]
  9623. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9624. (define interp-Rwhile-class
  9625. (class interp-Rany-class
  9626. (super-new)
  9627. (define/override ((interp-exp env) e)
  9628. (define recur (interp-exp env))
  9629. (match e
  9630. [(SetBang x rhs)
  9631. (set-box! (lookup x env) (recur rhs))]
  9632. [(WhileLoop cnd body)
  9633. (define (loop)
  9634. (cond [(recur cnd) (recur body) (loop)]
  9635. [else (void)]))
  9636. (loop)]
  9637. [(Begin es body)
  9638. (for ([e es]) (recur e))
  9639. (recur body)]
  9640. [else ((super interp-exp env) e)]))
  9641. ))
  9642. (define (interp-Rwhile p)
  9643. (send (new interp-Rwhile-class) interp-program p))
  9644. \end{lstlisting}
  9645. \caption{Interpreter for \LangLoop{}.}
  9646. \label{fig:interp-Rwhile}
  9647. \end{figure}
  9648. The type checker for \LangLoop{} is define in
  9649. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9650. variable and the right-hand-side must agree. The result type is
  9651. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9652. \code{Boolean}. The result type is also \code{Void}. For
  9653. \code{Begin}, the result type is the type of its last subexpression.
  9654. \begin{figure}[tbp]
  9655. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9656. (define type-check-Rwhile-class
  9657. (class type-check-Rany-class
  9658. (super-new)
  9659. (inherit check-type-equal?)
  9660. (define/override (type-check-exp env)
  9661. (lambda (e)
  9662. (define recur (type-check-exp env))
  9663. (match e
  9664. [(SetBang x rhs)
  9665. (define-values (rhs^ rhsT) (recur rhs))
  9666. (define varT (dict-ref env x))
  9667. (check-type-equal? rhsT varT e)
  9668. (values (SetBang x rhs^) 'Void)]
  9669. [(WhileLoop cnd body)
  9670. (define-values (cnd^ Tc) (recur cnd))
  9671. (check-type-equal? Tc 'Boolean e)
  9672. (define-values (body^ Tbody) ((type-check-exp env) body))
  9673. (values (WhileLoop cnd^ body^) 'Void)]
  9674. [(Begin es body)
  9675. (define-values (es^ ts)
  9676. (for/lists (l1 l2) ([e es]) (recur e)))
  9677. (define-values (body^ Tbody) (recur body))
  9678. (values (Begin es^ body^) Tbody)]
  9679. [else ((super type-check-exp env) e)])))
  9680. ))
  9681. (define (type-check-Rwhile p)
  9682. (send (new type-check-Rwhile-class) type-check-program p))
  9683. \end{lstlisting}
  9684. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9685. and \code{Begin} in \LangLoop{}.}
  9686. \label{fig:type-check-Rwhile}
  9687. \end{figure}
  9688. At first glance, the translation of these language features to x86
  9689. seems straightforward because the \LangCFun{} intermediate language already
  9690. supports all of the ingredients that we need: assignment, \code{goto},
  9691. conditional branching, and sequencing. However, there are two
  9692. complications that arise which we discuss in the next two
  9693. sections. After that we introduce one new compiler pass and the
  9694. changes necessary to the existing passes.
  9695. \section{Assignment and Lexically Scoped Functions}
  9696. \label{sec:assignment-scoping}
  9697. The addition of assignment raises a problem with our approach to
  9698. implementing lexically-scoped functions. Consider the following
  9699. example in which function \code{f} has a free variable \code{x} that
  9700. is changed after \code{f} is created but before the call to \code{f}.
  9701. % loop_test_11.rkt
  9702. \begin{lstlisting}
  9703. (let ([x 0])
  9704. (let ([y 0])
  9705. (let ([z 20])
  9706. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9707. (begin
  9708. (set! x 10)
  9709. (set! y 12)
  9710. (f y))))))
  9711. \end{lstlisting}
  9712. The correct output for this example is \code{42} because the call to
  9713. \code{f} is required to use the current value of \code{x} (which is
  9714. \code{10}). Unfortunately, the closure conversion pass
  9715. (Section~\ref{sec:closure-conversion}) generates code for the
  9716. \code{lambda} that copies the old value of \code{x} into a
  9717. closure. Thus, if we naively add support for assignment to our current
  9718. compiler, the output of this program would be \code{32}.
  9719. A first attempt at solving this problem would be to save a pointer to
  9720. \code{x} in the closure and change the occurrences of \code{x} inside
  9721. the lambda to dereference the pointer. Of course, this would require
  9722. assigning \code{x} to the stack and not to a register. However, the
  9723. problem goes a bit deeper. Consider the following example in which we
  9724. create a counter abstraction by creating a pair of functions that
  9725. share the free variable \code{x}.
  9726. % similar to loop_test_10.rkt
  9727. \begin{lstlisting}
  9728. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9729. (vector
  9730. (lambda: () : Integer x)
  9731. (lambda: () : Void (set! x (+ 1 x)))))
  9732. (let ([counter (f 0)])
  9733. (let ([get (vector-ref counter 0)])
  9734. (let ([inc (vector-ref counter 1)])
  9735. (begin
  9736. (inc)
  9737. (get)))))
  9738. \end{lstlisting}
  9739. In this example, the lifetime of \code{x} extends beyond the lifetime
  9740. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9741. stack frame for the call to \code{f}, it would be gone by the time we
  9742. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9743. \code{x}. This example demonstrates that when a variable occurs free
  9744. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9745. value of the variable needs to live on the heap. The verb ``box'' is
  9746. often used for allocating a single value on the heap, producing a
  9747. pointer, and ``unbox'' for dereferencing the pointer.
  9748. We recommend solving these problems by ``boxing'' the local variables
  9749. that are in the intersection of 1) variables that appear on the
  9750. left-hand-side of a \code{set!} and 2) variables that occur free
  9751. inside a \code{lambda}. We shall introduce a new pass named
  9752. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9753. perform this translation. But before diving into the compiler passes,
  9754. we one more problem to discuss.
  9755. \section{Cyclic Control Flow and Dataflow Analysis}
  9756. \label{sec:dataflow-analysis}
  9757. Up until this point the control-flow graphs generated in
  9758. \code{explicate-control} were guaranteed to be acyclic. However, each
  9759. \code{while} loop introduces a cycle in the control-flow graph.
  9760. But does that matter?
  9761. %
  9762. Indeed it does. Recall that for register allocation, the compiler
  9763. performs liveness analysis to determine which variables can share the
  9764. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9765. the control-flow graph in reverse topological order, but topological
  9766. order is only well-defined for acyclic graphs.
  9767. Let us return to the example of computing the sum of the first five
  9768. positive integers. Here is the program after instruction selection but
  9769. before register allocation.
  9770. \begin{center}
  9771. \begin{minipage}{0.45\textwidth}
  9772. \begin{lstlisting}
  9773. (define (main) : Integer
  9774. mainstart:
  9775. movq $0, sum1
  9776. movq $5, i2
  9777. jmp block5
  9778. block5:
  9779. movq i2, tmp3
  9780. cmpq tmp3, $0
  9781. jl block7
  9782. jmp block8
  9783. \end{lstlisting}
  9784. \end{minipage}
  9785. \begin{minipage}{0.45\textwidth}
  9786. \begin{lstlisting}
  9787. block7:
  9788. addq i2, sum1
  9789. movq $1, tmp4
  9790. negq tmp4
  9791. addq tmp4, i2
  9792. jmp block5
  9793. block8:
  9794. movq $27, %rax
  9795. addq sum1, %rax
  9796. jmp mainconclusion
  9797. )
  9798. \end{lstlisting}
  9799. \end{minipage}
  9800. \end{center}
  9801. Recall that liveness analysis works backwards, starting at the end
  9802. of each function. For this example we could start with \code{block8}
  9803. because we know what is live at the beginning of the conclusion,
  9804. just \code{rax} and \code{rsp}. So the live-before set
  9805. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9806. %
  9807. Next we might try to analyze \code{block5} or \code{block7}, but
  9808. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9809. we are stuck.
  9810. The way out of this impasse comes from the realization that one can
  9811. perform liveness analysis starting with an empty live-after set to
  9812. compute an under-approximation of the live-before set. By
  9813. \emph{under-approximation}, we mean that the set only contains
  9814. variables that are really live, but it may be missing some. Next, the
  9815. under-approximations for each block can be improved by 1) updating the
  9816. live-after set for each block using the approximate live-before sets
  9817. from the other blocks and 2) perform liveness analysis again on each
  9818. block. In fact, by iterating this process, the under-approximations
  9819. eventually become the correct solutions!
  9820. %
  9821. This approach of iteratively analyzing a control-flow graph is
  9822. applicable to many static analysis problems and goes by the name
  9823. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9824. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9825. Washington.
  9826. Let us apply this approach to the above example. We use the empty set
  9827. for the initial live-before set for each block. Let $m_0$ be the
  9828. following mapping from label names to sets of locations (variables and
  9829. registers).
  9830. \begin{center}
  9831. \begin{lstlisting}
  9832. mainstart: {}
  9833. block5: {}
  9834. block7: {}
  9835. block8: {}
  9836. \end{lstlisting}
  9837. \end{center}
  9838. Using the above live-before approximations, we determine the
  9839. live-after for each block and then apply liveness analysis to each
  9840. block. This produces our next approximation $m_1$ of the live-before
  9841. sets.
  9842. \begin{center}
  9843. \begin{lstlisting}
  9844. mainstart: {}
  9845. block5: {i2}
  9846. block7: {i2, sum1}
  9847. block8: {rsp, sum1}
  9848. \end{lstlisting}
  9849. \end{center}
  9850. For the second round, the live-after for \code{mainstart} is the
  9851. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9852. liveness analysis for \code{mainstart} computes the empty set. The
  9853. live-after for \code{block5} is the union of the live-before sets for
  9854. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9855. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9856. sum1\}}. The live-after for \code{block7} is the live-before for
  9857. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9858. So the liveness analysis for \code{block7} remains \code{\{i2,
  9859. sum1\}}. Together these yield the following approximation $m_2$ of
  9860. the live-before sets.
  9861. \begin{center}
  9862. \begin{lstlisting}
  9863. mainstart: {}
  9864. block5: {i2, rsp, sum1}
  9865. block7: {i2, sum1}
  9866. block8: {rsp, sum1}
  9867. \end{lstlisting}
  9868. \end{center}
  9869. In the preceding iteration, only \code{block5} changed, so we can
  9870. limit our attention to \code{mainstart} and \code{block7}, the two
  9871. blocks that jump to \code{block5}. As a result, the live-before sets
  9872. for \code{mainstart} and \code{block7} are updated to include
  9873. \code{rsp}, yielding the following approximation $m_3$.
  9874. \begin{center}
  9875. \begin{lstlisting}
  9876. mainstart: {rsp}
  9877. block5: {i2, rsp, sum1}
  9878. block7: {i2, rsp, sum1}
  9879. block8: {rsp, sum1}
  9880. \end{lstlisting}
  9881. \end{center}
  9882. Because \code{block7} changed, we analyze \code{block5} once more, but
  9883. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9884. our approximations have converged, so $m_3$ is the solution.
  9885. This iteration process is guaranteed to converge to a solution by the
  9886. Kleene Fixed-Point Theorem, a general theorem about functions on
  9887. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9888. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9889. elements, a least element $\bot$ (pronounced bottom), and a join
  9890. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9891. ordering}\index{join}\footnote{Technically speaking, we will be
  9892. working with join semi-lattices.} When two elements are ordered $m_i
  9893. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9894. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9895. approximation than $m_i$. The bottom element $\bot$ represents the
  9896. complete lack of information, i.e., the worst approximation. The join
  9897. operator takes two lattice elements and combines their information,
  9898. i.e., it produces the least upper bound of the two.\index{least upper
  9899. bound}
  9900. A dataflow analysis typically involves two lattices: one lattice to
  9901. represent abstract states and another lattice that aggregates the
  9902. abstract states of all the blocks in the control-flow graph. For
  9903. liveness analysis, an abstract state is a set of locations. We form
  9904. the lattice $L$ by taking its elements to be sets of locations, the
  9905. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9906. set, and the join operator to be set union.
  9907. %
  9908. We form a second lattice $M$ by taking its elements to be mappings
  9909. from the block labels to sets of locations (elements of $L$). We
  9910. order the mappings point-wise, using the ordering of $L$. So given any
  9911. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9912. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9913. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9914. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9915. We can think of one iteration of liveness analysis as being a function
  9916. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9917. mapping.
  9918. \[
  9919. f(m_i) = m_{i+1}
  9920. \]
  9921. Next let us think for a moment about what a final solution $m_s$
  9922. should look like. If we perform liveness analysis using the solution
  9923. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9924. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9925. \[
  9926. f(m_s) = m_s
  9927. \]
  9928. Furthermore, the solution should only include locations that are
  9929. forced to be there by performing liveness analysis on the program, so
  9930. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9931. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9932. monotone (better inputs produce better outputs), then the least fixed
  9933. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9934. chain} obtained by starting at $\bot$ and iterating $f$ as
  9935. follows.\index{Kleene Fixed-Point Theorem}
  9936. \[
  9937. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9938. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9939. \]
  9940. When a lattice contains only finitely-long ascending chains, then
  9941. every Kleene chain tops out at some fixed point after a number of
  9942. iterations of $f$. So that fixed point is also a least upper
  9943. bound of the chain.
  9944. \[
  9945. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9946. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9947. \]
  9948. The liveness analysis is indeed a monotone function and the lattice
  9949. $M$ only has finitely-long ascending chains because there are only a
  9950. finite number of variables and blocks in the program. Thus we are
  9951. guaranteed that iteratively applying liveness analysis to all blocks
  9952. in the program will eventually produce the least fixed point solution.
  9953. Next let us consider dataflow analysis in general and discuss the
  9954. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9955. %
  9956. The algorithm has four parameters: the control-flow graph \code{G}, a
  9957. function \code{transfer} that applies the analysis to one block, the
  9958. \code{bottom} and \code{join} operator for the lattice of abstract
  9959. states. The algorithm begins by creating the bottom mapping,
  9960. represented by a hash table. It then pushes all of the nodes in the
  9961. control-flow graph onto the work list (a queue). The algorithm repeats
  9962. the \code{while} loop as long as there are items in the work list. In
  9963. each iteration, a node is popped from the work list and processed. The
  9964. \code{input} for the node is computed by taking the join of the
  9965. abstract states of all the predecessor nodes. The \code{transfer}
  9966. function is then applied to obtain the \code{output} abstract
  9967. state. If the output differs from the previous state for this block,
  9968. the mapping for this block is updated and its successor nodes are
  9969. pushed onto the work list.
  9970. \begin{figure}[tb]
  9971. \begin{lstlisting}
  9972. (define (analyze-dataflow G transfer bottom join)
  9973. (define mapping (make-hash))
  9974. (for ([v (in-vertices G)])
  9975. (dict-set! mapping v bottom))
  9976. (define worklist (make-queue))
  9977. (for ([v (in-vertices G)])
  9978. (enqueue! worklist v))
  9979. (define trans-G (transpose G))
  9980. (while (not (queue-empty? worklist))
  9981. (define node (dequeue! worklist))
  9982. (define input (for/fold ([state bottom])
  9983. ([pred (in-neighbors trans-G node)])
  9984. (join state (dict-ref mapping pred))))
  9985. (define output (transfer node input))
  9986. (cond [(not (equal? output (dict-ref mapping node)))
  9987. (dict-set! mapping node output)
  9988. (for ([v (in-neighbors G node)])
  9989. (enqueue! worklist v))]))
  9990. mapping)
  9991. \end{lstlisting}
  9992. \caption{Generic work list algorithm for dataflow analysis}
  9993. \label{fig:generic-dataflow}
  9994. \end{figure}
  9995. Having discussed the two complications that arise from adding support
  9996. for assignment and loops, we turn to discussing the one new compiler
  9997. pass and the significant changes to existing passes.
  9998. \section{Convert Assignments}
  9999. \label{sec:convert-assignments}
  10000. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10001. the combination of assignments and lexically-scoped functions requires
  10002. that we box those variables that are both assigned-to and that appear
  10003. free inside a \code{lambda}. The purpose of the
  10004. \code{convert-assignments} pass is to carry out that transformation.
  10005. We recommend placing this pass after \code{uniquify} but before
  10006. \code{reveal-functions}.
  10007. Consider again the first example from
  10008. Section~\ref{sec:assignment-scoping}:
  10009. \begin{lstlisting}
  10010. (let ([x 0])
  10011. (let ([y 0])
  10012. (let ([z 20])
  10013. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10014. (begin
  10015. (set! x 10)
  10016. (set! y 12)
  10017. (f y))))))
  10018. \end{lstlisting}
  10019. The variables \code{x} and \code{y} are assigned-to. The variables
  10020. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10021. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10022. The boxing of \code{x} consists of three transformations: initialize
  10023. \code{x} with a vector, replace reads from \code{x} with
  10024. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10025. \code{vector-set!}. The output of \code{convert-assignments} for this
  10026. example is as follows.
  10027. \begin{lstlisting}
  10028. (define (main) : Integer
  10029. (let ([x0 (vector 0)])
  10030. (let ([y1 0])
  10031. (let ([z2 20])
  10032. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10033. (+ a3 (+ (vector-ref x0 0) z2)))])
  10034. (begin
  10035. (vector-set! x0 0 10)
  10036. (set! y1 12)
  10037. (f4 y1)))))))
  10038. \end{lstlisting}
  10039. \paragraph{Assigned \& Free}
  10040. We recommend defining an auxiliary function named
  10041. \code{assigned\&free} that takes an expression and simultaneously
  10042. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10043. that occur free within lambda's, and 3) a new version of the
  10044. expression that records which bound variables occurred in the
  10045. intersection of $A$ and $F$. You can use the struct
  10046. \code{AssignedFree} to do this. Consider the case for
  10047. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10048. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10049. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10050. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10051. \begin{lstlisting}
  10052. (Let |$x$| |$rhs$| |$body$|)
  10053. |$\Rightarrow$|
  10054. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10055. \end{lstlisting}
  10056. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10057. The set of assigned variables for this \code{Let} is
  10058. $A_r \cup (A_b - \{x\})$
  10059. and the set of variables free in lambda's is
  10060. $F_r \cup (F_b - \{x\})$.
  10061. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10062. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10063. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10064. and $F_r$.
  10065. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10066. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10067. recursively processing \itm{body}. Wrap each of parameter that occurs
  10068. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10069. Let $P$ be the set of parameter names in \itm{params}. The result is
  10070. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10071. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10072. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10073. \paragraph{Convert Assignments}
  10074. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10075. functions for expressions and definitions. The function for
  10076. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10077. set of assigned-and-free variables (obtained from the result of
  10078. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10079. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10080. \code{vector-ref}.
  10081. \begin{lstlisting}
  10082. (Var |$x$|)
  10083. |$\Rightarrow$|
  10084. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10085. \end{lstlisting}
  10086. %
  10087. In the case for $\LET{\LP\code{AssignedFree}\,
  10088. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10089. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10090. \itm{body'} but with $x$ added to the set of assigned-and-free
  10091. variables. Translate the let-expression as follows to bind $x$ to a
  10092. boxed value.
  10093. \begin{lstlisting}
  10094. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10095. |$\Rightarrow$|
  10096. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10097. \end{lstlisting}
  10098. %
  10099. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10100. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10101. variables, translate the \code{set!} into a \code{vector-set!}
  10102. as follows.
  10103. \begin{lstlisting}
  10104. (SetBang |$x$| |$\itm{rhs}$|)
  10105. |$\Rightarrow$|
  10106. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10107. \end{lstlisting}
  10108. %
  10109. The case for \code{Lambda} is non-trivial, but it is similar to the
  10110. case for function definitions, which we discuss next.
  10111. The auxiliary function for definitions, \code{cnvt-assign-def},
  10112. applies assignment conversion to function definitions.
  10113. We translate a function definition as follows.
  10114. \begin{lstlisting}
  10115. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10116. |$\Rightarrow$|
  10117. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10118. \end{lstlisting}
  10119. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10120. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10121. \code{assigned\&free} on $\itm{body_1}$.
  10122. Let $P$ be the parameter names in \itm{params}.
  10123. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10124. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10125. as the set of assigned-and-free variables.
  10126. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10127. in a sequence of let-expressions that box the parameters
  10128. that are in $A_b \cap F_b$.
  10129. %
  10130. Regarding \itm{params'}, change the names of the parameters that are
  10131. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10132. variables can retain the original names). Recall the second example in
  10133. Section~\ref{sec:assignment-scoping} involving a counter
  10134. abstraction. The following is the output of assignment version for
  10135. function \code{f}.
  10136. \begin{lstlisting}
  10137. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10138. (vector
  10139. (lambda: () : Integer x1)
  10140. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10141. |$\Rightarrow$|
  10142. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10143. (let ([x1 (vector param_x1)])
  10144. (vector (lambda: () : Integer (vector-ref x1 0))
  10145. (lambda: () : Void
  10146. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10147. \end{lstlisting}
  10148. \section{Remove Complex Operands}
  10149. \label{sec:rco-loop}
  10150. The three new language forms, \code{while}, \code{set!}, and
  10151. \code{begin} are all complex expressions and their subexpressions are
  10152. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10153. output language \LangFunANF{} of this pass.
  10154. \begin{figure}[tp]
  10155. \centering
  10156. \fbox{
  10157. \begin{minipage}{0.96\textwidth}
  10158. \small
  10159. \[
  10160. \begin{array}{rcl}
  10161. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10162. \mid \VOID{} } \\
  10163. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10164. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10165. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10166. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10167. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10168. \end{array}
  10169. \]
  10170. \end{minipage}
  10171. }
  10172. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10173. \label{fig:Rwhile-anf-syntax}
  10174. \end{figure}
  10175. As usual, when a complex expression appears in a grammar position that
  10176. needs to be atomic, such as the argument of a primitive operator, we
  10177. must introduce a temporary variable and bind it to the complex
  10178. expression. This approach applies, unchanged, to handle the new
  10179. language forms. For example, in the following code there are two
  10180. \code{begin} expressions appearing as arguments to \code{+}. The
  10181. output of \code{rco-exp} is shown below, in which the \code{begin}
  10182. expressions have been bound to temporary variables. Recall that
  10183. \code{let} expressions in \LangLoopANF{} are allowed to have
  10184. arbitrary expressions in their right-hand-side expression, so it is
  10185. fine to place \code{begin} there.
  10186. \begin{lstlisting}
  10187. (let ([x0 10])
  10188. (let ([y1 0])
  10189. (+ (+ (begin (set! y1 (read)) x0)
  10190. (begin (set! x0 (read)) y1))
  10191. x0)))
  10192. |$\Rightarrow$|
  10193. (let ([x0 10])
  10194. (let ([y1 0])
  10195. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10196. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10197. (let ([tmp4 (+ tmp2 tmp3)])
  10198. (+ tmp4 x0))))))
  10199. \end{lstlisting}
  10200. \section{Explicate Control and \LangCLoop{}}
  10201. \label{sec:explicate-loop}
  10202. Recall that in the \code{explicate-control} pass we define one helper
  10203. function for each kind of position in the program. For the \LangVar{}
  10204. language of integers and variables we needed kinds of positions:
  10205. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10206. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10207. yet another kind of position: effect position. Except for the last
  10208. subexpression, the subexpressions inside a \code{begin} are evaluated
  10209. only for their effect. Their result values are discarded. We can
  10210. generate better code by taking this fact into account.
  10211. The output language of \code{explicate-control} is \LangCLoop{}
  10212. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10213. \LangCLam{}. The only syntactic difference is that \code{Call},
  10214. \code{vector-set!}, and \code{read} may also appear as statements.
  10215. The most significant difference between \LangCLam{} and \LangCLoop{}
  10216. is that the control-flow graphs of the later may contain cycles.
  10217. \begin{figure}[tp]
  10218. \fbox{
  10219. \begin{minipage}{0.96\textwidth}
  10220. \small
  10221. \[
  10222. \begin{array}{lcl}
  10223. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10224. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10225. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10226. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10227. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10228. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10229. \end{array}
  10230. \]
  10231. \end{minipage}
  10232. }
  10233. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10234. \label{fig:c7-syntax}
  10235. \end{figure}
  10236. The new auxiliary function \code{explicate-effect} takes an expression
  10237. (in an effect position) and a promise of a continuation block. The
  10238. function returns a promise for a $\Tail$ that includes the generated
  10239. code for the input expression followed by the continuation block. If
  10240. the expression is obviously pure, that is, never causes side effects,
  10241. then the expression can be removed, so the result is just the
  10242. continuation block.
  10243. %
  10244. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10245. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10246. the loop. Recursively process the \itm{body} (in effect position)
  10247. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10248. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10249. \itm{body'} as the then-branch and the continuation block as the
  10250. else-branch. The result should be added to the control-flow graph with
  10251. the label \itm{loop}. The result for the whole \code{while} loop is a
  10252. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10253. added to the control-flow graph if the loop is indeed used, which can
  10254. be accomplished using \code{delay}.
  10255. The auxiliary functions for tail, assignment, and predicate positions
  10256. need to be updated. The three new language forms, \code{while},
  10257. \code{set!}, and \code{begin}, can appear in assignment and tail
  10258. positions. Only \code{begin} may appear in predicate positions; the
  10259. other two have result type \code{Void}.
  10260. \section{Select Instructions}
  10261. \label{sec:select-instructions-loop}
  10262. Only three small additions are needed in the
  10263. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10264. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10265. stand-alone statements instead of only appearing on the right-hand
  10266. side of an assignment statement. The code generation is nearly
  10267. identical; just leave off the instruction for moving the result into
  10268. the left-hand side.
  10269. \section{Register Allocation}
  10270. \label{sec:register-allocation-loop}
  10271. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10272. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10273. which complicates the liveness analysis needed for register
  10274. allocation.
  10275. \subsection{Liveness Analysis}
  10276. \label{sec:liveness-analysis-r8}
  10277. We recommend using the generic \code{analyze-dataflow} function that
  10278. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10279. perform liveness analysis, replacing the code in
  10280. \code{uncover-live-CFG} that processed the basic blocks in topological
  10281. order (Section~\ref{sec:liveness-analysis-Rif}).
  10282. The \code{analyze-dataflow} function has four parameters.
  10283. \begin{enumerate}
  10284. \item The first parameter \code{G} should be a directed graph from the
  10285. \code{racket/graph} package (see the sidebar in
  10286. Section~\ref{sec:build-interference}) that represents the
  10287. control-flow graph.
  10288. \item The second parameter \code{transfer} is a function that applies
  10289. liveness analysis to a basic block. It takes two parameters: the
  10290. label for the block to analyze and the live-after set for that
  10291. block. The transfer function should return the live-before set for
  10292. the block. Also, as a side-effect, it should update the block's
  10293. $\itm{info}$ with the liveness information for each instruction. To
  10294. implement the \code{transfer} function, you should be able to reuse
  10295. the code you already have for analyzing basic blocks.
  10296. \item The third and fourth parameters of \code{analyze-dataflow} are
  10297. \code{bottom} and \code{join} for the lattice of abstract states,
  10298. i.e. sets of locations. The bottom of the lattice is the empty set
  10299. \code{(set)} and the join operator is \code{set-union}.
  10300. \end{enumerate}
  10301. \begin{figure}[p]
  10302. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10303. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10304. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10305. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10306. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10307. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10308. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10309. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10310. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10311. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10312. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10313. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10314. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10315. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10316. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10317. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10318. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10319. %% \path[->,bend left=15] (Rfun) edge [above] node
  10320. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10321. \path[->,bend left=15] (Rfun) edge [above] node
  10322. {\ttfamily\footnotesize shrink} (Rfun-2);
  10323. \path[->,bend left=15] (Rfun-2) edge [above] node
  10324. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10325. \path[->,bend left=15] (Rfun-3) edge [above] node
  10326. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10327. \path[->,bend left=15] (Rfun-4) edge [right] node
  10328. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10329. \path[->,bend left=15] (F1-1) edge [below] node
  10330. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10331. \path[->,bend right=15] (F1-2) edge [above] node
  10332. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10333. \path[->,bend right=15] (F1-3) edge [above] node
  10334. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10335. \path[->,bend right=15] (F1-4) edge [above] node
  10336. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10337. \path[->,bend right=15] (F1-5) edge [right] node
  10338. {\ttfamily\footnotesize explicate-control} (C3-2);
  10339. \path[->,bend left=15] (C3-2) edge [left] node
  10340. {\ttfamily\footnotesize select-instr.} (x86-2);
  10341. \path[->,bend right=15] (x86-2) edge [left] node
  10342. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10343. \path[->,bend right=15] (x86-2-1) edge [below] node
  10344. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10345. \path[->,bend right=15] (x86-2-2) edge [left] node
  10346. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10347. \path[->,bend left=15] (x86-3) edge [above] node
  10348. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10349. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10350. \end{tikzpicture}
  10351. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10352. \label{fig:Rwhile-passes}
  10353. \end{figure}
  10354. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10355. for the compilation of \LangLoop{}.
  10356. \section{Challenge: Arrays}
  10357. \label{sec:arrays}
  10358. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10359. elements whose length is determined at compile-time and where each
  10360. element of a tuple may have a different type (they are
  10361. heterogeous). This challenge is also about sequences, but this time
  10362. the length is determined at run-time and all the elements have the same
  10363. type (they are homogeneous). We use the term ``array'' for this later
  10364. kind of sequence.
  10365. The Racket language does not distinguish between tuples and arrays,
  10366. they are both represented by vectors. However, Typed Racket
  10367. distinguishes between tuples and arrays: the \code{Vector} type is for
  10368. tuples and the \code{Vectorof} type is for arrays.
  10369. %
  10370. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10371. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10372. and the \code{make-vector} primitive operator for creating an array,
  10373. whose arguments are the length of the array and an initial value for
  10374. all the elements in the array. The \code{vector-length},
  10375. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10376. for tuples become overloaded for use with arrays.
  10377. %
  10378. We also include integer multiplication in \LangArray{}, as it is
  10379. useful in many examples involving arrays such as computing the
  10380. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10381. \begin{figure}[tp]
  10382. \centering
  10383. \fbox{
  10384. \begin{minipage}{0.96\textwidth}
  10385. \small
  10386. \[
  10387. \begin{array}{lcl}
  10388. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10389. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10390. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10391. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10392. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10393. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10394. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10395. \mid \LP\key{not}\;\Exp\RP } \\
  10396. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10397. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10398. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10399. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10400. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10401. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10402. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10403. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10404. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10405. \mid \CWHILE{\Exp}{\Exp} } \\
  10406. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10407. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10408. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10409. \end{array}
  10410. \]
  10411. \end{minipage}
  10412. }
  10413. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10414. \label{fig:Rvecof-concrete-syntax}
  10415. \end{figure}
  10416. \begin{figure}[tp]
  10417. \begin{lstlisting}
  10418. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10419. [n : Integer]) : Integer
  10420. (let ([i 0])
  10421. (let ([prod 0])
  10422. (begin
  10423. (while (< i n)
  10424. (begin
  10425. (set! prod (+ prod (* (vector-ref A i)
  10426. (vector-ref B i))))
  10427. (set! i (+ i 1))
  10428. ))
  10429. prod))))
  10430. (let ([A (make-vector 2 2)])
  10431. (let ([B (make-vector 2 3)])
  10432. (+ (inner-product A B 2)
  10433. 30)))
  10434. \end{lstlisting}
  10435. \caption{Example program that computes the inner-product.}
  10436. \label{fig:inner-product}
  10437. \end{figure}
  10438. The type checker for \LangArray{} is define in
  10439. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10440. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10441. of the intializing expression. The length expression is required to
  10442. have type \code{Integer}. The type checking of the operators
  10443. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10444. updated to handle the situation where the vector has type
  10445. \code{Vectorof}. In these cases we translate the operators to their
  10446. \code{vectorof} form so that later passes can easily distinguish
  10447. between operations on tuples versus arrays. We override the
  10448. \code{operator-types} method to provide the type signature for
  10449. multiplication: it takes two integers and returns an integer. To
  10450. support injection and projection of arrays to the \code{Any} type
  10451. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10452. predicate.
  10453. \begin{figure}[tbp]
  10454. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10455. (define type-check-Rvecof-class
  10456. (class type-check-Rwhile-class
  10457. (super-new)
  10458. (inherit check-type-equal?)
  10459. (define/override (flat-ty? ty)
  10460. (match ty
  10461. ['(Vectorof Any) #t]
  10462. [else (super flat-ty? ty)]))
  10463. (define/override (operator-types)
  10464. (append '((* . ((Integer Integer) . Integer)))
  10465. (super operator-types)))
  10466. (define/override (type-check-exp env)
  10467. (lambda (e)
  10468. (define recur (type-check-exp env))
  10469. (match e
  10470. [(Prim 'make-vector (list e1 e2))
  10471. (define-values (e1^ t1) (recur e1))
  10472. (define-values (e2^ elt-type) (recur e2))
  10473. (define vec-type `(Vectorof ,elt-type))
  10474. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10475. vec-type)]
  10476. [(Prim 'vector-ref (list e1 e2))
  10477. (define-values (e1^ t1) (recur e1))
  10478. (define-values (e2^ t2) (recur e2))
  10479. (match* (t1 t2)
  10480. [(`(Vectorof ,elt-type) 'Integer)
  10481. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10482. [(other wise) ((super type-check-exp env) e)])]
  10483. [(Prim 'vector-set! (list e1 e2 e3) )
  10484. (define-values (e-vec t-vec) (recur e1))
  10485. (define-values (e2^ t2) (recur e2))
  10486. (define-values (e-arg^ t-arg) (recur e3))
  10487. (match t-vec
  10488. [`(Vectorof ,elt-type)
  10489. (check-type-equal? elt-type t-arg e)
  10490. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10491. [else ((super type-check-exp env) e)])]
  10492. [(Prim 'vector-length (list e1))
  10493. (define-values (e1^ t1) (recur e1))
  10494. (match t1
  10495. [`(Vectorof ,t)
  10496. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10497. [else ((super type-check-exp env) e)])]
  10498. [else ((super type-check-exp env) e)])))
  10499. ))
  10500. (define (type-check-Rvecof p)
  10501. (send (new type-check-Rvecof-class) type-check-program p))
  10502. \end{lstlisting}
  10503. \caption{Type checker for the \LangArray{} language.}
  10504. \label{fig:type-check-Rvecof}
  10505. \end{figure}
  10506. The interpreter for \LangArray{} is defined in
  10507. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10508. implemented with Racket's \code{make-vector} function and
  10509. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10510. integers.
  10511. \begin{figure}[tbp]
  10512. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10513. (define interp-Rvecof-class
  10514. (class interp-Rwhile-class
  10515. (super-new)
  10516. (define/override (interp-op op)
  10517. (verbose "Rvecof/interp-op" op)
  10518. (match op
  10519. ['make-vector make-vector]
  10520. ['* fx*]
  10521. [else (super interp-op op)]))
  10522. ))
  10523. (define (interp-Rvecof p)
  10524. (send (new interp-Rvecof-class) interp-program p))
  10525. \end{lstlisting}
  10526. \caption{Interpreter for \LangArray{}.}
  10527. \label{fig:interp-Rvecof}
  10528. \end{figure}
  10529. \subsection{Data Representation}
  10530. \label{sec:array-rep}
  10531. Just like tuples, we store arrays on the heap which means that the
  10532. garbage collector will need to inspect arrays. An immediate thought is
  10533. to use the same representation for arrays that we use for tuples.
  10534. However, we limit tuples to a length of $50$ so that their length and
  10535. pointer mask can fit into the 64-bit tag at the beginning of each
  10536. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10537. millions of elements, so we need more bits to store the length.
  10538. However, because arrays are homogeneous, we only need $1$ bit for the
  10539. pointer mask instead of one bit per array elements. Finally, the
  10540. garbage collector will need to be able to distinguish between tuples
  10541. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10542. arrive at the following layout for the 64-bit tag at the beginning of
  10543. an array:
  10544. \begin{itemize}
  10545. \item The right-most bit is the forwarding bit, just like in a tuple.
  10546. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10547. it is not.
  10548. \item The next bit to the left is the pointer mask. A $0$ indicates
  10549. that none of the elements are pointers to the heap and a $1$
  10550. indicates that all of the elements are pointers.
  10551. \item The next $61$ bits store the length of the array.
  10552. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10553. array ($1$).
  10554. \end{itemize}
  10555. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10556. differentiate the kinds of values that have been injected into the
  10557. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10558. to indicate that the value is an array.
  10559. In the following subsections we provide hints regarding how to update
  10560. the passes to handle arrays.
  10561. \subsection{Reveal Casts}
  10562. The array-access operators \code{vectorof-ref} and
  10563. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10564. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10565. that the type checker cannot tell whether the index will be in bounds,
  10566. so the bounds check must be performed at run time. Recall that the
  10567. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10568. an \code{If} arround a vector reference for update to check whether
  10569. the index is less than the length. You should do the same for
  10570. \code{vectorof-ref} and \code{vectorof-set!} .
  10571. In addition, the handling of the \code{any-vector} operators in
  10572. \code{reveal-casts} needs to be updated to account for arrays that are
  10573. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10574. generated code should test whether the tag is for tuples (\code{010})
  10575. or arrays (\code{110}) and then dispatch to either
  10576. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10577. we add a case in \code{select-instructions} to generate the
  10578. appropriate instructions for accessing the array length from the
  10579. header of an array.
  10580. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10581. the generated code needs to check that the index is less than the
  10582. vector length, so like the code for \code{any-vector-length}, check
  10583. the tag to determine whether to use \code{any-vector-length} or
  10584. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10585. is complete, the generated code can use \code{any-vector-ref} and
  10586. \code{any-vector-set!} for both tuples and arrays because the
  10587. instructions used for those operators do not look at the tag at the
  10588. front of the tuple or array.
  10589. \subsection{Expose Allocation}
  10590. This pass should translate the \code{make-vector} operator into
  10591. lower-level operations. In particular, the new AST node
  10592. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10593. length specified by the $\Exp$, but does not initialize the elements
  10594. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10595. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10596. element type for the array. Regarding the initialization of the array,
  10597. we recommend generated a \code{while} loop that uses
  10598. \code{vector-set!} to put the initializing value into every element of
  10599. the array.
  10600. \subsection{Remove Complex Operands}
  10601. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10602. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10603. complex and its subexpression must be atomic.
  10604. \subsection{Explicate Control}
  10605. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10606. \code{explicate-assign}.
  10607. \subsection{Select Instructions}
  10608. Generate instructions for \code{AllocateArray} similar to those for
  10609. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10610. that the tag at the front of the array should instead use the
  10611. representation discussed in Section~\ref{sec:array-rep}.
  10612. Regarding \code{vectorof-length}, extract the length from the tag
  10613. according to the representation discussed in
  10614. Section~\ref{sec:array-rep}.
  10615. The instructions generated for \code{vectorof-ref} differ from those
  10616. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10617. that the index is not a constant so the offset must be computed at
  10618. runtime, similar to the instructions generated for
  10619. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10620. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10621. appear in an assignment and as a stand-alone statement, so make sure
  10622. to handle both situations in this pass.
  10623. Finally, the instructions for \code{any-vectorof-length} should be
  10624. similar to those for \code{vectorof-length}, except that one must
  10625. first project the array by writing zeroes into the $3$-bit tag
  10626. \begin{exercise}\normalfont
  10627. Implement a compiler for the \LangArray{} language by extending your
  10628. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10629. programs, including the one in Figure~\ref{fig:inner-product} and also
  10630. a program that multiplies two matrices. Note that matrices are
  10631. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10632. arrays by laying out each row in the array, one after the next.
  10633. \end{exercise}
  10634. % Further Reading: dataflow analysis
  10635. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10636. \chapter{Gradual Typing}
  10637. \label{ch:Rgrad}
  10638. \index{gradual typing}
  10639. This chapter studies a language, \LangGrad{}, in which the programmer
  10640. can choose between static and dynamic type checking in different parts
  10641. of a program, thereby mixing the statically typed \LangLoop{} language
  10642. with the dynamically typed \LangDyn{}. There are several approaches to
  10643. mixing static and dynamic typing, including multi-language
  10644. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10645. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10646. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10647. programmer controls the amount of static versus dynamic checking by
  10648. adding or removing type annotations on parameters and
  10649. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10650. %
  10651. The concrete syntax of \LangGrad{} is defined in
  10652. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10653. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10654. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10655. non-terminals that make type annotations optional. The return types
  10656. are not optional in the abstract syntax; the parser fills in
  10657. \code{Any} when the return type is not specified in the concrete
  10658. syntax.
  10659. \begin{figure}[tp]
  10660. \centering
  10661. \fbox{
  10662. \begin{minipage}{0.96\textwidth}
  10663. \small
  10664. \[
  10665. \begin{array}{lcl}
  10666. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10667. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10668. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10669. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10670. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10671. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10672. \mid (\key{and}\;\Exp\;\Exp)
  10673. \mid (\key{or}\;\Exp\;\Exp)
  10674. \mid (\key{not}\;\Exp) } \\
  10675. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10676. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10677. (\key{vector-ref}\;\Exp\;\Int)} \\
  10678. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10679. \mid (\Exp \; \Exp\ldots) } \\
  10680. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10681. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10682. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10683. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10684. \mid \CWHILE{\Exp}{\Exp} } \\
  10685. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10686. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10687. \end{array}
  10688. \]
  10689. \end{minipage}
  10690. }
  10691. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10692. \label{fig:Rgrad-concrete-syntax}
  10693. \end{figure}
  10694. \begin{figure}[tp]
  10695. \centering
  10696. \fbox{
  10697. \begin{minipage}{0.96\textwidth}
  10698. \small
  10699. \[
  10700. \begin{array}{lcl}
  10701. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10702. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10703. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10704. &\mid& \gray{ \BOOL{\itm{bool}}
  10705. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10706. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10707. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10708. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10709. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10710. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10711. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10712. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10713. \end{array}
  10714. \]
  10715. \end{minipage}
  10716. }
  10717. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10718. \label{fig:Rgrad-syntax}
  10719. \end{figure}
  10720. Both the type checker and the interpreter for \LangGrad{} require some
  10721. interesting changes to enable gradual typing, which we discuss in the
  10722. next two sections in the context of the \code{map-vec} example from
  10723. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10724. revised the \code{map-vec} example, omitting the type annotations from
  10725. the \code{add1} function.
  10726. \begin{figure}[btp]
  10727. % gradual_test_9.rkt
  10728. \begin{lstlisting}
  10729. (define (map-vec [f : (Integer -> Integer)]
  10730. [v : (Vector Integer Integer)])
  10731. : (Vector Integer Integer)
  10732. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10733. (define (add1 x) (+ x 1))
  10734. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10735. \end{lstlisting}
  10736. \caption{A partially-typed version of the \code{map-vec} example.}
  10737. \label{fig:gradual-map-vec}
  10738. \end{figure}
  10739. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10740. \label{sec:gradual-type-check}
  10741. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10742. parameter and return types. For example, the \code{x} parameter of
  10743. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10744. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10745. consider the \code{+} operator inside \code{add1}. It expects both
  10746. arguments to have type \code{Integer}, but its first argument \code{x}
  10747. has type \code{Any}. In a gradually typed language, such differences
  10748. are allowed so long as the types are \emph{consistent}, that is, they
  10749. are equal except in places where there is an \code{Any} type. The type
  10750. \code{Any} is consistent with every other type.
  10751. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10752. \begin{figure}[tbp]
  10753. \begin{lstlisting}
  10754. (define/public (consistent? t1 t2)
  10755. (match* (t1 t2)
  10756. [('Integer 'Integer) #t]
  10757. [('Boolean 'Boolean) #t]
  10758. [('Void 'Void) #t]
  10759. [('Any t2) #t]
  10760. [(t1 'Any) #t]
  10761. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10762. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10763. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10764. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10765. (consistent? rt1 rt2))]
  10766. [(other wise) #f]))
  10767. \end{lstlisting}
  10768. \caption{The consistency predicate on types.}
  10769. \label{fig:consistent}
  10770. \end{figure}
  10771. Returning to the \code{map-vec} example of
  10772. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10773. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10774. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10775. because the two types are consistent. In particular, \code{->} is
  10776. equal to \code{->} and because \code{Any} is consistent with
  10777. \code{Integer}.
  10778. Next consider a program with an error, such as applying the
  10779. \code{map-vec} to a function that sometimes returns a Boolean, as
  10780. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10781. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10782. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10783. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10784. Integer)}. One might say that a gradual type checker is optimistic
  10785. in that it accepts programs that might execute without a runtime type
  10786. error.
  10787. %
  10788. Unfortunately, running this program with input \code{1} triggers an
  10789. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10790. performs checking at runtime to ensure the integrity of the static
  10791. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10792. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10793. new \code{Cast} form that is inserted by the type checker. Thus, the
  10794. output of the type checker is a program in the \LangCast{} language, which
  10795. adds \code{Cast} to \LangLoop{}, as shown in
  10796. Figure~\ref{fig:Rgrad-prime-syntax}.
  10797. \begin{figure}[tp]
  10798. \centering
  10799. \fbox{
  10800. \begin{minipage}{0.96\textwidth}
  10801. \small
  10802. \[
  10803. \begin{array}{lcl}
  10804. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10805. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10806. \end{array}
  10807. \]
  10808. \end{minipage}
  10809. }
  10810. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10811. \label{fig:Rgrad-prime-syntax}
  10812. \end{figure}
  10813. \begin{figure}[tbp]
  10814. \begin{lstlisting}
  10815. (define (map-vec [f : (Integer -> Integer)]
  10816. [v : (Vector Integer Integer)])
  10817. : (Vector Integer Integer)
  10818. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10819. (define (add1 x) (+ x 1))
  10820. (define (true) #t)
  10821. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10822. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10823. \end{lstlisting}
  10824. \caption{A variant of the \code{map-vec} example with an error.}
  10825. \label{fig:map-vec-maybe-add1}
  10826. \end{figure}
  10827. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10828. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10829. inserted every time the type checker sees two types that are
  10830. consistent but not equal. In the \code{add1} function, \code{x} is
  10831. cast to \code{Integer} and the result of the \code{+} is cast to
  10832. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10833. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10834. \begin{figure}[btp]
  10835. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10836. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10837. : (Vector Integer Integer)
  10838. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10839. (define (add1 [x : Any]) : Any
  10840. (cast (+ (cast x Any Integer) 1) Integer Any))
  10841. (define (true) : Any (cast #t Boolean Any))
  10842. (define (maybe-add1 [x : Any]) : Any
  10843. (if (eq? 0 (read)) (add1 x) (true)))
  10844. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10845. (vector 0 41)) 0)
  10846. \end{lstlisting}
  10847. \caption{Output of type checking \code{map-vec}
  10848. and \code{maybe-add1}.}
  10849. \label{fig:map-vec-cast}
  10850. \end{figure}
  10851. The type checker for \LangGrad{} is defined in
  10852. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10853. and \ref{fig:type-check-Rgradual-3}.
  10854. \begin{figure}[tbp]
  10855. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10856. (define type-check-gradual-class
  10857. (class type-check-Rwhile-class
  10858. (super-new)
  10859. (inherit operator-types type-predicates)
  10860. (define/override (type-check-exp env)
  10861. (lambda (e)
  10862. (define recur (type-check-exp env))
  10863. (match e
  10864. [(Prim 'vector-length (list e1))
  10865. (define-values (e1^ t) (recur e1))
  10866. (match t
  10867. [`(Vector ,ts ...)
  10868. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10869. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10870. [(Prim 'vector-ref (list e1 e2))
  10871. (define-values (e1^ t1) (recur e1))
  10872. (define-values (e2^ t2) (recur e2))
  10873. (check-consistent? t2 'Integer e)
  10874. (match t1
  10875. [`(Vector ,ts ...)
  10876. (match e2^
  10877. [(Int i)
  10878. (unless (and (0 . <= . i) (i . < . (length ts)))
  10879. (error 'type-check "invalid index ~a in ~a" i e))
  10880. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10881. [else (define e1^^ (make-cast e1^ t1 'Any))
  10882. (define e2^^ (make-cast e2^ t2 'Integer))
  10883. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10884. ['Any
  10885. (define e2^^ (make-cast e2^ t2 'Integer))
  10886. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10887. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10888. [(Prim 'vector-set! (list e1 e2 e3) )
  10889. (define-values (e1^ t1) (recur e1))
  10890. (define-values (e2^ t2) (recur e2))
  10891. (define-values (e3^ t3) (recur e3))
  10892. (check-consistent? t2 'Integer e)
  10893. (match t1
  10894. [`(Vector ,ts ...)
  10895. (match e2^
  10896. [(Int i)
  10897. (unless (and (0 . <= . i) (i . < . (length ts)))
  10898. (error 'type-check "invalid index ~a in ~a" i e))
  10899. (check-consistent? (list-ref ts i) t3 e)
  10900. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10901. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10902. [else
  10903. (define e1^^ (make-cast e1^ t1 'Any))
  10904. (define e2^^ (make-cast e2^ t2 'Integer))
  10905. (define e3^^ (make-cast e3^ t3 'Any))
  10906. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10907. ['Any
  10908. (define e2^^ (make-cast e2^ t2 'Integer))
  10909. (define e3^^ (make-cast e3^ t3 'Any))
  10910. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10911. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10912. \end{lstlisting}
  10913. \caption{Type checker for the \LangGrad{} language, part 1.}
  10914. \label{fig:type-check-Rgradual-1}
  10915. \end{figure}
  10916. \begin{figure}[tbp]
  10917. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10918. [(Prim 'eq? (list e1 e2))
  10919. (define-values (e1^ t1) (recur e1))
  10920. (define-values (e2^ t2) (recur e2))
  10921. (check-consistent? t1 t2 e)
  10922. (define T (meet t1 t2))
  10923. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10924. 'Boolean)]
  10925. [(Prim 'not (list e1))
  10926. (define-values (e1^ t1) (recur e1))
  10927. (match t1
  10928. ['Any
  10929. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10930. (Bool #t) (Bool #f)))]
  10931. [else
  10932. (define-values (t-ret new-es^)
  10933. (type-check-op 'not (list t1) (list e1^) e))
  10934. (values (Prim 'not new-es^) t-ret)])]
  10935. [(Prim 'and (list e1 e2))
  10936. (recur (If e1 e2 (Bool #f)))]
  10937. [(Prim 'or (list e1 e2))
  10938. (define tmp (gensym 'tmp))
  10939. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10940. [(Prim op es)
  10941. #:when (not (set-member? explicit-prim-ops op))
  10942. (define-values (new-es ts)
  10943. (for/lists (exprs types) ([e es])
  10944. (recur e)))
  10945. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10946. (values (Prim op new-es^) t-ret)]
  10947. [(If e1 e2 e3)
  10948. (define-values (e1^ T1) (recur e1))
  10949. (define-values (e2^ T2) (recur e2))
  10950. (define-values (e3^ T3) (recur e3))
  10951. (check-consistent? T2 T3 e)
  10952. (match T1
  10953. ['Boolean
  10954. (define Tif (join T2 T3))
  10955. (values (If e1^ (make-cast e2^ T2 Tif)
  10956. (make-cast e3^ T3 Tif)) Tif)]
  10957. ['Any
  10958. (define Tif (meet T2 T3))
  10959. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10960. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10961. Tif)]
  10962. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10963. [(HasType e1 T)
  10964. (define-values (e1^ T1) (recur e1))
  10965. (check-consistent? T1 T)
  10966. (values (make-cast e1^ T1 T) T)]
  10967. [(SetBang x e1)
  10968. (define-values (e1^ T1) (recur e1))
  10969. (define varT (dict-ref env x))
  10970. (check-consistent? T1 varT e)
  10971. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10972. [(WhileLoop e1 e2)
  10973. (define-values (e1^ T1) (recur e1))
  10974. (check-consistent? T1 'Boolean e)
  10975. (define-values (e2^ T2) ((type-check-exp env) e2))
  10976. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10977. \end{lstlisting}
  10978. \caption{Type checker for the \LangGrad{} language, part 2.}
  10979. \label{fig:type-check-Rgradual-2}
  10980. \end{figure}
  10981. \begin{figure}[tbp]
  10982. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10983. [(Apply e1 e2s)
  10984. (define-values (e1^ T1) (recur e1))
  10985. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10986. (match T1
  10987. [`(,T1ps ... -> ,T1rt)
  10988. (for ([T2 T2s] [Tp T1ps])
  10989. (check-consistent? T2 Tp e))
  10990. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10991. (make-cast e2 src tgt)))
  10992. (values (Apply e1^ e2s^^) T1rt)]
  10993. [`Any
  10994. (define e1^^ (make-cast e1^ 'Any
  10995. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10996. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10997. (make-cast e2 src 'Any)))
  10998. (values (Apply e1^^ e2s^^) 'Any)]
  10999. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11000. [(Lambda params Tr e1)
  11001. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11002. (match p
  11003. [`[,x : ,T] (values x T)]
  11004. [(? symbol? x) (values x 'Any)])))
  11005. (define-values (e1^ T1)
  11006. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11007. (check-consistent? Tr T1 e)
  11008. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11009. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11010. [else ((super type-check-exp env) e)]
  11011. )))
  11012. \end{lstlisting}
  11013. \caption{Type checker for the \LangGrad{} language, part 3.}
  11014. \label{fig:type-check-Rgradual-3}
  11015. \end{figure}
  11016. \begin{figure}[tbp]
  11017. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11018. (define/public (join t1 t2)
  11019. (match* (t1 t2)
  11020. [('Integer 'Integer) 'Integer]
  11021. [('Boolean 'Boolean) 'Boolean]
  11022. [('Void 'Void) 'Void]
  11023. [('Any t2) t2]
  11024. [(t1 'Any) t1]
  11025. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11026. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11027. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11028. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11029. -> ,(join rt1 rt2))]))
  11030. (define/public (meet t1 t2)
  11031. (match* (t1 t2)
  11032. [('Integer 'Integer) 'Integer]
  11033. [('Boolean 'Boolean) 'Boolean]
  11034. [('Void 'Void) 'Void]
  11035. [('Any t2) 'Any]
  11036. [(t1 'Any) 'Any]
  11037. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11038. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11039. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11040. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11041. -> ,(meet rt1 rt2))]))
  11042. (define/public (make-cast e src tgt)
  11043. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11044. (define/public (check-consistent? t1 t2 e)
  11045. (unless (consistent? t1 t2)
  11046. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11047. (define/override (type-check-op op arg-types args e)
  11048. (match (dict-ref (operator-types) op)
  11049. [`(,param-types . ,return-type)
  11050. (for ([at arg-types] [pt param-types])
  11051. (check-consistent? at pt e))
  11052. (values return-type
  11053. (for/list ([e args] [s arg-types] [t param-types])
  11054. (make-cast e s t)))]
  11055. [else (error 'type-check-op "unrecognized ~a" op)]))
  11056. (define explicit-prim-ops
  11057. (set-union
  11058. (type-predicates)
  11059. (set 'procedure-arity 'eq?
  11060. 'vector 'vector-length 'vector-ref 'vector-set!
  11061. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11062. (define/override (fun-def-type d)
  11063. (match d
  11064. [(Def f params rt info body)
  11065. (define ps
  11066. (for/list ([p params])
  11067. (match p
  11068. [`[,x : ,T] T]
  11069. [(? symbol?) 'Any]
  11070. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11071. `(,@ps -> ,rt)]
  11072. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11073. \end{lstlisting}
  11074. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11075. \label{fig:type-check-Rgradual-aux}
  11076. \end{figure}
  11077. \clearpage
  11078. \section{Interpreting \LangCast{}}
  11079. \label{sec:interp-casts}
  11080. The runtime behavior of first-order casts is straightforward, that is,
  11081. casts involving simple types such as \code{Integer} and
  11082. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11083. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11084. puts the integer into a tagged value
  11085. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11086. \code{Integer} is accomplished with the \code{Project} operator, that
  11087. is, by checking the value's tag and either retrieving the underlying
  11088. integer or signaling an error if it the tag is not the one for
  11089. integers (Figure~\ref{fig:apply-project}).
  11090. %
  11091. Things get more interesting for higher-order casts, that is, casts
  11092. involving function or vector types.
  11093. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11094. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11095. this cast at runtime, we can't know in general whether the function
  11096. will always return an integer.\footnote{Predicting the return value of
  11097. a function is equivalent to the halting problem, which is
  11098. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11099. of the cast until the function is applied. This is accomplished by
  11100. wrapping \code{maybe-add1} in a new function that casts its parameter
  11101. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11102. casts the return value from \code{Any} to \code{Integer}.
  11103. Turning our attention to casts involving vector types, we consider the
  11104. example in Figure~\ref{fig:map-vec-bang} that defines a
  11105. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11106. type \code{(Vector Any Any)} and that updates \code{v} in place
  11107. instead of returning a new vector. So we name this function
  11108. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11109. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11110. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11111. cast between vector types would be a build a new vector whose elements
  11112. are the result of casting each of the original elements to the
  11113. appropriate target type. However, this approach is only valid for
  11114. immutable vectors; and our vectors are mutable. In the example of
  11115. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11116. the updates inside of \code{map-vec!} would happen to the new vector
  11117. and not the original one.
  11118. \begin{figure}[tbp]
  11119. % gradual_test_11.rkt
  11120. \begin{lstlisting}
  11121. (define (map-vec! [f : (Any -> Any)]
  11122. [v : (Vector Any Any)]) : Void
  11123. (begin
  11124. (vector-set! v 0 (f (vector-ref v 0)))
  11125. (vector-set! v 1 (f (vector-ref v 1)))))
  11126. (define (add1 x) (+ x 1))
  11127. (let ([v (vector 0 41)])
  11128. (begin (map-vec! add1 v) (vector-ref v 1)))
  11129. \end{lstlisting}
  11130. \caption{An example involving casts on vectors.}
  11131. \label{fig:map-vec-bang}
  11132. \end{figure}
  11133. Instead the interpreter needs to create a new kind of value, a
  11134. \emph{vector proxy}, that intercepts every vector operation. On a
  11135. read, the proxy reads from the underlying vector and then applies a
  11136. cast to the resulting value. On a write, the proxy casts the argument
  11137. value and then performs the write to the underlying vector. For the
  11138. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11139. \code{0} from \code{Integer} to \code{Any}. For the first
  11140. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11141. to \code{Integer}.
  11142. The final category of cast that we need to consider are casts between
  11143. the \code{Any} type and either a function or a vector
  11144. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11145. in which parameter \code{v} does not have a type annotation, so it is
  11146. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11147. type \code{(Vector Integer Integer)} so the type checker inserts a
  11148. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11149. thought is to use \code{Inject}, but that doesn't work because
  11150. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11151. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11152. to \code{Any}.
  11153. \begin{figure}[tbp]
  11154. \begin{lstlisting}
  11155. (define (map-vec! [f : (Any -> Any)] v) : Void
  11156. (begin
  11157. (vector-set! v 0 (f (vector-ref v 0)))
  11158. (vector-set! v 1 (f (vector-ref v 1)))))
  11159. (define (add1 x) (+ x 1))
  11160. (let ([v (vector 0 41)])
  11161. (begin (map-vec! add1 v) (vector-ref v 1)))
  11162. \end{lstlisting}
  11163. \caption{Casting a vector to \code{Any}.}
  11164. \label{fig:map-vec-any}
  11165. \end{figure}
  11166. The \LangCast{} interpreter uses an auxiliary function named
  11167. \code{apply-cast} to cast a value from a source type to a target type,
  11168. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11169. of the kinds of casts that we've discussed in this section.
  11170. \begin{figure}[tbp]
  11171. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11172. (define/public (apply-cast v s t)
  11173. (match* (s t)
  11174. [(t1 t2) #:when (equal? t1 t2) v]
  11175. [('Any t2)
  11176. (match t2
  11177. [`(,ts ... -> ,rt)
  11178. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11179. (define v^ (apply-project v any->any))
  11180. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11181. [`(Vector ,ts ...)
  11182. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11183. (define v^ (apply-project v vec-any))
  11184. (apply-cast v^ vec-any `(Vector ,@ts))]
  11185. [else (apply-project v t2)])]
  11186. [(t1 'Any)
  11187. (match t1
  11188. [`(,ts ... -> ,rt)
  11189. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11190. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11191. (apply-inject v^ (any-tag any->any))]
  11192. [`(Vector ,ts ...)
  11193. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11194. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11195. (apply-inject v^ (any-tag vec-any))]
  11196. [else (apply-inject v (any-tag t1))])]
  11197. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11198. (define x (gensym 'x))
  11199. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11200. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11201. (define cast-writes
  11202. (for/list ([t1 ts1] [t2 ts2])
  11203. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11204. `(vector-proxy ,(vector v (apply vector cast-reads)
  11205. (apply vector cast-writes)))]
  11206. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11207. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11208. `(function ,xs ,(Cast
  11209. (Apply (Value v)
  11210. (for/list ([x xs][t1 ts1][t2 ts2])
  11211. (Cast (Var x) t2 t1)))
  11212. rt1 rt2) ())]
  11213. ))
  11214. \end{lstlisting}
  11215. \caption{The \code{apply-cast} auxiliary method.}
  11216. \label{fig:apply-cast}
  11217. \end{figure}
  11218. The interpreter for \LangCast{} is defined in
  11219. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11220. dispatching to \code{apply-cast}. To handle the addition of vector
  11221. proxies, we update the vector primitives in \code{interp-op} using the
  11222. functions in Figure~\ref{fig:guarded-vector}.
  11223. \begin{figure}[tbp]
  11224. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11225. (define interp-Rcast-class
  11226. (class interp-Rwhile-class
  11227. (super-new)
  11228. (inherit apply-fun apply-inject apply-project)
  11229. (define/override (interp-op op)
  11230. (match op
  11231. ['vector-length guarded-vector-length]
  11232. ['vector-ref guarded-vector-ref]
  11233. ['vector-set! guarded-vector-set!]
  11234. ['any-vector-ref (lambda (v i)
  11235. (match v [`(tagged ,v^ ,tg)
  11236. (guarded-vector-ref v^ i)]))]
  11237. ['any-vector-set! (lambda (v i a)
  11238. (match v [`(tagged ,v^ ,tg)
  11239. (guarded-vector-set! v^ i a)]))]
  11240. ['any-vector-length (lambda (v)
  11241. (match v [`(tagged ,v^ ,tg)
  11242. (guarded-vector-length v^)]))]
  11243. [else (super interp-op op)]
  11244. ))
  11245. (define/override ((interp-exp env) e)
  11246. (define (recur e) ((interp-exp env) e))
  11247. (match e
  11248. [(Value v) v]
  11249. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11250. [else ((super interp-exp env) e)]))
  11251. ))
  11252. (define (interp-Rcast p)
  11253. (send (new interp-Rcast-class) interp-program p))
  11254. \end{lstlisting}
  11255. \caption{The interpreter for \LangCast{}.}
  11256. \label{fig:interp-Rcast}
  11257. \end{figure}
  11258. \begin{figure}[tbp]
  11259. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11260. (define (guarded-vector-ref vec i)
  11261. (match vec
  11262. [`(vector-proxy ,proxy)
  11263. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11264. (define rd (vector-ref (vector-ref proxy 1) i))
  11265. (apply-fun rd (list val) 'guarded-vector-ref)]
  11266. [else (vector-ref vec i)]))
  11267. (define (guarded-vector-set! vec i arg)
  11268. (match vec
  11269. [`(vector-proxy ,proxy)
  11270. (define wr (vector-ref (vector-ref proxy 2) i))
  11271. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11272. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11273. [else (vector-set! vec i arg)]))
  11274. (define (guarded-vector-length vec)
  11275. (match vec
  11276. [`(vector-proxy ,proxy)
  11277. (guarded-vector-length (vector-ref proxy 0))]
  11278. [else (vector-length vec)]))
  11279. \end{lstlisting}
  11280. \caption{The guarded-vector auxiliary functions.}
  11281. \label{fig:guarded-vector}
  11282. \end{figure}
  11283. \section{Lower Casts}
  11284. \label{sec:lower-casts}
  11285. The next step in the journey towards x86 is the \code{lower-casts}
  11286. pass that translates the casts in \LangCast{} to the lower-level
  11287. \code{Inject} and \code{Project} operators and a new operator for
  11288. creating vector proxies, extending the \LangLoop{} language to create
  11289. \LangProxy{}. We recommend creating an auxiliary function named
  11290. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11291. and a target type, and translates it to expression in \LangProxy{} that has
  11292. the same behavior as casting the expression from the source to the
  11293. target type in the interpreter.
  11294. The \code{lower-cast} function can follow a code structure similar to
  11295. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11296. the interpreter for \LangCast{} because it must handle the same cases as
  11297. \code{apply-cast} and it needs to mimic the behavior of
  11298. \code{apply-cast}. The most interesting cases are those concerning the
  11299. casts between two vector types and between two function types.
  11300. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11301. type to another vector type is accomplished by creating a proxy that
  11302. intercepts the operations on the underlying vector. Here we make the
  11303. creation of the proxy explicit with the \code{vector-proxy} primitive
  11304. operation. It takes three arguments, the first is an expression for
  11305. the vector, the second is a vector of functions for casting an element
  11306. that is being read from the vector, and the third is a vector of
  11307. functions for casting an element that is being written to the vector.
  11308. You can create the functions using \code{Lambda}. Also, as we shall
  11309. see in the next section, we need to differentiate these vectors from
  11310. the user-created ones, so we recommend using a new primitive operator
  11311. named \code{raw-vector} instead of \code{vector} to create these
  11312. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11313. the output of \code{lower-casts} on the example in
  11314. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11315. integers to a vector of \code{Any}.
  11316. \begin{figure}[tbp]
  11317. \begin{lstlisting}
  11318. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11319. (begin
  11320. (vector-set! v 0 (f (vector-ref v 0)))
  11321. (vector-set! v 1 (f (vector-ref v 1)))))
  11322. (define (add1 [x : Any]) : Any
  11323. (inject (+ (project x Integer) 1) Integer))
  11324. (let ([v (vector 0 41)])
  11325. (begin
  11326. (map-vec! add1 (vector-proxy v
  11327. (raw-vector (lambda: ([x9 : Integer]) : Any
  11328. (inject x9 Integer))
  11329. (lambda: ([x9 : Integer]) : Any
  11330. (inject x9 Integer)))
  11331. (raw-vector (lambda: ([x9 : Any]) : Integer
  11332. (project x9 Integer))
  11333. (lambda: ([x9 : Any]) : Integer
  11334. (project x9 Integer)))))
  11335. (vector-ref v 1)))
  11336. \end{lstlisting}
  11337. \caption{Output of \code{lower-casts} on the example in
  11338. Figure~\ref{fig:map-vec-bang}.}
  11339. \label{fig:map-vec-bang-lower-cast}
  11340. \end{figure}
  11341. A cast from one function type to another function type is accomplished
  11342. by generating a \code{Lambda} whose parameter and return types match
  11343. the target function type. The body of the \code{Lambda} should cast
  11344. the parameters from the target type to the source type (yes,
  11345. backwards! functions are contravariant\index{contravariant} in the
  11346. parameters), then call the underlying function, and finally cast the
  11347. result from the source return type to the target return type.
  11348. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11349. \code{lower-casts} pass on the \code{map-vec} example in
  11350. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11351. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11352. \begin{figure}[tbp]
  11353. \begin{lstlisting}
  11354. (define (map-vec [f : (Integer -> Integer)]
  11355. [v : (Vector Integer Integer)])
  11356. : (Vector Integer Integer)
  11357. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11358. (define (add1 [x : Any]) : Any
  11359. (inject (+ (project x Integer) 1) Integer))
  11360. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11361. (project (add1 (inject x9 Integer)) Integer))
  11362. (vector 0 41)) 1)
  11363. \end{lstlisting}
  11364. \caption{Output of \code{lower-casts} on the example in
  11365. Figure~\ref{fig:gradual-map-vec}.}
  11366. \label{fig:map-vec-lower-cast}
  11367. \end{figure}
  11368. \section{Differentiate Proxies}
  11369. \label{sec:differentiate-proxies}
  11370. So far the job of differentiating vectors and vector proxies has been
  11371. the job of the interpreter. For example, the interpreter for \LangCast{}
  11372. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11373. function in Figure~\ref{fig:guarded-vector}. In the
  11374. \code{differentiate-proxies} pass we shift this responsibility to the
  11375. generated code.
  11376. We begin by designing the output language $R^p_8$. In
  11377. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11378. proxies. In $R^p_8$ we return the \code{Vector} type to
  11379. its original meaning, as the type of real vectors, and we introduce a
  11380. new type, \code{PVector}, whose values can be either real vectors or
  11381. vector proxies. This new type comes with a suite of new primitive
  11382. operations for creating and using values of type \code{PVector}. We
  11383. don't need to introduce a new type to represent vector proxies. A
  11384. proxy is represented by a vector containing three things: 1) the
  11385. underlying vector, 2) a vector of functions for casting elements that
  11386. are read from the vector, and 3) a vector of functions for casting
  11387. values to be written to the vector. So we define the following
  11388. abbreviation for the type of a vector proxy:
  11389. \[
  11390. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11391. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11392. \to (\key{PVector}~ T' \ldots)
  11393. \]
  11394. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11395. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11396. %
  11397. Next we describe each of the new primitive operations.
  11398. \begin{description}
  11399. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11400. (\key{PVector} $T \ldots$)]\ \\
  11401. %
  11402. This operation brands a vector as a value of the \code{PVector} type.
  11403. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11404. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11405. %
  11406. This operation brands a vector proxy as value of the \code{PVector} type.
  11407. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11408. \code{Boolean}] \ \\
  11409. %
  11410. returns true if the value is a vector proxy and false if it is a
  11411. real vector.
  11412. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11413. (\key{Vector} $T \ldots$)]\ \\
  11414. %
  11415. Assuming that the input is a vector (and not a proxy), this
  11416. operation returns the vector.
  11417. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11418. $\to$ \code{Boolean}]\ \\
  11419. %
  11420. Given a vector proxy, this operation returns the length of the
  11421. underlying vector.
  11422. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11423. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11424. %
  11425. Given a vector proxy, this operation returns the $i$th element of
  11426. the underlying vector.
  11427. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11428. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11429. proxy, this operation writes a value to the $i$th element of the
  11430. underlying vector.
  11431. \end{description}
  11432. Now to discuss the translation that differentiates vectors from
  11433. proxies. First, every type annotation in the program must be
  11434. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11435. Next, we must insert uses of \code{PVector} operations in the
  11436. appropriate places. For example, we wrap every vector creation with an
  11437. \code{inject-vector}.
  11438. \begin{lstlisting}
  11439. (vector |$e_1 \ldots e_n$|)
  11440. |$\Rightarrow$|
  11441. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11442. \end{lstlisting}
  11443. The \code{raw-vector} operator that we introduced in the previous
  11444. section does not get injected.
  11445. \begin{lstlisting}
  11446. (raw-vector |$e_1 \ldots e_n$|)
  11447. |$\Rightarrow$|
  11448. (vector |$e'_1 \ldots e'_n$|)
  11449. \end{lstlisting}
  11450. The \code{vector-proxy} primitive translates as follows.
  11451. \begin{lstlisting}
  11452. (vector-proxy |$e_1~e_2~e_3$|)
  11453. |$\Rightarrow$|
  11454. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11455. \end{lstlisting}
  11456. We translate the vector operations into conditional expressions that
  11457. check whether the value is a proxy and then dispatch to either the
  11458. appropriate proxy vector operation or the regular vector operation.
  11459. For example, the following is the translation for \code{vector-ref}.
  11460. \begin{lstlisting}
  11461. (vector-ref |$e_1$| |$i$|)
  11462. |$\Rightarrow$|
  11463. (let ([|$v~e_1$|])
  11464. (if (proxy? |$v$|)
  11465. (proxy-vector-ref |$v$| |$i$|)
  11466. (vector-ref (project-vector |$v$|) |$i$|)
  11467. \end{lstlisting}
  11468. Note in the case of a real vector, we must apply \code{project-vector}
  11469. before the \code{vector-ref}.
  11470. \section{Reveal Casts}
  11471. \label{sec:reveal-casts-gradual}
  11472. Recall that the \code{reveal-casts} pass
  11473. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11474. \code{Inject} and \code{Project} into lower-level operations. In
  11475. particular, \code{Project} turns into a conditional expression that
  11476. inspects the tag and retrieves the underlying value. Here we need to
  11477. augment the translation of \code{Project} to handle the situation when
  11478. the target type is \code{PVector}. Instead of using
  11479. \code{vector-length} we need to use \code{proxy-vector-length}.
  11480. \begin{lstlisting}
  11481. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11482. |$\Rightarrow$|
  11483. (let |$\itm{tmp}$| |$e'$|
  11484. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11485. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11486. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11487. (exit)))
  11488. \end{lstlisting}
  11489. \section{Closure Conversion}
  11490. \label{sec:closure-conversion-gradual}
  11491. The closure conversion pass only requires one minor adjustment. The
  11492. auxiliary function that translates type annotations needs to be
  11493. updated to handle the \code{PVector} type.
  11494. \section{Explicate Control}
  11495. \label{sec:explicate-control-gradual}
  11496. Update the \code{explicate-control} pass to handle the new primitive
  11497. operations on the \code{PVector} type.
  11498. \section{Select Instructions}
  11499. \label{sec:select-instructions-gradual}
  11500. Recall that the \code{select-instructions} pass is responsible for
  11501. lowering the primitive operations into x86 instructions. So we need
  11502. to translate the new \code{PVector} operations to x86. To do so, the
  11503. first question we need to answer is how will we differentiate the two
  11504. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11505. We need just one bit to accomplish this, and use the bit in position
  11506. $57$ of the 64-bit tag at the front of every vector (see
  11507. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11508. for \code{inject-vector} we leave it that way.
  11509. \begin{lstlisting}
  11510. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11511. |$\Rightarrow$|
  11512. movq |$e'_1$|, |$\itm{lhs'}$|
  11513. \end{lstlisting}
  11514. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11515. \begin{lstlisting}
  11516. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11517. |$\Rightarrow$|
  11518. movq |$e'_1$|, %r11
  11519. movq |$(1 << 57)$|, %rax
  11520. orq 0(%r11), %rax
  11521. movq %rax, 0(%r11)
  11522. movq %r11, |$\itm{lhs'}$|
  11523. \end{lstlisting}
  11524. The \code{proxy?} operation consumes the information so carefully
  11525. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11526. isolates the $57$th bit to tell whether the value is a real vector or
  11527. a proxy.
  11528. \begin{lstlisting}
  11529. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11530. |$\Rightarrow$|
  11531. movq |$e_1'$|, %r11
  11532. movq 0(%r11), %rax
  11533. sarq $57, %rax
  11534. andq $1, %rax
  11535. movq %rax, |$\itm{lhs'}$|
  11536. \end{lstlisting}
  11537. The \code{project-vector} operation is straightforward to translate,
  11538. so we leave it up to the reader.
  11539. Regarding the \code{proxy-vector} operations, the runtime provides
  11540. procedures that implement them (they are recursive functions!) so
  11541. here we simply need to translate these vector operations into the
  11542. appropriate function call. For example, here is the translation for
  11543. \code{proxy-vector-ref}.
  11544. \begin{lstlisting}
  11545. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11546. |$\Rightarrow$|
  11547. movq |$e_1'$|, %rdi
  11548. movq |$e_2'$|, %rsi
  11549. callq proxy_vector_ref
  11550. movq %rax, |$\itm{lhs'}$|
  11551. \end{lstlisting}
  11552. We have another batch of vector operations to deal with, those for the
  11553. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11554. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11555. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11556. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11557. Section~\ref{sec:select-Rany} we selected instructions for these
  11558. operations based on the idea that the underlying value was a real
  11559. vector. But in the current setting, the underlying value is of type
  11560. \code{PVector}. So \code{any-vector-ref} can be translates to
  11561. pseudo-x86 as follows. We begin by projecting the underlying value out
  11562. of the tagged value and then call the \code{proxy\_vector\_ref}
  11563. procedure in the runtime.
  11564. \begin{lstlisting}
  11565. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11566. movq |$\neg 111$|, %rdi
  11567. andq |$e_1'$|, %rdi
  11568. movq |$e_2'$|, %rsi
  11569. callq proxy_vector_ref
  11570. movq %rax, |$\itm{lhs'}$|
  11571. \end{lstlisting}
  11572. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11573. be translated in a similar way.
  11574. \begin{exercise}\normalfont
  11575. Implement a compiler for the gradually-typed \LangGrad{} language by
  11576. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11577. partially-typed test programs. In addition to testing with these
  11578. new programs, also test your compiler on all the tests for \LangLoop{}
  11579. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11580. on the \LangDyn{} programs but you can adapt them by inserting
  11581. a cast to the \code{Any} type around each subexpression
  11582. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11583. you can induce one by wrapping the subexpression \code{e}
  11584. with a call to an un-annotated identity function, like this:
  11585. \code{((lambda (x) x) e)}.
  11586. \end{exercise}
  11587. \begin{figure}[p]
  11588. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11589. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11590. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11591. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11592. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11593. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11594. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11595. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11596. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11597. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11598. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11599. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11600. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11601. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11602. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11603. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11604. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11605. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11606. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11607. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11608. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11609. \path[->,bend right=15] (Rgradual) edge [above] node
  11610. {\ttfamily\footnotesize type-check} (Rgradualp);
  11611. \path[->,bend right=15] (Rgradualp) edge [above] node
  11612. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11613. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11614. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11615. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11616. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11617. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11618. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11619. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11620. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11621. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11622. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11623. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11624. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11625. \path[->,bend left=15] (F1-1) edge [below] node
  11626. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11627. \path[->,bend right=15] (F1-2) edge [above] node
  11628. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11629. \path[->,bend right=15] (F1-3) edge [above] node
  11630. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11631. \path[->,bend right=15] (F1-4) edge [above] node
  11632. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11633. \path[->,bend right=15] (F1-5) edge [right] node
  11634. {\ttfamily\footnotesize explicate-control} (C3-2);
  11635. \path[->,bend left=15] (C3-2) edge [left] node
  11636. {\ttfamily\footnotesize select-instr.} (x86-2);
  11637. \path[->,bend right=15] (x86-2) edge [left] node
  11638. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11639. \path[->,bend right=15] (x86-2-1) edge [below] node
  11640. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11641. \path[->,bend right=15] (x86-2-2) edge [left] node
  11642. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11643. \path[->,bend left=15] (x86-3) edge [above] node
  11644. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11645. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11646. \end{tikzpicture}
  11647. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11648. \label{fig:Rgradual-passes}
  11649. \end{figure}
  11650. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11651. for the compilation of \LangGrad{}.
  11652. \section{Further Reading}
  11653. This chapter just scratches the surface of gradual typing. The basic
  11654. approach described here is missing two key ingredients that one would
  11655. want in a implementation of gradual typing: blame
  11656. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11657. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11658. problem addressed by blame tracking is that when a cast on a
  11659. higher-order value fails, it often does so at a point in the program
  11660. that is far removed from the original cast. Blame tracking is a
  11661. technique for propagating extra information through casts and proxies
  11662. so that when a cast fails, the error message can point back to the
  11663. original location of the cast in the source program.
  11664. The problem addressed by space-efficient casts also relates to
  11665. higher-order casts. It turns out that in partially typed programs, a
  11666. function or vector can flow through very-many casts at runtime. With
  11667. the approach described in this chapter, each cast adds another
  11668. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11669. considerable space, but it also makes the function calls and vector
  11670. operations slow. For example, a partially-typed version of quicksort
  11671. could, in the worst case, build a chain of proxies of length $O(n)$
  11672. around the vector, changing the overall time complexity of the
  11673. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11674. solution to this problem by representing casts using the coercion
  11675. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11676. long chains of proxies by compressing them into a concise normal
  11677. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11678. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11679. the Grift compiler.
  11680. \begin{center}
  11681. \url{https://github.com/Gradual-Typing/Grift}
  11682. \end{center}
  11683. There are also interesting interactions between gradual typing and
  11684. other language features, such as parametetric polymorphism,
  11685. information-flow types, and type inference, to name a few. We
  11686. recommend the reader to the online gradual typing bibliography:
  11687. \begin{center}
  11688. \url{http://samth.github.io/gradual-typing-bib/}
  11689. \end{center}
  11690. % TODO: challenge problem:
  11691. % type analysis and type specialization?
  11692. % coercions?
  11693. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11694. \chapter{Parametric Polymorphism}
  11695. \label{ch:Rpoly}
  11696. \index{parametric polymorphism}
  11697. \index{generics}
  11698. This chapter studies the compilation of parametric
  11699. polymorphism\index{parametric polymorphism}
  11700. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11701. Racket. Parametric polymorphism enables improved code reuse by
  11702. parameterizing functions and data structures with respect to the types
  11703. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11704. revisits the \code{map-vec} example but this time gives it a more
  11705. fitting type. This \code{map-vec} function is parameterized with
  11706. respect to the element type of the vector. The type of \code{map-vec}
  11707. is the following polymorphic type as specified by the \code{All} and
  11708. the type parameter \code{a}.
  11709. \begin{lstlisting}
  11710. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11711. \end{lstlisting}
  11712. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11713. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11714. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11715. \code{a}, but we could have just as well applied \code{map-vec} to a
  11716. vector of Booleans (and a function on Booleans).
  11717. \begin{figure}[tbp]
  11718. % poly_test_2.rkt
  11719. \begin{lstlisting}
  11720. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11721. (define (map-vec f v)
  11722. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11723. (define (add1 [x : Integer]) : Integer (+ x 1))
  11724. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11725. \end{lstlisting}
  11726. \caption{The \code{map-vec} example using parametric polymorphism.}
  11727. \label{fig:map-vec-poly}
  11728. \end{figure}
  11729. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11730. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11731. syntax. We add a second form for function definitions in which a type
  11732. declaration comes before the \code{define}. In the abstract syntax,
  11733. the return type in the \code{Def} is \code{Any}, but that should be
  11734. ignored in favor of the return type in the type declaration. (The
  11735. \code{Any} comes from using the same parser as in
  11736. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11737. enables the use of an \code{All} type for a function, thereby making
  11738. it polymorphic. The grammar for types is extended to include
  11739. polymorphic types and type variables.
  11740. \begin{figure}[tp]
  11741. \centering
  11742. \fbox{
  11743. \begin{minipage}{0.96\textwidth}
  11744. \small
  11745. \[
  11746. \begin{array}{lcl}
  11747. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11748. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11749. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11750. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11751. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11752. \end{array}
  11753. \]
  11754. \end{minipage}
  11755. }
  11756. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11757. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11758. \label{fig:Rpoly-concrete-syntax}
  11759. \end{figure}
  11760. \begin{figure}[tp]
  11761. \centering
  11762. \fbox{
  11763. \begin{minipage}{0.96\textwidth}
  11764. \small
  11765. \[
  11766. \begin{array}{lcl}
  11767. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11768. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11769. &\mid& \DECL{\Var}{\Type} \\
  11770. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11771. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11772. \end{array}
  11773. \]
  11774. \end{minipage}
  11775. }
  11776. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11777. (Figure~\ref{fig:Rwhile-syntax}).}
  11778. \label{fig:Rpoly-syntax}
  11779. \end{figure}
  11780. By including polymorphic types in the $\Type$ non-terminal we choose
  11781. to make them first-class which has interesting repercussions on the
  11782. compiler. Many languages with polymorphism, such as
  11783. C++~\citep{stroustrup88:_param_types} and Standard
  11784. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11785. it is useful to see an example of first-class polymorphism. In
  11786. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11787. whose parameter is a polymorphic function. The occurrence of a
  11788. polymorphic type underneath a function type is enabled by the normal
  11789. recursive structure of the grammar for $\Type$ and the categorization
  11790. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11791. applies the polymorphic function to a Boolean and to an integer.
  11792. \begin{figure}[tbp]
  11793. \begin{lstlisting}
  11794. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11795. (define (apply-twice f)
  11796. (if (f #t) (f 42) (f 777)))
  11797. (: id (All (a) (a -> a)))
  11798. (define (id x) x)
  11799. (apply-twice id)
  11800. \end{lstlisting}
  11801. \caption{An example illustrating first-class polymorphism.}
  11802. \label{fig:apply-twice}
  11803. \end{figure}
  11804. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11805. three new responsibilities (compared to \LangLoop{}). The type checking of
  11806. function application is extended to handle the case where the operator
  11807. expression is a polymorphic function. In that case the type arguments
  11808. are deduced by matching the type of the parameters with the types of
  11809. the arguments.
  11810. %
  11811. The \code{match-types} auxiliary function carries out this deduction
  11812. by recursively descending through a parameter type \code{pt} and the
  11813. corresponding argument type \code{at}, making sure that they are equal
  11814. except when there is a type parameter on the left (in the parameter
  11815. type). If it's the first time that the type parameter has been
  11816. encountered, then the algorithm deduces an association of the type
  11817. parameter to the corresponding type on the right (in the argument
  11818. type). If it's not the first time that the type parameter has been
  11819. encountered, the algorithm looks up its deduced type and makes sure
  11820. that it is equal to the type on the right.
  11821. %
  11822. Once the type arguments are deduced, the operator expression is
  11823. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11824. type of the operator, but more importantly, records the deduced type
  11825. arguments. The return type of the application is the return type of
  11826. the polymorphic function, but with the type parameters replaced by the
  11827. deduced type arguments, using the \code{subst-type} function.
  11828. The second responsibility of the type checker is extending the
  11829. function \code{type-equal?} to handle the \code{All} type. This is
  11830. not quite a simple as equal on other types, such as function and
  11831. vector types, because two polymorphic types can be syntactically
  11832. different even though they are equivalent types. For example,
  11833. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11834. Two polymorphic types should be considered equal if they differ only
  11835. in the choice of the names of the type parameters. The
  11836. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11837. renames the type parameters of the first type to match the type
  11838. parameters of the second type.
  11839. The third responsibility of the type checker is making sure that only
  11840. defined type variables appear in type annotations. The
  11841. \code{check-well-formed} function defined in
  11842. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11843. sure that each type variable has been defined.
  11844. The output language of the type checker is \LangInst{}, defined in
  11845. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11846. declaration and polymorphic function into a single definition, using
  11847. the \code{Poly} form, to make polymorphic functions more convenient to
  11848. process in next pass of the compiler.
  11849. \begin{figure}[tp]
  11850. \centering
  11851. \fbox{
  11852. \begin{minipage}{0.96\textwidth}
  11853. \small
  11854. \[
  11855. \begin{array}{lcl}
  11856. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11857. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11858. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11859. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11860. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11861. \end{array}
  11862. \]
  11863. \end{minipage}
  11864. }
  11865. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11866. (Figure~\ref{fig:Rwhile-syntax}).}
  11867. \label{fig:Rpoly-prime-syntax}
  11868. \end{figure}
  11869. The output of the type checker on the polymorphic \code{map-vec}
  11870. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11871. \begin{figure}[tbp]
  11872. % poly_test_2.rkt
  11873. \begin{lstlisting}
  11874. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11875. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11876. (define (add1 [x : Integer]) : Integer (+ x 1))
  11877. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11878. (Integer))
  11879. add1 (vector 0 41)) 1)
  11880. \end{lstlisting}
  11881. \caption{Output of the type checker on the \code{map-vec} example.}
  11882. \label{fig:map-vec-type-check}
  11883. \end{figure}
  11884. \begin{figure}[tbp]
  11885. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11886. (define type-check-poly-class
  11887. (class type-check-Rwhile-class
  11888. (super-new)
  11889. (inherit check-type-equal?)
  11890. (define/override (type-check-apply env e1 es)
  11891. (define-values (e^ ty) ((type-check-exp env) e1))
  11892. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11893. ((type-check-exp env) e)))
  11894. (match ty
  11895. [`(,ty^* ... -> ,rt)
  11896. (for ([arg-ty ty*] [param-ty ty^*])
  11897. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11898. (values e^ es^ rt)]
  11899. [`(All ,xs (,tys ... -> ,rt))
  11900. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11901. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11902. (match-types env^^ param-ty arg-ty)))
  11903. (define targs
  11904. (for/list ([x xs])
  11905. (match (dict-ref env^^ x (lambda () #f))
  11906. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11907. x (Apply e1 es))]
  11908. [ty ty])))
  11909. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11910. [else (error 'type-check "expected a function, not ~a" ty)]))
  11911. (define/override ((type-check-exp env) e)
  11912. (match e
  11913. [(Lambda `([,xs : ,Ts] ...) rT body)
  11914. (for ([T Ts]) ((check-well-formed env) T))
  11915. ((check-well-formed env) rT)
  11916. ((super type-check-exp env) e)]
  11917. [(HasType e1 ty)
  11918. ((check-well-formed env) ty)
  11919. ((super type-check-exp env) e)]
  11920. [else ((super type-check-exp env) e)]))
  11921. (define/override ((type-check-def env) d)
  11922. (verbose 'type-check "poly/def" d)
  11923. (match d
  11924. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11925. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11926. (for ([p ps]) ((check-well-formed ts-env) p))
  11927. ((check-well-formed ts-env) rt)
  11928. (define new-env (append ts-env (map cons xs ps) env))
  11929. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11930. (check-type-equal? ty^ rt body)
  11931. (Generic ts (Def f p:t* rt info body^))]
  11932. [else ((super type-check-def env) d)]))
  11933. (define/override (type-check-program p)
  11934. (match p
  11935. [(Program info body)
  11936. (type-check-program (ProgramDefsExp info '() body))]
  11937. [(ProgramDefsExp info ds body)
  11938. (define ds^ (combine-decls-defs ds))
  11939. (define new-env (for/list ([d ds^])
  11940. (cons (def-name d) (fun-def-type d))))
  11941. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11942. (define-values (body^ ty) ((type-check-exp new-env) body))
  11943. (check-type-equal? ty 'Integer body)
  11944. (ProgramDefsExp info ds^^ body^)]))
  11945. ))
  11946. \end{lstlisting}
  11947. \caption{Type checker for the \LangPoly{} language.}
  11948. \label{fig:type-check-Rvar0}
  11949. \end{figure}
  11950. \begin{figure}[tbp]
  11951. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11952. (define/override (type-equal? t1 t2)
  11953. (match* (t1 t2)
  11954. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11955. (define env (map cons xs ys))
  11956. (type-equal? (subst-type env T1) T2)]
  11957. [(other wise)
  11958. (super type-equal? t1 t2)]))
  11959. (define/public (match-types env pt at)
  11960. (match* (pt at)
  11961. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11962. [('Void 'Void) env] [('Any 'Any) env]
  11963. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11964. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11965. (match-types env^ pt1 at1))]
  11966. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11967. (define env^ (match-types env prt art))
  11968. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11969. (match-types env^^ pt1 at1))]
  11970. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11971. (define env^ (append (map cons pxs axs) env))
  11972. (match-types env^ pt1 at1)]
  11973. [((? symbol? x) at)
  11974. (match (dict-ref env x (lambda () #f))
  11975. [#f (error 'type-check "undefined type variable ~a" x)]
  11976. ['Type (cons (cons x at) env)]
  11977. [t^ (check-type-equal? at t^ 'matching) env])]
  11978. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11979. (define/public (subst-type env pt)
  11980. (match pt
  11981. ['Integer 'Integer] ['Boolean 'Boolean]
  11982. ['Void 'Void] ['Any 'Any]
  11983. [`(Vector ,ts ...)
  11984. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11985. [`(,ts ... -> ,rt)
  11986. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11987. [`(All ,xs ,t)
  11988. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11989. [(? symbol? x) (dict-ref env x)]
  11990. [else (error 'type-check "expected a type not ~a" pt)]))
  11991. (define/public (combine-decls-defs ds)
  11992. (match ds
  11993. ['() '()]
  11994. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11995. (unless (equal? name f)
  11996. (error 'type-check "name mismatch, ~a != ~a" name f))
  11997. (match type
  11998. [`(All ,xs (,ps ... -> ,rt))
  11999. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12000. (cons (Generic xs (Def name params^ rt info body))
  12001. (combine-decls-defs ds^))]
  12002. [`(,ps ... -> ,rt)
  12003. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12004. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12005. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12006. [`(,(Def f params rt info body) . ,ds^)
  12007. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12008. \end{lstlisting}
  12009. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12010. \label{fig:type-check-Rvar0-aux}
  12011. \end{figure}
  12012. \begin{figure}[tbp]
  12013. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12014. (define/public ((check-well-formed env) ty)
  12015. (match ty
  12016. ['Integer (void)]
  12017. ['Boolean (void)]
  12018. ['Void (void)]
  12019. [(? symbol? a)
  12020. (match (dict-ref env a (lambda () #f))
  12021. ['Type (void)]
  12022. [else (error 'type-check "undefined type variable ~a" a)])]
  12023. [`(Vector ,ts ...)
  12024. (for ([t ts]) ((check-well-formed env) t))]
  12025. [`(,ts ... -> ,t)
  12026. (for ([t ts]) ((check-well-formed env) t))
  12027. ((check-well-formed env) t)]
  12028. [`(All ,xs ,t)
  12029. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12030. ((check-well-formed env^) t)]
  12031. [else (error 'type-check "unrecognized type ~a" ty)]))
  12032. \end{lstlisting}
  12033. \caption{Well-formed types.}
  12034. \label{fig:well-formed-types}
  12035. \end{figure}
  12036. % TODO: interpreter for R'_10
  12037. \section{Compiling Polymorphism}
  12038. \label{sec:compiling-poly}
  12039. Broadly speaking, there are four approaches to compiling parametric
  12040. polymorphism, which we describe below.
  12041. \begin{description}
  12042. \item[Monomorphization] generates a different version of a polymorphic
  12043. function for each set of type arguments that it is used with,
  12044. producing type-specialized code. This approach results in the most
  12045. efficient code but requires whole-program compilation (no separate
  12046. compilation) and increases code size. For our current purposes
  12047. monomorphization is a non-starter because, with first-class
  12048. polymorphism, it is sometimes not possible to determine which
  12049. generic functions are used with which type arguments during
  12050. compilation. (It can be done at runtime, with just-in-time
  12051. compilation.) This approach is used to compile C++
  12052. templates~\citep{stroustrup88:_param_types} and polymorphic
  12053. functions in NESL~\citep{Blelloch:1993aa} and
  12054. ML~\citep{Weeks:2006aa}.
  12055. \item[Uniform representation] generates one version of each
  12056. polymorphic function but requires all values have a common ``boxed''
  12057. format, such as the tagged values of type \code{Any} in
  12058. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12059. similarly to code in a dynamically typed language (like \LangDyn{}),
  12060. in which primitive operators require their arguments to be projected
  12061. from \code{Any} and their results are injected into \code{Any}. (In
  12062. object-oriented languages, the projection is accomplished via
  12063. virtual method dispatch.) The uniform representation approach is
  12064. compatible with separate compilation and with first-class
  12065. polymorphism. However, it produces the least-efficient code because
  12066. it introduces overhead in the entire program, including
  12067. non-polymorphic code. This approach is used in implementations of
  12068. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12069. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12070. Java~\citep{Bracha:1998fk}.
  12071. \item[Mixed representation] generates one version of each polymorphic
  12072. function, using a boxed representation for type
  12073. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12074. and conversions are performed at the boundaries between monomorphic
  12075. and polymorphic (e.g. when a polymorphic function is instantiated
  12076. and called). This approach is compatible with separate compilation
  12077. and first-class polymorphism and maintains the efficiency of
  12078. monomorphic code. The tradeoff is increased overhead at the boundary
  12079. between monomorphic and polymorphic code. This approach is used in
  12080. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12081. Java 5 with the addition of autoboxing.
  12082. \item[Type passing] uses the unboxed representation in both
  12083. monomorphic and polymorphic code. Each polymorphic function is
  12084. compiled to a single function with extra parameters that describe
  12085. the type arguments. The type information is used by the generated
  12086. code to know how to access the unboxed values at runtime. This
  12087. approach is used in implementation of the Napier88
  12088. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12089. passing is compatible with separate compilation and first-class
  12090. polymorphism and maintains the efficiency for monomorphic
  12091. code. There is runtime overhead in polymorphic code from dispatching
  12092. on type information.
  12093. \end{description}
  12094. In this chapter we use the mixed representation approach, partly
  12095. because of its favorable attributes, and partly because it is
  12096. straightforward to implement using the tools that we have already
  12097. built to support gradual typing. To compile polymorphic functions, we
  12098. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12099. \LangCast{}.
  12100. \section{Erase Types}
  12101. \label{sec:erase-types}
  12102. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12103. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12104. shows the output of the \code{erase-types} pass on the polymorphic
  12105. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12106. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12107. \code{All} types are removed from the type of \code{map-vec}.
  12108. \begin{figure}[tbp]
  12109. \begin{lstlisting}
  12110. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12111. : (Vector Any Any)
  12112. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12113. (define (add1 [x : Integer]) : Integer (+ x 1))
  12114. (vector-ref ((cast map-vec
  12115. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12116. ((Integer -> Integer) (Vector Integer Integer)
  12117. -> (Vector Integer Integer)))
  12118. add1 (vector 0 41)) 1)
  12119. \end{lstlisting}
  12120. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12121. \label{fig:map-vec-erase}
  12122. \end{figure}
  12123. This process of type erasure creates a challenge at points of
  12124. instantiation. For example, consider the instantiation of
  12125. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12126. The type of \code{map-vec} is
  12127. \begin{lstlisting}
  12128. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12129. \end{lstlisting}
  12130. and it is instantiated to
  12131. \begin{lstlisting}
  12132. ((Integer -> Integer) (Vector Integer Integer)
  12133. -> (Vector Integer Integer))
  12134. \end{lstlisting}
  12135. After erasure, the type of \code{map-vec} is
  12136. \begin{lstlisting}
  12137. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12138. \end{lstlisting}
  12139. but we need to convert it to the instantiated type. This is easy to
  12140. do in the target language \LangCast{} with a single \code{cast}. In
  12141. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12142. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12143. the instantiated type. The source and target type of a cast must be
  12144. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12145. because both the source and target are obtained from the same
  12146. polymorphic type of \code{map-vec}, replacing the type parameters with
  12147. \code{Any} in the former and with the deduced type arguments in the
  12148. later. (Recall that the \code{Any} type is consistent with any type.)
  12149. To implement the \code{erase-types} pass, we recommend defining a
  12150. recursive auxiliary function named \code{erase-type} that applies the
  12151. following two transformations. It replaces type variables with
  12152. \code{Any}
  12153. \begin{lstlisting}
  12154. |$x$|
  12155. |$\Rightarrow$|
  12156. Any
  12157. \end{lstlisting}
  12158. and it removes the polymorphic \code{All} types.
  12159. \begin{lstlisting}
  12160. (All |$xs$| |$T_1$|)
  12161. |$\Rightarrow$|
  12162. |$T'_1$|
  12163. \end{lstlisting}
  12164. Apply the \code{erase-type} function to all of the type annotations in
  12165. the program.
  12166. Regarding the translation of expressions, the case for \code{Inst} is
  12167. the interesting one. We translate it into a \code{Cast}, as shown
  12168. below. The type of the subexpression $e$ is the polymorphic type
  12169. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12170. $T$, the type $T'$. The target type $T''$ is the result of
  12171. substituting the arguments types $ts$ for the type parameters $xs$ in
  12172. $T$ followed by doing type erasure.
  12173. \begin{lstlisting}
  12174. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12175. |$\Rightarrow$|
  12176. (Cast |$e'$| |$T'$| |$T''$|)
  12177. \end{lstlisting}
  12178. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12179. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12180. Finally, each polymorphic function is translated to a regular
  12181. functions in which type erasure has been applied to all the type
  12182. annotations and the body.
  12183. \begin{lstlisting}
  12184. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12185. |$\Rightarrow$|
  12186. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12187. \end{lstlisting}
  12188. \begin{exercise}\normalfont
  12189. Implement a compiler for the polymorphic language \LangPoly{} by
  12190. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12191. programs that use polymorphic functions. Some of them should make
  12192. use of first-class polymorphism.
  12193. \end{exercise}
  12194. \begin{figure}[p]
  12195. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12196. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12197. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12198. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12199. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12200. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12201. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12202. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12203. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12204. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12205. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12206. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12207. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12208. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12209. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12210. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12211. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12212. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12213. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12214. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12215. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12216. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12217. \path[->,bend right=15] (Rpoly) edge [above] node
  12218. {\ttfamily\footnotesize type-check} (Rpolyp);
  12219. \path[->,bend right=15] (Rpolyp) edge [above] node
  12220. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12221. \path[->,bend right=15] (Rgradualp) edge [above] node
  12222. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12223. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12224. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12225. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12226. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12227. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12228. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12229. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12230. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12231. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12232. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12233. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12234. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12235. \path[->,bend left=15] (F1-1) edge [below] node
  12236. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12237. \path[->,bend right=15] (F1-2) edge [above] node
  12238. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12239. \path[->,bend right=15] (F1-3) edge [above] node
  12240. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12241. \path[->,bend right=15] (F1-4) edge [above] node
  12242. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12243. \path[->,bend right=15] (F1-5) edge [right] node
  12244. {\ttfamily\footnotesize explicate-control} (C3-2);
  12245. \path[->,bend left=15] (C3-2) edge [left] node
  12246. {\ttfamily\footnotesize select-instr.} (x86-2);
  12247. \path[->,bend right=15] (x86-2) edge [left] node
  12248. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12249. \path[->,bend right=15] (x86-2-1) edge [below] node
  12250. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12251. \path[->,bend right=15] (x86-2-2) edge [left] node
  12252. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12253. \path[->,bend left=15] (x86-3) edge [above] node
  12254. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12255. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12256. \end{tikzpicture}
  12257. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12258. \label{fig:Rpoly-passes}
  12259. \end{figure}
  12260. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12261. for the compilation of \LangPoly{}.
  12262. % TODO: challenge problem: specialization of instantiations
  12263. % Further Reading
  12264. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12265. \chapter{Appendix}
  12266. \section{Interpreters}
  12267. \label{appendix:interp}
  12268. \index{interpreter}
  12269. We provide interpreters for each of the source languages \LangInt{},
  12270. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12271. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12272. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12273. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12274. and x86 are in the \key{interp.rkt} file.
  12275. \section{Utility Functions}
  12276. \label{appendix:utilities}
  12277. The utility functions described in this section are in the
  12278. \key{utilities.rkt} file of the support code.
  12279. \paragraph{\code{interp-tests}}
  12280. The \key{interp-tests} function runs the compiler passes and the
  12281. interpreters on each of the specified tests to check whether each pass
  12282. is correct. The \key{interp-tests} function has the following
  12283. parameters:
  12284. \begin{description}
  12285. \item[name (a string)] a name to identify the compiler,
  12286. \item[typechecker] a function of exactly one argument that either
  12287. raises an error using the \code{error} function when it encounters a
  12288. type error, or returns \code{\#f} when it encounters a type
  12289. error. If there is no type error, the type checker returns the
  12290. program.
  12291. \item[passes] a list with one entry per pass. An entry is a list with
  12292. four things:
  12293. \begin{enumerate}
  12294. \item a string giving the name of the pass,
  12295. \item the function that implements the pass (a translator from AST
  12296. to AST),
  12297. \item a function that implements the interpreter (a function from
  12298. AST to result value) for the output language,
  12299. \item and a type checker for the output language. Type checkers for
  12300. the $R$ and $C$ languages are provided in the support code. For
  12301. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12302. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12303. type checker entry is optional. The support code does not provide
  12304. type checkers for the x86 languages.
  12305. \end{enumerate}
  12306. \item[source-interp] an interpreter for the source language. The
  12307. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12308. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12309. \item[tests] a list of test numbers that specifies which tests to
  12310. run. (see below)
  12311. \end{description}
  12312. %
  12313. The \key{interp-tests} function assumes that the subdirectory
  12314. \key{tests} has a collection of Racket programs whose names all start
  12315. with the family name, followed by an underscore and then the test
  12316. number, ending with the file extension \key{.rkt}. Also, for each test
  12317. program that calls \code{read} one or more times, there is a file with
  12318. the same name except that the file extension is \key{.in} that
  12319. provides the input for the Racket program. If the test program is
  12320. expected to fail type checking, then there should be an empty file of
  12321. the same name but with extension \key{.tyerr}.
  12322. \paragraph{\code{compiler-tests}}
  12323. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12324. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12325. machine code and checks that the output is $42$. The parameters to the
  12326. \code{compiler-tests} function are similar to those of the
  12327. \code{interp-tests} function, and consist of
  12328. \begin{itemize}
  12329. \item a compiler name (a string),
  12330. \item a type checker,
  12331. \item description of the passes,
  12332. \item name of a test-family, and
  12333. \item a list of test numbers.
  12334. \end{itemize}
  12335. \paragraph{\code{compile-file}}
  12336. takes a description of the compiler passes (see the comment for
  12337. \key{interp-tests}) and returns a function that, given a program file
  12338. name (a string ending in \key{.rkt}), applies all of the passes and
  12339. writes the output to a file whose name is the same as the program file
  12340. name but with \key{.rkt} replaced with \key{.s}.
  12341. \paragraph{\code{read-program}}
  12342. takes a file path and parses that file (it must be a Racket program)
  12343. into an abstract syntax tree.
  12344. \paragraph{\code{parse-program}}
  12345. takes an S-expression representation of an abstract syntax tree and converts it into
  12346. the struct-based representation.
  12347. \paragraph{\code{assert}}
  12348. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12349. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12350. \paragraph{\code{lookup}}
  12351. % remove discussion of lookup? -Jeremy
  12352. takes a key and an alist, and returns the first value that is
  12353. associated with the given key, if there is one. If not, an error is
  12354. triggered. The alist may contain both immutable pairs (built with
  12355. \key{cons}) and mutable pairs (built with \key{mcons}).
  12356. %The \key{map2} function ...
  12357. \section{x86 Instruction Set Quick-Reference}
  12358. \label{sec:x86-quick-reference}
  12359. \index{x86}
  12360. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12361. do. We write $A \to B$ to mean that the value of $A$ is written into
  12362. location $B$. Address offsets are given in bytes. The instruction
  12363. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12364. registers (such as \code{\%rax}), or memory references (such as
  12365. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12366. reference per instruction. Other operands must be immediates or
  12367. registers.
  12368. \begin{table}[tbp]
  12369. \centering
  12370. \begin{tabular}{l|l}
  12371. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12372. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12373. \texttt{negq} $A$ & $- A \to A$ \\
  12374. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12375. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12376. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12377. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12378. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12379. \texttt{retq} & Pops the return address and jumps to it \\
  12380. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12381. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12382. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12383. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12384. be an immediate) \\
  12385. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12386. matches the condition code of the instruction, otherwise go to the
  12387. next instructions. The condition codes are \key{e} for ``equal'',
  12388. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12389. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12390. \texttt{jl} $L$ & \\
  12391. \texttt{jle} $L$ & \\
  12392. \texttt{jg} $L$ & \\
  12393. \texttt{jge} $L$ & \\
  12394. \texttt{jmp} $L$ & Jump to label $L$ \\
  12395. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12396. \texttt{movzbq} $A$, $B$ &
  12397. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12398. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12399. and the extra bytes of $B$ are set to zero.} \\
  12400. & \\
  12401. & \\
  12402. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12403. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12404. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12405. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12406. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12407. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12408. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12409. description of the condition codes. $A$ must be a single byte register
  12410. (e.g., \texttt{al} or \texttt{cl}).} \\
  12411. \texttt{setl} $A$ & \\
  12412. \texttt{setle} $A$ & \\
  12413. \texttt{setg} $A$ & \\
  12414. \texttt{setge} $A$ &
  12415. \end{tabular}
  12416. \vspace{5pt}
  12417. \caption{Quick-reference for the x86 instructions used in this book.}
  12418. \label{tab:x86-instr}
  12419. \end{table}
  12420. \cleardoublepage
  12421. \section{Concrete Syntax for Intermediate Languages}
  12422. The concrete syntax of \LangAny{} is defined in
  12423. Figure~\ref{fig:Rany-concrete-syntax}.
  12424. \begin{figure}[tp]
  12425. \centering
  12426. \fbox{
  12427. \begin{minipage}{0.97\textwidth}\small
  12428. \[
  12429. \begin{array}{lcl}
  12430. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12431. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12432. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12433. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12434. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12435. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12436. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12437. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12438. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12439. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12440. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12441. \mid \LP\key{void?}\;\Exp\RP \\
  12442. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12443. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12444. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  12445. \end{array}
  12446. \]
  12447. \end{minipage}
  12448. }
  12449. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12450. (Figure~\ref{fig:Rlam-syntax}).}
  12451. \label{fig:Rany-concrete-syntax}
  12452. \end{figure}
  12453. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12454. defined in Figures~\ref{fig:c0-concrete-syntax},
  12455. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12456. and \ref{fig:c3-concrete-syntax}, respectively.
  12457. \begin{figure}[tbp]
  12458. \fbox{
  12459. \begin{minipage}{0.96\textwidth}
  12460. \[
  12461. \begin{array}{lcl}
  12462. \Atm &::=& \Int \mid \Var \\
  12463. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12464. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12465. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12466. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12467. \end{array}
  12468. \]
  12469. \end{minipage}
  12470. }
  12471. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12472. \label{fig:c0-concrete-syntax}
  12473. \end{figure}
  12474. \begin{figure}[tbp]
  12475. \fbox{
  12476. \begin{minipage}{0.96\textwidth}
  12477. \small
  12478. \[
  12479. \begin{array}{lcl}
  12480. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12481. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12482. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12483. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12484. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12485. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12486. \mid \key{goto}~\itm{label}\key{;}\\
  12487. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12488. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12489. \end{array}
  12490. \]
  12491. \end{minipage}
  12492. }
  12493. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12494. \label{fig:c1-concrete-syntax}
  12495. \end{figure}
  12496. \begin{figure}[tbp]
  12497. \fbox{
  12498. \begin{minipage}{0.96\textwidth}
  12499. \small
  12500. \[
  12501. \begin{array}{lcl}
  12502. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12503. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12504. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12505. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12506. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12507. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12508. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12509. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12510. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12511. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12512. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12513. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12514. \end{array}
  12515. \]
  12516. \end{minipage}
  12517. }
  12518. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12519. \label{fig:c2-concrete-syntax}
  12520. \end{figure}
  12521. \begin{figure}[tp]
  12522. \fbox{
  12523. \begin{minipage}{0.96\textwidth}
  12524. \small
  12525. \[
  12526. \begin{array}{lcl}
  12527. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12528. \\
  12529. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12530. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12531. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12532. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12533. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12534. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12535. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12536. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12537. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12538. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12539. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12540. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12541. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12542. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12543. \LangCFun{} & ::= & \Def\ldots
  12544. \end{array}
  12545. \]
  12546. \end{minipage}
  12547. }
  12548. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12549. \label{fig:c3-concrete-syntax}
  12550. \end{figure}
  12551. \cleardoublepage
  12552. \addcontentsline{toc}{chapter}{Index}
  12553. \printindex
  12554. \cleardoublepage
  12555. \bibliographystyle{plainnat}
  12556. \bibliography{all}
  12557. \addcontentsline{toc}{chapter}{Bibliography}
  12558. \end{document}
  12559. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  12560. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  12561. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  12562. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  12563. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  12564. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  12565. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  12566. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  12567. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  12568. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  12569. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  12570. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  12571. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  12572. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  12573. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  12574. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  12575. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  12576. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  12577. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  12578. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  12579. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  12580. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  12581. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  12582. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  12583. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  12584. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  12585. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12586. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12587. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12588. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12589. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12590. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12591. % LocalWords: alists arity github unordered pqueue exprs ret param
  12592. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12593. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12594. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12595. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12596. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12597. % LocalWords: ValueOf typechecker