book.tex 617 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \definecolor{lightgray}{gray}{1}
  17. \newcommand{\black}[1]{{\color{black} #1}}
  18. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  19. \newcommand{\gray}[1]{{\color{gray} #1}}
  20. \def\racketEd{0}
  21. \def\pythonEd{1}
  22. \def\edition{1}
  23. % material that is specific to the Racket edition of the book
  24. \newcommand{\racket}[1]{{\if\edition\racketEd\color{olive}{#1}\fi}}
  25. % would like a command for: \if\edition\racketEd\color{olive}
  26. % and : \fi\color{black}
  27. % material that is specific to the Python edition of the book
  28. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  29. %% For multiple indices:
  30. \usepackage{multind}
  31. \makeindex{subject}
  32. \makeindex{authors}
  33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  34. \if\edition\racketEd
  35. \lstset{%
  36. language=Lisp,
  37. basicstyle=\ttfamily\small,
  38. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  39. deletekeywords={read,mapping,vector},
  40. escapechar=|,
  41. columns=flexible,
  42. moredelim=[is][\color{red}]{~}{~},
  43. showstringspaces=false
  44. }
  45. \fi
  46. \if\edition\pythonEd
  47. \lstset{%
  48. language=Python,
  49. basicstyle=\ttfamily\small,
  50. morekeywords={match,case,bool,int},
  51. deletekeywords={},
  52. escapechar=|,
  53. columns=flexible,
  54. moredelim=[is][\color{red}]{~}{~},
  55. showstringspaces=false
  56. }
  57. \fi
  58. %%% Any shortcut own defined macros place here
  59. %% sample of author macro:
  60. \input{defs}
  61. \newtheorem{exercise}[theorem]{Exercise}
  62. % Adjusted settings
  63. \setlength{\columnsep}{4pt}
  64. %% \begingroup
  65. %% \setlength{\intextsep}{0pt}%
  66. %% \setlength{\columnsep}{0pt}%
  67. %% \begin{wrapfigure}{r}{0.5\textwidth}
  68. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  69. %% \caption{Basic layout}
  70. %% \end{wrapfigure}
  71. %% \lipsum[1]
  72. %% \endgroup
  73. \newbox\oiintbox
  74. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  75. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  76. \def\oiint{\copy\oiintbox}
  77. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  78. %\usepackage{showframe}
  79. \def\ShowFrameLinethickness{0.125pt}
  80. \addbibresource{book.bib}
  81. \begin{document}
  82. \frontmatter
  83. \HalfTitle{Essentials of Compilation, Python Edition}
  84. \halftitlepage
  85. %% \begin{seriespage}
  86. %% \seriestitle{Industrial Economics}
  87. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  88. %% \title{Engineering and Economics}
  89. %% \author{Samuel Endgrove}
  90. %% \title{Structural Economics: From Beginning to End}
  91. %% \author{Guang Xi}
  92. %% \end{seriespage}
  93. \Title{Essentials of Compilation, Python Edition}
  94. \Booksubtitle{The Incremental, Nano-Pass Approach}
  95. %\edition{First Edition}
  96. \BookAuthor{Jeremy G. Siek}
  97. \imprint{The MIT Press\\
  98. Cambridge, Massachusetts\\
  99. London, England}
  100. \begin{copyrightpage}
  101. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  102. or personal downloading under the
  103. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  104. license.
  105. Copyright in this monograph has been licensed exclusively to The MIT
  106. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  107. version to the public in 2022. All inquiries regarding rights should
  108. be addressed to The MIT Press, Rights and Permissions Department.
  109. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  110. %% All rights reserved. No part of this book may be reproduced in any
  111. %% form by any electronic or mechanical means (including photocopying,
  112. %% recording, or information storage and retrieval) without permission in
  113. %% writing from the publisher.
  114. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  115. %% United States of America.
  116. %% Library of Congress Cataloging-in-Publication Data is available.
  117. %% ISBN:
  118. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  119. \end{copyrightpage}
  120. \dedication{This book is dedicated to the programming language wonks
  121. at Indiana University.}
  122. %% \begin{epigraphpage}
  123. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  124. %% \textit{Book Name if any}}
  125. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  126. %% \end{epigraphpage}
  127. \tableofcontents
  128. %\listoffigures
  129. %\listoftables
  130. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  131. \chapter*{Preface}
  132. \addcontentsline{toc}{fmbm}{Preface}
  133. There is a magical moment when a programmer presses the ``run'' button
  134. and the software begins to execute. Somehow a program written in a
  135. high-level language is running on a computer that is only capable of
  136. shuffling bits. Here we reveal the wizardry that makes that moment
  137. possible. Beginning with the groundbreaking work of Backus and
  138. colleagues in the 1950s, computer scientists discovered techniques for
  139. constructing programs, called \emph{compilers}, that automatically
  140. translate high-level programs into machine code.
  141. We take you on a journey by constructing your own compiler for a small
  142. but powerful language. Along the way we explain the essential
  143. concepts, algorithms, and data structures that underlie compilers. We
  144. develop your understanding of how programs are mapped onto computer
  145. hardware, which is helpful when reasoning about properties at the
  146. junction between hardware and software such as execution time,
  147. software errors, and security vulnerabilities. For those interested
  148. in pursuing compiler construction, our goal is to provide a
  149. stepping-stone to advanced topics such as just-in-time compilation,
  150. program analysis, and program optimization. For those interested in
  151. designing and implementing programming languages, we connect
  152. language design choices to their impact on the compiler and the generated
  153. code.
  154. A compiler is typically organized as a sequence of stages that
  155. progressively translate a program to code that runs on hardware. We
  156. take this approach to the extreme by partitioning our compiler into a
  157. large number of \emph{nanopasses}, each of which performs a single
  158. task. This allows us to test the output of each pass in isolation, and
  159. furthermore, allows us to focus our attention which makes the compiler
  160. far easier to understand.
  161. The most familiar approach to describing compilers is with one pass
  162. per chapter. The problem with that approach is it obfuscates how
  163. language features motivate design choices in a compiler. We take an
  164. \emph{incremental} approach in which we build a complete compiler in
  165. each chapter, starting with a small input language that includes only
  166. arithmetic and variables and we add new language features in
  167. subsequent chapters.
  168. Our choice of language features is designed to elicit the fundamental
  169. concepts and algorithms used in compilers.
  170. \begin{itemize}
  171. \item We begin with integer arithmetic and local variables in
  172. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  173. the fundamental tools of compiler construction: \emph{abstract
  174. syntax trees} and \emph{recursive functions}.
  175. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  176. \emph{graph coloring} to assign variables to machine registers.
  177. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  178. an elegant recursive algorithm for translating them into conditional
  179. \code{goto}'s.
  180. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  181. programming languages with the addition of loops\racket{ and mutable
  182. variables}. This elicits the need for \emph{dataflow
  183. analysis} in the register allocator.
  184. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  185. \emph{garbage collection}.
  186. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  187. but lack lexical scoping, similar to the C programming
  188. language~\citep{Kernighan:1988nx} except that we generate efficient
  189. tail calls. The reader learns about the procedure call stack,
  190. \emph{calling conventions}, and their interaction with register
  191. allocation and garbage collection.
  192. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  193. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  194. \emph{closure conversion}, in which lambdas are translated into a
  195. combination of functions and tuples.
  196. % Chapter about classes and objects?
  197. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  198. point the input languages are statically typed. The reader extends
  199. the statically typed language with an \code{Any} type which serves
  200. as a target for compiling the dynamically typed language.
  201. {\if\edition\pythonEd
  202. \item Chapter~\ref{ch:Robject} adds support for \emph{objects} and
  203. \emph{classes}.
  204. \fi}
  205. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  206. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  207. in which different regions of a program may be static or dynamically
  208. typed. The reader implements runtime support for \emph{proxies} that
  209. allow values to safely move between regions.
  210. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  211. leveraging the \code{Any} type and type casts developed in Chapters
  212. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  213. \end{itemize}
  214. There are many language features that we do not include. Our choices
  215. balance the incidental complexity of a feature versus the fundamental
  216. concepts that it exposes. For example, we include tuples and not
  217. records because they both elicit the study of heap allocation and
  218. garbage collection but records come with more incidental complexity.
  219. Since 2009 drafts of this book have served as the textbook for 16-week
  220. compiler courses for upper-level undergraduates and first-year
  221. graduate students at the University of Colorado and Indiana
  222. University.
  223. %
  224. Students come into the course having learned the basics of
  225. programmming, data structures and algorithms, and discrete
  226. mathematics.
  227. %
  228. At the beginning of the course, students form groups of 2-4 people.
  229. The groups complete one chapter every two weeks, starting with
  230. Chapter~\ref{ch:Rvar}. Many chapters include a challenge problem that
  231. we assign to the graduate students. The last two weeks of the course
  232. involve a final project in which students design and implement a
  233. compiler extension of their choosing. Chapters~\ref{ch:Rgrad} and
  234. \ref{ch:Rpoly} can be used in support of these projects or they can
  235. replace some of the other chapters. For example, a course with an
  236. emphasis on statically-typed imperative languages could include
  237. Chapter~\ref{ch:Rpoly} but skip Chapter~\ref{ch:Rdyn}. For compiler
  238. courses at univerities on the quarter system, with 10 weeks, we
  239. recommend completing up through Chapter~\ref{ch:Rfun}. (If pressed
  240. for time, one can skip Chapter~\ref{ch:Rvec} but still include
  241. Chapter~\ref{ch:Rfun} by limiting the number of parameters allowed in
  242. functions.) Figure~\ref{fig:chapter-dependences} depicts the
  243. dependencies between chapters.
  244. This book has also been used in compiler courses at California
  245. Polytechnic State University, Portland State University, Rose–Hulman
  246. Institute of Technology, University of Massachusetts Lowell, and the
  247. University of Vermont.
  248. \begin{figure}[tp]
  249. {\if\edition\racketEd
  250. \begin{tikzpicture}[baseline=(current bounding box.center)]
  251. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  252. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  253. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  254. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Conditionals};
  255. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  256. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  257. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  258. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  259. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  260. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  261. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  262. \path[->] (C1) edge [above] node {} (C2);
  263. \path[->] (C2) edge [above] node {} (C3);
  264. \path[->] (C3) edge [above] node {} (C4);
  265. \path[->] (C4) edge [above] node {} (C5);
  266. \path[->] (C5) edge [above] node {} (C6);
  267. \path[->] (C6) edge [above] node {} (C7);
  268. \path[->] (C4) edge [above] node {} (C8);
  269. \path[->] (C4) edge [above] node {} (C9);
  270. \path[->] (C8) edge [above] node {} (C10);
  271. \path[->] (C10) edge [above] node {} (C11);
  272. \end{tikzpicture}
  273. \fi}
  274. {\if\edition\pythonEd
  275. \begin{tikzpicture}[baseline=(current bounding box.center)]
  276. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  277. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  278. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  279. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Conditionals};
  280. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  281. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  282. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  283. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  284. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Robject} Objects};
  285. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  286. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  287. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  288. \path[->] (C1) edge [above] node {} (C2);
  289. \path[->] (C2) edge [above] node {} (C3);
  290. \path[->] (C3) edge [above] node {} (C4);
  291. \path[->] (C4) edge [above] node {} (C5);
  292. \path[->] (C5) edge [above] node {} (C6);
  293. \path[->] (C6) edge [above] node {} (C7);
  294. \path[->] (C4) edge [above] node {} (C8);
  295. \path[->] (C4) edge [above] node {} (C9);
  296. \path[->] (C8) edge [above] node {} (C10);
  297. \path[->] (C8) edge [above] node {} (CO);
  298. \path[->] (C10) edge [above] node {} (C11);
  299. \end{tikzpicture}
  300. \fi}
  301. \caption{Diagram of chapter dependencies.}
  302. \label{fig:chapter-dependences}
  303. \end{figure}
  304. \racket{
  305. We use the \href{https://racket-lang.org/}{Racket} language both for
  306. the implementation of the compiler and for the input language, so the
  307. reader should be proficient with Racket or Scheme. There are many
  308. excellent resources for learning Scheme and
  309. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  310. }
  311. \python{
  312. This edition of the book uses \href{https://www.python.org/}{Python}
  313. both for the implementation of the compiler and for the input language, so the
  314. reader should be proficient with Python. There are many
  315. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  316. }
  317. The support code for this book is in the \code{github} repository at
  318. the following URL:
  319. \if\edition\racketEd
  320. \begin{center}\small
  321. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  322. \end{center}
  323. \fi
  324. \if\edition\pythonEd
  325. \begin{center}\small
  326. \url{https://github.com/IUCompilerCourse/}
  327. \end{center}
  328. \fi
  329. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  330. is helpful but not necessary for the reader to have taken a computer
  331. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  332. of x86-64 assembly language that are needed.
  333. %
  334. We follow the System V calling
  335. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  336. that we generate works with the runtime system (written in C) when it
  337. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  338. operating systems on Intel hardware.
  339. %
  340. On the Windows operating system, \code{gcc} uses the Microsoft x64
  341. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  342. assembly code that we generate does \emph{not} work with the runtime
  343. system on Windows. One workaround is to use a virtual machine with
  344. Linux as the guest operating system.
  345. \section*{Acknowledgments}
  346. The tradition of compiler construction at Indiana University goes back
  347. to research and courses on programming languages by Daniel Friedman in
  348. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  349. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  350. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  351. the compiler course and continued the development of Chez Scheme.
  352. %
  353. The compiler course evolved to incorporate novel pedagogical ideas
  354. while also including elements of real-world compilers. One of
  355. Friedman's ideas was to split the compiler into many small
  356. passes. Another idea, called ``the game'', was to test the code
  357. generated by each pass using interpreters.
  358. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  359. developed infrastructure to support this approach and evolved the
  360. course to use even smaller
  361. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  362. design decisions in this book are inspired by the assignment
  363. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  364. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  365. organization of the course made it difficult for students to
  366. understand the rationale for the compiler design. Ghuloum proposed the
  367. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  368. on.
  369. We thank the many students who served as teaching assistants for the
  370. compiler course at IU and made suggestions for improving the book
  371. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  372. thank Andre Kuhlenschmidt for his work on the garbage collector,
  373. Michael Vollmer for his work on efficient tail calls, and Michael
  374. Vitousek for his help running the first offering of the incremental
  375. compiler course at IU.
  376. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  377. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  378. for teaching courses based on drafts of this book and for their
  379. invaluable feedback.
  380. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  381. course in the early 2000's and especially for finding the bug that
  382. sent our garbage collector on a wild goose chase!
  383. \mbox{}\\
  384. \noindent Jeremy G. Siek \\
  385. Bloomington, Indiana
  386. \mainmatter
  387. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  388. \chapter{Preliminaries}
  389. \label{ch:trees-recur}
  390. In this chapter we review the basic tools that are needed to implement
  391. a compiler. Programs are typically input by a programmer as text,
  392. i.e., a sequence of characters. The program-as-text representation is
  393. called \emph{concrete syntax}. We use concrete syntax to concisely
  394. write down and talk about programs. Inside the compiler, we use
  395. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  396. that efficiently supports the operations that the compiler needs to
  397. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  398. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  399. from concrete syntax to abstract syntax is a process called
  400. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  401. implementation of parsing in this book.
  402. %
  403. \racket{A parser is provided in the support code for translating from
  404. concrete to abstract syntax.}
  405. %
  406. \python{We use Python's \code{ast} module to translate from concrete
  407. to abstract syntax.}
  408. ASTs can be represented in many different ways inside the compiler,
  409. depending on the programming language used to write the compiler.
  410. %
  411. \racket{We use Racket's
  412. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  413. feature to represent ASTs (Section~\ref{sec:ast}).}
  414. %
  415. \python{We use Python classes and objects to represent ASTs, especially the
  416. classes defined in the standard \code{ast} module for the Python
  417. source language.}
  418. %
  419. We use grammars to define the abstract syntax of programming languages
  420. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  421. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  422. recursive functions to construct and deconstruct ASTs
  423. (Section~\ref{sec:recursion}). This chapter provides an brief
  424. introduction to these ideas.
  425. \racket{\index{subject}{struct}}
  426. \python{\index{subject}{class}\index{subject}{object}}
  427. \section{Abstract Syntax Trees}
  428. \label{sec:ast}
  429. Compilers use abstract syntax trees to represent programs because they
  430. often need to ask questions like: for a given part of a program, what
  431. kind of language feature is it? What are its sub-parts? Consider the
  432. program on the left and its AST on the right. This program is an
  433. addition operation and it has two sub-parts, a
  434. \racket{read}\python{input} operation and a negation. The negation has
  435. another sub-part, the integer constant \code{8}. By using a tree to
  436. represent the program, we can easily follow the links to go from one
  437. part of a program to its sub-parts.
  438. \begin{center}
  439. \begin{minipage}{0.4\textwidth}
  440. \if\edition\racketEd
  441. \begin{lstlisting}
  442. (+ (read) (- 8))
  443. \end{lstlisting}
  444. \fi
  445. \if\edition\pythonEd
  446. \begin{lstlisting}
  447. input_int() + -8
  448. \end{lstlisting}
  449. \fi
  450. \end{minipage}
  451. \begin{minipage}{0.4\textwidth}
  452. \begin{equation}
  453. \begin{tikzpicture}
  454. \node[draw] (plus) at (0 , 0) {\key{+}};
  455. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  456. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  457. \node[draw] (8) at (1 , -3) {\key{8}};
  458. \draw[->] (plus) to (read);
  459. \draw[->] (plus) to (minus);
  460. \draw[->] (minus) to (8);
  461. \end{tikzpicture}
  462. \label{eq:arith-prog}
  463. \end{equation}
  464. \end{minipage}
  465. \end{center}
  466. We use the standard terminology for trees to describe ASTs: each
  467. rectangle above is called a \emph{node}. The arrows connect a node to its
  468. \emph{children} (which are also nodes). The top-most node is the
  469. \emph{root}. Every node except for the root has a \emph{parent} (the
  470. node it is the child of). If a node has no children, it is a
  471. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  472. \index{subject}{node}
  473. \index{subject}{children}
  474. \index{subject}{root}
  475. \index{subject}{parent}
  476. \index{subject}{leaf}
  477. \index{subject}{internal node}
  478. %% Recall that an \emph{symbolic expression} (S-expression) is either
  479. %% \begin{enumerate}
  480. %% \item an atom, or
  481. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  482. %% where $e_1$ and $e_2$ are each an S-expression.
  483. %% \end{enumerate}
  484. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  485. %% null value \code{'()}, etc. We can create an S-expression in Racket
  486. %% simply by writing a backquote (called a quasi-quote in Racket)
  487. %% followed by the textual representation of the S-expression. It is
  488. %% quite common to use S-expressions to represent a list, such as $a, b
  489. %% ,c$ in the following way:
  490. %% \begin{lstlisting}
  491. %% `(a . (b . (c . ())))
  492. %% \end{lstlisting}
  493. %% Each element of the list is in the first slot of a pair, and the
  494. %% second slot is either the rest of the list or the null value, to mark
  495. %% the end of the list. Such lists are so common that Racket provides
  496. %% special notation for them that removes the need for the periods
  497. %% and so many parenthesis:
  498. %% \begin{lstlisting}
  499. %% `(a b c)
  500. %% \end{lstlisting}
  501. %% The following expression creates an S-expression that represents AST
  502. %% \eqref{eq:arith-prog}.
  503. %% \begin{lstlisting}
  504. %% `(+ (read) (- 8))
  505. %% \end{lstlisting}
  506. %% When using S-expressions to represent ASTs, the convention is to
  507. %% represent each AST node as a list and to put the operation symbol at
  508. %% the front of the list. The rest of the list contains the children. So
  509. %% in the above case, the root AST node has operation \code{`+} and its
  510. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  511. %% diagram \eqref{eq:arith-prog}.
  512. %% To build larger S-expressions one often needs to splice together
  513. %% several smaller S-expressions. Racket provides the comma operator to
  514. %% splice an S-expression into a larger one. For example, instead of
  515. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  516. %% we could have first created an S-expression for AST
  517. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  518. %% S-expression.
  519. %% \begin{lstlisting}
  520. %% (define ast1.4 `(- 8))
  521. %% (define ast1_1 `(+ (read) ,ast1.4))
  522. %% \end{lstlisting}
  523. %% In general, the Racket expression that follows the comma (splice)
  524. %% can be any expression that produces an S-expression.
  525. {\if\edition\racketEd\color{olive}
  526. We define a Racket \code{struct} for each kind of node. For this
  527. chapter we require just two kinds of nodes: one for integer constants
  528. and one for primitive operations. The following is the \code{struct}
  529. definition for integer constants.
  530. \begin{lstlisting}
  531. (struct Int (value))
  532. \end{lstlisting}
  533. An integer node includes just one thing: the integer value.
  534. To create an AST node for the integer $8$, we write \INT{8}.
  535. \begin{lstlisting}
  536. (define eight (Int 8))
  537. \end{lstlisting}
  538. We say that the value created by \INT{8} is an
  539. \emph{instance} of the
  540. \code{Int} structure.
  541. The following is the \code{struct} definition for primitive operations.
  542. \begin{lstlisting}
  543. (struct Prim (op args))
  544. \end{lstlisting}
  545. A primitive operation node includes an operator symbol \code{op} and a
  546. list of child \code{args}. For example, to create an AST that negates
  547. the number $8$, we write \code{(Prim '- (list eight))}.
  548. \begin{lstlisting}
  549. (define neg-eight (Prim '- (list eight)))
  550. \end{lstlisting}
  551. Primitive operations may have zero or more children. The \code{read}
  552. operator has zero children:
  553. \begin{lstlisting}
  554. (define rd (Prim 'read '()))
  555. \end{lstlisting}
  556. whereas the addition operator has two children:
  557. \begin{lstlisting}
  558. (define ast1_1 (Prim '+ (list rd neg-eight)))
  559. \end{lstlisting}
  560. We have made a design choice regarding the \code{Prim} structure.
  561. Instead of using one structure for many different operations
  562. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  563. structure for each operation, as follows.
  564. \begin{lstlisting}
  565. (struct Read ())
  566. (struct Add (left right))
  567. (struct Neg (value))
  568. \end{lstlisting}
  569. The reason we choose to use just one structure is that in many parts
  570. of the compiler the code for the different primitive operators is the
  571. same, so we might as well just write that code once, which is enabled
  572. by using a single structure.
  573. \fi}
  574. {\if\edition\pythonEd
  575. We use a Python \code{class} for each kind of node.
  576. The following is the class definition for constants.
  577. \begin{lstlisting}
  578. class Constant:
  579. def __init__(self, value):
  580. self.value = value
  581. \end{lstlisting}
  582. An integer constant node includes just one thing: the integer value.
  583. To create an AST node for the integer $8$, we write \INT{8}.
  584. \begin{lstlisting}
  585. eight = Constant(8)
  586. \end{lstlisting}
  587. We say that the value created by \INT{8} is an
  588. \emph{instance} of the \code{Constant} class.
  589. The following is the class definition for unary operators.
  590. \begin{lstlisting}
  591. class UnaryOp:
  592. def __init__(self, op, operand):
  593. self.op = op
  594. self.operand = operand
  595. \end{lstlisting}
  596. The specific operation is specified by the \code{op} parameter. For
  597. example, the class \code{USub} is for unary subtraction. (More unary
  598. operators are introduced in later chapters.) To create an AST that
  599. negates the number $8$, we write the following.
  600. \begin{lstlisting}
  601. neg_eight = UnaryOp(USub(), eight)
  602. \end{lstlisting}
  603. The call to the \code{input\_int} function is represented by the
  604. \code{Call} and \code{Name} classes.
  605. \begin{lstlisting}
  606. class Call:
  607. def __init__(self, func, args):
  608. self.func = func
  609. self.args = args
  610. class Name:
  611. def __init__(self, id):
  612. self.id = id
  613. \end{lstlisting}
  614. To create an AST node that calls \code{input\_int}, we write
  615. \begin{lstlisting}
  616. read = Call(Name('input_int'), [])
  617. \end{lstlisting}
  618. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  619. the \code{BinOp} class for binary operators.
  620. \begin{lstlisting}
  621. class BinOp:
  622. def __init__(self, left, op, right):
  623. self.op = op
  624. self.left = left
  625. self.right = right
  626. \end{lstlisting}
  627. Similar to \code{UnaryOp}, the specific operation is specified by the
  628. \code{op} parameter, which for now is just an instance of the
  629. \code{Add} class. So to create the AST node that adds negative eight
  630. to some user input, we write the following.
  631. \begin{lstlisting}
  632. ast1_1 = BinOp(read, Add(), neg_eight)
  633. \end{lstlisting}
  634. \fi}
  635. When compiling a program such as \eqref{eq:arith-prog}, we need to
  636. know that the operation associated with the root node is addition and
  637. we need to be able to access its two children. \racket{Racket}\python{Python}
  638. provides pattern matching to support these kinds of queries, as we see in
  639. Section~\ref{sec:pattern-matching}.
  640. In this book, we often write down the concrete syntax of a program
  641. even when we really have in mind the AST because the concrete syntax
  642. is more concise. We recommend that, in your mind, you always think of
  643. programs as abstract syntax trees.
  644. \section{Grammars}
  645. \label{sec:grammar}
  646. \index{subject}{integer}
  647. \index{subject}{literal}
  648. \index{subject}{constant}
  649. A programming language can be thought of as a \emph{set} of programs.
  650. The set is typically infinite (one can always create larger and larger
  651. programs), so one cannot simply describe a language by listing all of
  652. the programs in the language. Instead we write down a set of rules, a
  653. \emph{grammar}, for building programs. Grammars are often used to
  654. define the concrete syntax of a language, but they can also be used to
  655. describe the abstract syntax. We write our rules in a variant of
  656. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  657. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  658. As an example, we describe a small language, named \LangInt{}, that consists of
  659. integers and arithmetic operations.
  660. \index{subject}{grammar}
  661. The first grammar rule for the abstract syntax of \LangInt{} says that an
  662. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  663. \begin{equation}
  664. \Exp ::= \INT{\Int} \label{eq:arith-int}
  665. \end{equation}
  666. %
  667. Each rule has a left-hand-side and a right-hand-side.
  668. If you have an AST node that matches the
  669. right-hand-side, then you can categorize it according to the
  670. left-hand-side.
  671. %
  672. A name such as $\Exp$ that is defined by the grammar rules is a
  673. \emph{non-terminal}. \index{subject}{non-terminal}
  674. %
  675. The name $\Int$ is also a non-terminal, but instead of defining it
  676. with a grammar rule, we define it with the following explanation. An
  677. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  678. $-$ (for negative integers), such that the sequence of decimals
  679. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  680. the representation of integers using 63 bits, which simplifies several
  681. aspects of compilation. \racket{Thus, these integers corresponds to
  682. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  683. \python{In contrast, integers in Python have unlimited precision, but
  684. the techniques need to handle unlimited precision fall outside the
  685. scope of this book.}
  686. The second grammar rule is the \READOP{} operation that receives an
  687. input integer from the user of the program.
  688. \begin{equation}
  689. \Exp ::= \READ{} \label{eq:arith-read}
  690. \end{equation}
  691. The third rule says that, given an $\Exp$ node, the negation of that
  692. node is also an $\Exp$.
  693. \begin{equation}
  694. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  695. \end{equation}
  696. Symbols in typewriter font are \emph{terminal} symbols and must
  697. literally appear in the program for the rule to be applicable.
  698. \index{subject}{terminal}
  699. We can apply these rules to categorize the ASTs that are in the
  700. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  701. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  702. following AST is an $\Exp$.
  703. \begin{center}
  704. \begin{minipage}{0.5\textwidth}
  705. \NEG{\INT{\code{8}}}
  706. \end{minipage}
  707. \begin{minipage}{0.25\textwidth}
  708. \begin{equation}
  709. \begin{tikzpicture}
  710. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  711. \node[draw, circle] (8) at (0, -1.2) {$8$};
  712. \draw[->] (minus) to (8);
  713. \end{tikzpicture}
  714. \label{eq:arith-neg8}
  715. \end{equation}
  716. \end{minipage}
  717. \end{center}
  718. The next grammar rule is for addition expressions:
  719. \begin{equation}
  720. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  721. \end{equation}
  722. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  723. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  724. \eqref{eq:arith-read} and we have already categorized
  725. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  726. to show that
  727. \[
  728. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  729. \]
  730. is an $\Exp$ in the \LangInt{} language.
  731. If you have an AST for which the above rules do not apply, then the
  732. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  733. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  734. because there are no rules for the \key{-} operator with two
  735. arguments. Whenever we define a language with a grammar, the language
  736. only includes those programs that are justified by the grammar rules.
  737. {\if\edition\pythonEd
  738. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  739. There is a statement for printing the value of an expression
  740. \[
  741. \Stmt{} ::= \PRINT{\Exp}
  742. \]
  743. and a statement that evaluates an expression but ignores the result.
  744. \[
  745. \Stmt{} ::= \EXPR{\Exp}
  746. \]
  747. \fi}
  748. {\if\edition\racketEd\color{olive}
  749. The last grammar rule for \LangInt{} states that there is a
  750. \code{Program} node to mark the top of the whole program:
  751. \[
  752. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  753. \]
  754. The \code{Program} structure is defined as follows
  755. \begin{lstlisting}
  756. (struct Program (info body))
  757. \end{lstlisting}
  758. where \code{body} is an expression. In later chapters, the \code{info}
  759. part will be used to store auxiliary information but for now it is
  760. just the empty list.
  761. \fi}
  762. {\if\edition\pythonEd
  763. The last grammar rule for \LangInt{} states that there is a
  764. \code{Module} node to mark the top of the whole program:
  765. \[
  766. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  767. \]
  768. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  769. this case, a list of statements.
  770. %
  771. The \code{Module} class is defined as follows
  772. \begin{lstlisting}
  773. class Module:
  774. def __init__(self, body):
  775. self.body = body
  776. \end{lstlisting}
  777. where \code{body} is a list of statements.
  778. \fi}
  779. It is common to have many grammar rules with the same left-hand side
  780. but different right-hand sides, such as the rules for $\Exp$ in the
  781. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  782. combine several right-hand-sides into a single rule.
  783. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  784. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  785. defined in Figure~\ref{fig:r0-concrete-syntax}.
  786. \racket{The \code{read-program} function provided in
  787. \code{utilities.rkt} of the support code reads a program in from a
  788. file (the sequence of characters in the concrete syntax of Racket)
  789. and parses it into an abstract syntax tree. See the description of
  790. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  791. details.}
  792. \python{The \code{parse} function in Python's \code{ast} module
  793. converts the concrete syntax (represented as a string) into an
  794. abstract syntax tree.}
  795. \begin{figure}[tp]
  796. \fbox{
  797. \begin{minipage}{0.96\textwidth}
  798. {\if\edition\racketEd\color{olive}
  799. \[
  800. \begin{array}{rcl}
  801. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  802. \LangInt{} &::=& \Exp
  803. \end{array}
  804. \]
  805. \fi}
  806. {\if\edition\pythonEd
  807. \[
  808. \begin{array}{rcl}
  809. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  810. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  811. \LangInt{} &::=& \Stmt^{*}
  812. \end{array}
  813. \]
  814. \fi}
  815. \end{minipage}
  816. }
  817. \caption{The concrete syntax of \LangInt{}.}
  818. \label{fig:r0-concrete-syntax}
  819. \end{figure}
  820. \begin{figure}[tp]
  821. \fbox{
  822. \begin{minipage}{0.96\textwidth}
  823. {\if\edition\racketEd\color{olive}
  824. \[
  825. \begin{array}{rcl}
  826. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  827. &\MID& \ADD{\Exp}{\Exp} \\
  828. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  829. \end{array}
  830. \]
  831. \fi}
  832. {\if\edition\pythonEd
  833. \[
  834. \begin{array}{rcl}
  835. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  836. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  837. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  838. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  839. \end{array}
  840. \]
  841. \fi}
  842. \end{minipage}
  843. }
  844. \caption{The abstract syntax of \LangInt{}.}
  845. \label{fig:r0-syntax}
  846. \end{figure}
  847. \section{Pattern Matching}
  848. \label{sec:pattern-matching}
  849. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  850. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  851. \texttt{match} feature to access the parts of a value.
  852. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  853. \begin{center}
  854. \begin{minipage}{0.5\textwidth}
  855. {\if\edition\racketEd\color{olive}
  856. \begin{lstlisting}
  857. (match ast1_1
  858. [(Prim op (list child1 child2))
  859. (print op)])
  860. \end{lstlisting}
  861. \fi}
  862. {\if\edition\pythonEd
  863. \begin{lstlisting}
  864. match ast1_1:
  865. case BinOp(child1, op, child2):
  866. print(op)
  867. \end{lstlisting}
  868. \fi}
  869. \end{minipage}
  870. \end{center}
  871. {\if\edition\racketEd\color{olive}
  872. %
  873. In the above example, the \texttt{match} form checks whether the AST
  874. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  875. three pattern variables \texttt{op}, \texttt{child1}, and
  876. \texttt{child2}, and then prints out the operator. In general, a match
  877. clause consists of a \emph{pattern} and a
  878. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  879. to be either a pattern variable, a structure name followed by a
  880. pattern for each of the structure's arguments, or an S-expression
  881. (symbols, lists, etc.). (See Chapter 12 of The Racket
  882. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  883. and Chapter 9 of The Racket
  884. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  885. for a complete description of \code{match}.)
  886. %
  887. The body of a match clause may contain arbitrary Racket code. The
  888. pattern variables can be used in the scope of the body, such as
  889. \code{op} in \code{(print op)}.
  890. %
  891. \fi}
  892. %
  893. %
  894. {\if\edition\pythonEd
  895. %
  896. In the above example, the \texttt{match} form checks whether the AST
  897. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  898. three pattern variables \texttt{child1}, \texttt{op}, and
  899. \texttt{child2}, and then prints out the operator. In general, each
  900. \code{case} consists of a \emph{pattern} and a
  901. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  902. to be either a pattern variable, a class name followed by a pattern
  903. for each of its constructor's arguments, or other literals such as
  904. strings, lists, etc.
  905. %
  906. The body of each \code{case} may contain arbitrary Python code. The
  907. pattern variables can be used in the body, such as \code{op} in
  908. \code{print(op)}.
  909. %
  910. \fi}
  911. A \code{match} form may contain several clauses, as in the following
  912. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  913. the AST. The \code{match} proceeds through the clauses in order,
  914. checking whether the pattern can match the input AST. The body of the
  915. first clause that matches is executed. The output of \code{leaf} for
  916. several ASTs is shown on the right.
  917. \begin{center}
  918. \begin{minipage}{0.6\textwidth}
  919. {\if\edition\racketEd\color{olive}
  920. \begin{lstlisting}
  921. (define (leaf arith)
  922. (match arith
  923. [(Int n) #t]
  924. [(Prim 'read '()) #t]
  925. [(Prim '- (list e1)) #f]
  926. [(Prim '+ (list e1 e2)) #f]))
  927. (leaf (Prim 'read '()))
  928. (leaf (Prim '- (list (Int 8))))
  929. (leaf (Int 8))
  930. \end{lstlisting}
  931. \fi}
  932. {\if\edition\pythonEd
  933. \begin{lstlisting}
  934. def leaf(arith):
  935. match arith:
  936. case Constant(n):
  937. return True
  938. case Call(Name('input_int'), []):
  939. return True
  940. case UnaryOp(USub(), e1):
  941. return False
  942. case BinOp(e1, Add(), e2):
  943. return False
  944. print(leaf(Call(Name('input_int'), [])))
  945. print(leaf(UnaryOp(USub(), eight)))
  946. print(leaf(Constant(8)))
  947. \end{lstlisting}
  948. \fi}
  949. \end{minipage}
  950. \vrule
  951. \begin{minipage}{0.25\textwidth}
  952. {\if\edition\racketEd\color{olive}
  953. \begin{lstlisting}
  954. #t
  955. #f
  956. #t
  957. \end{lstlisting}
  958. \fi}
  959. {\if\edition\pythonEd
  960. \begin{lstlisting}
  961. True
  962. False
  963. True
  964. \end{lstlisting}
  965. \fi}
  966. \end{minipage}
  967. \end{center}
  968. When writing a \code{match}, we refer to the grammar definition to
  969. identify which non-terminal we are expecting to match against, then we
  970. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  971. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  972. corresponding right-hand side of a grammar rule. For the \code{match}
  973. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  974. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  975. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  976. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  977. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  978. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  979. patterns, replace non-terminals such as $\Exp$ with pattern variables
  980. of your choice (e.g. \code{e1} and \code{e2}).
  981. \section{Recursive Functions}
  982. \label{sec:recursion}
  983. \index{subject}{recursive function}
  984. Programs are inherently recursive. For example, an expression is often
  985. made of smaller expressions. Thus, the natural way to process an
  986. entire program is with a recursive function. As a first example of
  987. such a recursive function, we define the function \code{exp} in
  988. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  989. determines whether or not it is an expression in \LangInt{}.
  990. %
  991. We say that a function is defined by \emph{structural recursion} when
  992. it is defined using a sequence of match \racket{clauses}\python{cases}
  993. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  994. makes a recursive call on each
  995. child node.\footnote{This principle of structuring code according to
  996. the data definition is advocated in the book \emph{How to Design
  997. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  998. \python{We define a second function, named \code{stmt}, that recognizes
  999. whether a value is a \LangInt{} statement.}
  1000. \python{Finally, }
  1001. Figure~\ref{fig:exp-predicate} \racket{also} defines \racket{\code{Rint}}\python{\code{Pint}}, which
  1002. determines whether an AST is a program in \LangInt{}. In general we can
  1003. expect to write one recursive function to handle each non-terminal in
  1004. a grammar.\index{subject}{structural recursion}
  1005. \begin{figure}[tp]
  1006. {\if\edition\racketEd\color{olive}
  1007. \begin{minipage}{0.7\textwidth}
  1008. \begin{lstlisting}
  1009. (define (exp ast)
  1010. (match ast
  1011. [(Int n) #t]
  1012. [(Prim 'read '()) #t]
  1013. [(Prim '- (list e)) (exp e)]
  1014. [(Prim '+ (list e1 e2))
  1015. (and (exp e1) (exp e2))]
  1016. [else #f]))
  1017. (define (Rint ast)
  1018. (match ast
  1019. [(Program '() e) (exp e)]
  1020. [else #f]))
  1021. (Rint (Program '() ast1_1)
  1022. (Rint (Program '()
  1023. (Prim '- (list (Prim 'read '())
  1024. (Prim '+ (list (Num 8)))))))
  1025. \end{lstlisting}
  1026. \end{minipage}
  1027. \vrule
  1028. \begin{minipage}{0.25\textwidth}
  1029. \begin{lstlisting}
  1030. #t
  1031. #f
  1032. \end{lstlisting}
  1033. \end{minipage}
  1034. \fi}
  1035. {\if\edition\pythonEd
  1036. \begin{minipage}{0.7\textwidth}
  1037. \begin{lstlisting}
  1038. def exp(e):
  1039. match e:
  1040. case Constant(n):
  1041. return True
  1042. case Call(Name('input_int'), []):
  1043. return True
  1044. case UnaryOp(USub(), e1):
  1045. return exp(e1)
  1046. case BinOp(e1, Add(), e2):
  1047. return exp(e1) and exp(e2)
  1048. case _:
  1049. return False
  1050. def stmt(s):
  1051. match s:
  1052. case Call(Name('print'), [e]):
  1053. return exp(e)
  1054. case Expr(e):
  1055. return exp(e)
  1056. case _:
  1057. return False
  1058. def P_int(p):
  1059. match p:
  1060. case Module(body):
  1061. return all([stmt(s) for s in body])
  1062. case _:
  1063. return False
  1064. print(P_int(Module([Expr(ast1_1)])))
  1065. print(P_int(Module([Expr(BinOp(read, Sub(),
  1066. UnaryOp(Add(), Constant(8))))])))
  1067. \end{lstlisting}
  1068. \end{minipage}
  1069. \vrule
  1070. \begin{minipage}{0.25\textwidth}
  1071. \begin{lstlisting}
  1072. True
  1073. False
  1074. \end{lstlisting}
  1075. \end{minipage}
  1076. \fi}
  1077. \caption{Example of recursive functions for \LangInt{}. These functions
  1078. recognize whether an AST is in \LangInt{}.}
  1079. \label{fig:exp-predicate}
  1080. \end{figure}
  1081. %% You may be tempted to merge the two functions into one, like this:
  1082. %% \begin{center}
  1083. %% \begin{minipage}{0.5\textwidth}
  1084. %% \begin{lstlisting}
  1085. %% (define (Rint ast)
  1086. %% (match ast
  1087. %% [(Int n) #t]
  1088. %% [(Prim 'read '()) #t]
  1089. %% [(Prim '- (list e)) (Rint e)]
  1090. %% [(Prim '+ (list e1 e2)) (and (Rint e1) (Rint e2))]
  1091. %% [(Program '() e) (Rint e)]
  1092. %% [else #f]))
  1093. %% \end{lstlisting}
  1094. %% \end{minipage}
  1095. %% \end{center}
  1096. %% %
  1097. %% Sometimes such a trick will save a few lines of code, especially when
  1098. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1099. %% \emph{not} recommended because it can get you into trouble.
  1100. %% %
  1101. %% For example, the above function is subtly wrong:
  1102. %% \lstinline{(Rint (Program '() (Program '() (Int 3))))}
  1103. %% returns true when it should return false.
  1104. \section{Interpreters}
  1105. \label{sec:interp_Rint}
  1106. \index{subject}{interpreter}
  1107. The behavior of a program is defined by the specification of the
  1108. programming language.
  1109. %
  1110. \racket{For example, the Scheme language is defined in the report by
  1111. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1112. reference manual~\citep{plt-tr}.}
  1113. %
  1114. \python{For example, the Python language is defined in the Python
  1115. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1116. %
  1117. In this book we use interpreters
  1118. to specify each language that we consider. An interpreter that is
  1119. designated as the definition of a language is called a
  1120. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1121. \index{subject}{definitional interpreter} We warm up by creating a
  1122. definitional interpreter for the \LangInt{} language, which serves as
  1123. a second example of structural recursion. The \racket{\code{interp\_Rint}}
  1124. \python{\code{interp\_Pint}}
  1125. function is defined in Figure~\ref{fig:interp_Rint}.
  1126. %
  1127. \racket{The body of the function is a match on the input program
  1128. followed by a call to the \lstinline{interp_exp} helper function,
  1129. which in turn has one match clause per grammar rule for \LangInt{}
  1130. expressions.}
  1131. %
  1132. \python{The body of the function matches on the \code{Module} AST node
  1133. and then invokes \code{interp\_stmt} on each statement in the
  1134. module. The \code{interp\_stmt} function includes a case for each
  1135. grammar rule of the \Stmt{} non-terminal and it calls
  1136. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1137. function includes a case for each grammar rule of the \Exp{}
  1138. non-terminal.}
  1139. \begin{figure}[tp]
  1140. {\if\edition\racketEd\color{olive}
  1141. \begin{lstlisting}
  1142. (define (interp_exp e)
  1143. (match e
  1144. [(Int n) n]
  1145. [(Prim 'read '())
  1146. (define r (read))
  1147. (cond [(fixnum? r) r]
  1148. [else (error 'interp_exp "read expected an integer" r)])]
  1149. [(Prim '- (list e))
  1150. (define v (interp_exp e))
  1151. (fx- 0 v)]
  1152. [(Prim '+ (list e1 e2))
  1153. (define v1 (interp_exp e1))
  1154. (define v2 (interp_exp e2))
  1155. (fx+ v1 v2)]))
  1156. (define (interp_Rint p)
  1157. (match p
  1158. [(Program '() e) (interp_exp e)]))
  1159. \end{lstlisting}
  1160. \fi}
  1161. {\if\edition\pythonEd
  1162. \begin{lstlisting}
  1163. def interp_exp(e):
  1164. match e:
  1165. case BinOp(left, Add(), right):
  1166. l = interp_exp(left)
  1167. r = interp_exp(right)
  1168. return l + r
  1169. case UnaryOp(USub(), v):
  1170. return - interp_exp(v)
  1171. case Constant(value):
  1172. return value
  1173. case Call(Name('input_int'), []):
  1174. return int(input())
  1175. def interp_stmt(s):
  1176. match s:
  1177. case Expr(Call(Name('print'), [arg])):
  1178. print(interp_exp(arg))
  1179. case Expr(value):
  1180. interp_exp(value)
  1181. def interp_P_int(p):
  1182. match p:
  1183. case Module(body):
  1184. for s in body:
  1185. interp_stmt(s)
  1186. \end{lstlisting}
  1187. \fi}
  1188. \caption{Interpreter for the \LangInt{} language.}
  1189. \label{fig:interp_Rint}
  1190. \end{figure}
  1191. Let us consider the result of interpreting a few \LangInt{} programs. The
  1192. following program adds two integers.
  1193. {\if\edition\racketEd\color{olive}
  1194. \begin{lstlisting}
  1195. (+ 10 32)
  1196. \end{lstlisting}
  1197. \fi}
  1198. {\if\edition\pythonEd
  1199. \begin{lstlisting}
  1200. print(10 + 32)
  1201. \end{lstlisting}
  1202. \fi}
  1203. The result is \key{42}, the answer to life, the universe, and
  1204. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1205. Galaxy} by Douglas Adams.}.
  1206. %
  1207. We wrote the above program in concrete syntax whereas the parsed
  1208. abstract syntax is:
  1209. {\if\edition\racketEd\color{olive}
  1210. \begin{lstlisting}
  1211. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1212. \end{lstlisting}
  1213. \fi}
  1214. {\if\edition\pythonEd
  1215. \begin{lstlisting}
  1216. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1217. \end{lstlisting}
  1218. \fi}
  1219. The next example demonstrates that expressions may be nested within
  1220. each other, in this case nesting several additions and negations.
  1221. {\if\edition\racketEd\color{olive}
  1222. \begin{lstlisting}
  1223. (+ 10 (- (+ 12 20)))
  1224. \end{lstlisting}
  1225. \fi}
  1226. {\if\edition\pythonEd
  1227. \begin{lstlisting}
  1228. print(10 + -(12 + 20))
  1229. \end{lstlisting}
  1230. \fi}
  1231. %
  1232. \noindent What is the result of the above program?
  1233. {\if\edition\racketEd\color{olive}
  1234. As mentioned previously, the \LangInt{} language does not support
  1235. arbitrarily-large integers, but only $63$-bit integers, so we
  1236. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1237. in Racket.
  1238. Suppose
  1239. \[
  1240. n = 999999999999999999
  1241. \]
  1242. which indeed fits in $63$-bits. What happens when we run the
  1243. following program in our interpreter?
  1244. \begin{lstlisting}
  1245. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1246. \end{lstlisting}
  1247. It produces an error:
  1248. \begin{lstlisting}
  1249. fx+: result is not a fixnum
  1250. \end{lstlisting}
  1251. We establish the convention that if running the definitional
  1252. interpreter on a program produces an error then the meaning of that
  1253. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1254. error is a \code{trapped-error}. A compiler for the language is under
  1255. no obligations regarding programs with unspecified behavior; it does
  1256. not have to produce an executable, and if it does, that executable can
  1257. do anything. On the other hand, if the error is a
  1258. \code{trapped-error}, then the compiler must produce an executable and
  1259. it is required to report that an error occurred. To signal an error,
  1260. exit with a return code of \code{255}. The interpreters in chapters
  1261. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1262. \code{trapped-error}.
  1263. \fi}
  1264. % TODO: how to deal with too-large integers in the Python interpreter?
  1265. %% This convention applies to the languages defined in this
  1266. %% book, as a way to simplify the student's task of implementing them,
  1267. %% but this convention is not applicable to all programming languages.
  1268. %%
  1269. Moving on to the last feature of the \LangInt{} language, the
  1270. \READOP{} operation prompts the user of the program for an integer.
  1271. Recall that program \eqref{eq:arith-prog} requests an integer input
  1272. and then subtracts \code{8}. So if we run
  1273. {\if\edition\racketEd\color{olive}
  1274. \begin{lstlisting}
  1275. (interp_Rint (Program '() ast1_1))
  1276. \end{lstlisting}
  1277. \fi}
  1278. {\if\edition\pythonEd
  1279. \begin{lstlisting}
  1280. interp_P_int(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1281. \end{lstlisting}
  1282. \fi}
  1283. \noindent and if the input is \code{50}, the result is \code{42}.
  1284. We include the \READOP{} operation in \LangInt{} so a clever student
  1285. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1286. during compilation to obtain the output and then generates the trivial
  1287. code to produce the output.\footnote{Yes, a clever student did this in the
  1288. first instance of this course!}
  1289. The job of a compiler is to translate a program in one language into a
  1290. program in another language so that the output program behaves the
  1291. same way as the input program. This idea is depicted in the
  1292. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1293. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1294. Given a compiler that translates from language $\mathcal{L}_1$ to
  1295. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1296. compiler must translate it into some program $P_2$ such that
  1297. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1298. same input $i$ yields the same output $o$.
  1299. \begin{equation} \label{eq:compile-correct}
  1300. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1301. \node (p1) at (0, 0) {$P_1$};
  1302. \node (p2) at (3, 0) {$P_2$};
  1303. \node (o) at (3, -2.5) {$o$};
  1304. \path[->] (p1) edge [above] node {compile} (p2);
  1305. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1306. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1307. \end{tikzpicture}
  1308. \end{equation}
  1309. In the next section we see our first example of a compiler.
  1310. \section{Example Compiler: a Partial Evaluator}
  1311. \label{sec:partial-evaluation}
  1312. In this section we consider a compiler that translates \LangInt{}
  1313. programs into \LangInt{} programs that may be more efficient. The
  1314. compiler eagerly computes the parts of the program that do not depend
  1315. on any inputs, a process known as \emph{partial
  1316. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1317. For example, given the following program
  1318. {\if\edition\racketEd\color{olive}
  1319. \begin{lstlisting}
  1320. (+ (read) (- (+ 5 3)))
  1321. \end{lstlisting}
  1322. \fi}
  1323. {\if\edition\pythonEd
  1324. \begin{lstlisting}
  1325. print(input_int() + -(5 + 3) )
  1326. \end{lstlisting}
  1327. \fi}
  1328. \noindent our compiler translates it into the program
  1329. {\if\edition\racketEd\color{olive}
  1330. \begin{lstlisting}
  1331. (+ (read) -8)
  1332. \end{lstlisting}
  1333. \fi}
  1334. {\if\edition\pythonEd
  1335. \begin{lstlisting}
  1336. print(input_int() + -8)
  1337. \end{lstlisting}
  1338. \fi}
  1339. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1340. evaluator for the \LangInt{} language. The output of the partial evaluator
  1341. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1342. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1343. whereas the code for partially evaluating the negation and addition
  1344. operations is factored into two auxiliary functions:
  1345. \code{pe\_neg} and \code{pe\_add}. The input to these
  1346. functions is the output of partially evaluating the children.
  1347. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1348. arguments are integers and if they are, perform the appropriate
  1349. arithmetic. Otherwise, they create an AST node for the arithmetic
  1350. operation.
  1351. \begin{figure}[tp]
  1352. {\if\edition\racketEd\color{olive}
  1353. \begin{lstlisting}
  1354. (define (pe_neg r)
  1355. (match r
  1356. [(Int n) (Int (fx- 0 n))]
  1357. [else (Prim '- (list r))]))
  1358. (define (pe_add r1 r2)
  1359. (match* (r1 r2)
  1360. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1361. [(_ _) (Prim '+ (list r1 r2))]))
  1362. (define (pe_exp e)
  1363. (match e
  1364. [(Int n) (Int n)]
  1365. [(Prim 'read '()) (Prim 'read '())]
  1366. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1367. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1368. (define (pe_Rint p)
  1369. (match p
  1370. [(Program '() e) (Program '() (pe_exp e))]))
  1371. \end{lstlisting}
  1372. \fi}
  1373. {\if\edition\pythonEd
  1374. \begin{lstlisting}
  1375. def pe_neg(r):
  1376. match r:
  1377. case Constant(n):
  1378. return Constant(-n)
  1379. case _:
  1380. return UnaryOp(USub(), r)
  1381. def pe_add(r1, r2):
  1382. match (r1, r2):
  1383. case (Constant(n1), Constant(n2)):
  1384. return Constant(n1 + n2)
  1385. case _:
  1386. return BinOp(r1, Add(), r2)
  1387. def pe_exp(e):
  1388. match e:
  1389. case BinOp(left, Add(), right):
  1390. return pe_add(pe_exp(left), pe_exp(right))
  1391. case UnaryOp(USub(), v):
  1392. return pe_neg(pe_exp(v))
  1393. case Constant(value):
  1394. return e
  1395. case Call(Name('input_int'), []):
  1396. return e
  1397. def pe_stmt(s):
  1398. match s:
  1399. case Expr(Call(Name('print'), [arg])):
  1400. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1401. case Expr(value):
  1402. return Expr(pe_exp(value))
  1403. def pe_P_int(p):
  1404. match p:
  1405. case Module(body):
  1406. new_body = [pe_stmt(s) for s in body]
  1407. return Module(new_body)
  1408. \end{lstlisting}
  1409. \fi}
  1410. \caption{A partial evaluator for \LangInt{}.}
  1411. \label{fig:pe-arith}
  1412. \end{figure}
  1413. To gain some confidence that the partial evaluator is correct, we can
  1414. test whether it produces programs that get the same result as the
  1415. input programs. That is, we can test whether it satisfies Diagram
  1416. \ref{eq:compile-correct}.
  1417. %
  1418. {\if\edition\racketEd\color{olive}
  1419. The following code runs the partial evaluator on several examples and
  1420. tests the output program. The \texttt{parse-program} and
  1421. \texttt{assert} functions are defined in
  1422. Appendix~\ref{appendix:utilities}.\\
  1423. \begin{minipage}{1.0\textwidth}
  1424. \begin{lstlisting}
  1425. (define (test_pe p)
  1426. (assert "testing pe_Rint"
  1427. (equal? (interp_Rint p) (interp_Rint (pe_Rint p)))))
  1428. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1429. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1430. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1431. \end{lstlisting}
  1432. \end{minipage}
  1433. \fi}
  1434. % TODO: python version of testing the PE
  1435. \begin{exercise}\normalfont
  1436. Create three programs in the \LangInt{} language and test whether
  1437. partially evaluating them with \code{pe\_Pint} and then
  1438. interpreting them with \code{interp\_Pint} gives the same result
  1439. as directly interpreting them with \code{interp\_Pint}.
  1440. \end{exercise}
  1441. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1442. \chapter{Integers and Variables}
  1443. \label{ch:Rvar}
  1444. This chapter is about compiling a subset of
  1445. \racket{Racket}\python{Python} to x86-64 assembly
  1446. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1447. integer arithmetic and local variables. We often refer to x86-64
  1448. simply as x86. The chapter begins with a description of the
  1449. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1450. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1451. large so we discuss only the instructions needed for compiling
  1452. \LangVar{}. We introduce more x86 instructions in later chapters.
  1453. After introducing \LangVar{} and x86, we reflect on their differences
  1454. and come up with a plan to break down the translation from \LangVar{}
  1455. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1456. rest of the sections in this chapter give detailed hints regarding
  1457. each step. We hope to give enough hints that the well-prepared
  1458. reader, together with a few friends, can implement a compiler from
  1459. \LangVar{} to x86 in a couple weeks. To give the reader a feeling for
  1460. the scale of this first compiler, the instructor solution for the
  1461. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1462. code.
  1463. \section{The \LangVar{} Language}
  1464. \label{sec:s0}
  1465. \index{subject}{variable}
  1466. The \LangVar{} language extends the \LangInt{} language with
  1467. variables. The concrete syntax of the \LangVar{} language is defined
  1468. by the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the
  1469. abstract syntax is defined in Figure~\ref{fig:Rvar-syntax}. The
  1470. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1471. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1472. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1473. syntax of \LangVar{} includes the \racket{\key{Program}
  1474. struct}\python{\key{Module} instance} to mark the top of the
  1475. program.
  1476. %% The $\itm{info}$
  1477. %% field of the \key{Program} structure contains an \emph{association
  1478. %% list} (a list of key-value pairs) that is used to communicate
  1479. %% auxiliary data from one compiler pass the next.
  1480. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1481. exhibit several compilation techniques.
  1482. \begin{figure}[tp]
  1483. \centering
  1484. \fbox{
  1485. \begin{minipage}{0.96\textwidth}
  1486. {\if\edition\racketEd\color{olive}
  1487. \[
  1488. \begin{array}{rcl}
  1489. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1490. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1491. \LangVarM{} &::=& \Exp
  1492. \end{array}
  1493. \]
  1494. \fi}
  1495. {\if\edition\pythonEd
  1496. \[
  1497. \begin{array}{rcl}
  1498. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1499. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1500. \LangVarM{} &::=& \Stmt^{*}
  1501. \end{array}
  1502. \]
  1503. \fi}
  1504. \end{minipage}
  1505. }
  1506. \caption{The concrete syntax of \LangVar{}.}
  1507. \label{fig:Rvar-concrete-syntax}
  1508. \end{figure}
  1509. \begin{figure}[tp]
  1510. \centering
  1511. \fbox{
  1512. \begin{minipage}{0.96\textwidth}
  1513. {\if\edition\racketEd\color{olive}
  1514. \[
  1515. \begin{array}{rcl}
  1516. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1517. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1518. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1519. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1520. \end{array}
  1521. \]
  1522. \fi}
  1523. {\if\edition\pythonEd
  1524. \[
  1525. \begin{array}{rcl}
  1526. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1527. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1528. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1529. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1530. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1531. \end{array}
  1532. \]
  1533. \fi}
  1534. \end{minipage}
  1535. }
  1536. \caption{The abstract syntax of \LangVar{}.}
  1537. \label{fig:Rvar-syntax}
  1538. \end{figure}
  1539. {\if\edition\racketEd\color{olive}
  1540. Let us dive further into the syntax and semantics of the \LangVar{}
  1541. language. The \key{let} feature defines a variable for use within its
  1542. body and initializes the variable with the value of an expression.
  1543. The abstract syntax for \key{let} is defined in
  1544. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1545. \begin{lstlisting}
  1546. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1547. \end{lstlisting}
  1548. For example, the following program initializes \code{x} to $32$ and then
  1549. evaluates the body \code{(+ 10 x)}, producing $42$.
  1550. \begin{lstlisting}
  1551. (let ([x (+ 12 20)]) (+ 10 x))
  1552. \end{lstlisting}
  1553. \fi}
  1554. %
  1555. {\if\edition\pythonEd
  1556. %
  1557. The \LangVar{} language includes assignment statements, which define a
  1558. variable for use in later statements and initializes the variable with
  1559. the value of an expression. The abstract syntax for assignment is
  1560. defined in Figure~\ref{fig:Rvar-syntax}. The concrete syntax for
  1561. assignment is
  1562. \begin{lstlisting}
  1563. |$\itm{var}$| = |$\itm{exp}$|
  1564. \end{lstlisting}
  1565. For example, the following program initializes the variable \code{x}
  1566. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1567. \begin{lstlisting}
  1568. x = 12 + 20
  1569. print(10 + x)
  1570. \end{lstlisting}
  1571. \fi}
  1572. {\if\edition\racketEd\color{olive}
  1573. %
  1574. When there are multiple \key{let}'s for the same variable, the closest
  1575. enclosing \key{let} is used. That is, variable definitions overshadow
  1576. prior definitions. Consider the following program with two \key{let}'s
  1577. that define variables named \code{x}. Can you figure out the result?
  1578. \begin{lstlisting}
  1579. (let ([x 32]) (+ (let ([x 10]) x) x))
  1580. \end{lstlisting}
  1581. For the purposes of depicting which variable uses correspond to which
  1582. definitions, the following shows the \code{x}'s annotated with
  1583. subscripts to distinguish them. Double check that your answer for the
  1584. above is the same as your answer for this annotated version of the
  1585. program.
  1586. \begin{lstlisting}
  1587. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1588. \end{lstlisting}
  1589. The initializing expression is always evaluated before the body of the
  1590. \key{let}, so in the following, the \key{read} for \code{x} is
  1591. performed before the \key{read} for \code{y}. Given the input
  1592. $52$ then $10$, the following produces $42$ (not $-42$).
  1593. \begin{lstlisting}
  1594. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1595. \end{lstlisting}
  1596. \fi}
  1597. \subsection{Extensible Interpreters via Method Overriding}
  1598. \label{sec:extensible-interp}
  1599. To prepare for discussing the interpreter for \LangVar{}, we
  1600. explain why we to implement the interpreter using
  1601. object-oriented programming, that is, as a collection of methods
  1602. inside of a class. Throughout this book we define many interpreters,
  1603. one for each of the languages that we study. Because each language
  1604. builds on the prior one, there is a lot of commonality between these
  1605. interpreters. We want to write down the common parts just once
  1606. instead of many times. A naive approach would be to have, for example,
  1607. the interpreter for \LangIf{} handle all of the new features in that
  1608. language and then have a default case that dispatches to the
  1609. interpreter for \LangVar{}. The following code sketches this idea.
  1610. \begin{center}
  1611. {\if\edition\racketEd\color{olive}
  1612. \begin{minipage}{0.45\textwidth}
  1613. \begin{lstlisting}
  1614. (define (interp_Rvar_exp e)
  1615. (match e
  1616. [(Prim '- (list e1))
  1617. (fx- 0 (interp_Rvar_exp e1))]
  1618. ...))
  1619. \end{lstlisting}
  1620. \end{minipage}
  1621. \begin{minipage}{0.45\textwidth}
  1622. \begin{lstlisting}
  1623. (define (interp_Rif_exp e)
  1624. (match e
  1625. [(If cnd thn els)
  1626. (match (interp_Rif_exp cnd)
  1627. [#t (interp_Rif_exp thn)]
  1628. [#f (interp_Rif_exp els)])]
  1629. ...
  1630. [else (interp_Rvar_exp e)]))
  1631. \end{lstlisting}
  1632. \end{minipage}
  1633. \fi}
  1634. {\if\edition\pythonEd
  1635. \begin{minipage}{0.45\textwidth}
  1636. \begin{lstlisting}
  1637. def interp_P_var_exp(e):
  1638. match e:
  1639. case UnaryOp(USub(), e1):
  1640. return - interp_P_var_exp(e1)
  1641. ...
  1642. \end{lstlisting}
  1643. \end{minipage}
  1644. \begin{minipage}{0.45\textwidth}
  1645. \begin{lstlisting}
  1646. def interp_P_if_exp(e):
  1647. match e:
  1648. case IfExp(cnd, thn, els):
  1649. match interp_P_if_exp(cnd):
  1650. case True:
  1651. return interp_P_if_exp(thn)
  1652. case False:
  1653. return interp_P_if_exp(els)
  1654. ...
  1655. case _:
  1656. return interp_P_var_exp(e)
  1657. \end{lstlisting}
  1658. \end{minipage}
  1659. \fi}
  1660. \end{center}
  1661. The problem with this approach is that it does not handle situations
  1662. in which an \LangIf{} feature, such as a conditional expression, is
  1663. nested inside an \LangVar{} feature, like the \code{-} operator, as in
  1664. the following program.
  1665. {\if\edition\racketEd\color{olive}
  1666. \begin{lstlisting}
  1667. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1668. \end{lstlisting}
  1669. \fi}
  1670. {\if\edition\pythonEd
  1671. \begin{lstlisting}
  1672. print(-(42 if True else 0))
  1673. \end{lstlisting}
  1674. \fi}
  1675. If we invoke
  1676. \racket{\code{interp\_Rif\_exp}}
  1677. \python{\code{interp\_Pif\_exp}}
  1678. on this program, it dispatches to
  1679. \racket{\code{interp\_Rvar\_exp}}
  1680. \python{\code{interp\_Pvar\_exp}}
  1681. to handle the \code{-} operator, but then it recurisvely calls
  1682. \racket{\code{interp\_Rvar\_exp}}
  1683. \python{\code{interp\_Pvar\_exp}}
  1684. again on the argument of \code{-}, which is an \code{If}. But there is no case for \code{If} in
  1685. \racket{\code{interp\_Rvar\_exp}}
  1686. \python{\code{interp\_Pvar\_exp}},
  1687. so we get an error!
  1688. To make our interpreters extensible we need something called
  1689. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1690. recursive knot is delayed to when the functions are
  1691. composed. Object-oriented languages provide open recursion via
  1692. method overriding\index{subject}{method overriding}. The
  1693. following code uses method overriding to interpret \LangVar{} and
  1694. \LangIf{} using
  1695. %
  1696. \racket{the
  1697. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1698. \index{subject}{class} feature of Racket}
  1699. %
  1700. \python{a Python \code{class} definition}.
  1701. %
  1702. We define one class for each language and define a method for
  1703. interpreting expressions inside each class. The class for \LangIf{}
  1704. inherits from the class for \LangVar{} and the method
  1705. \code{interp\_exp} in \LangIf{} overrides the \code{interp\_exp} in
  1706. \LangVar{}. Note that the default case of \code{interp\_exp} in
  1707. \LangIf{} uses \code{super} to invoke \code{interp\_exp}, and because
  1708. \LangIf{} inherits from \LangVar{}, that dispatches to the
  1709. \code{interp\_exp} in \LangVar{}.
  1710. \begin{center}
  1711. {\if\edition\racketEd\color{olive}
  1712. \begin{minipage}{0.45\textwidth}
  1713. \begin{lstlisting}
  1714. (define interp_Rvar_class
  1715. (class object%
  1716. (define/public (interp_exp e)
  1717. (match e
  1718. [(Prim '- (list e))
  1719. (fx- 0 (interp_exp e))]
  1720. ...))
  1721. ...))
  1722. \end{lstlisting}
  1723. \end{minipage}
  1724. \begin{minipage}{0.45\textwidth}
  1725. \begin{lstlisting}
  1726. (define interp_Rif_class
  1727. (class interp_Rvar_class
  1728. (define/override (interp_exp e)
  1729. (match e
  1730. [(If cnd thn els)
  1731. (match (interp_exp cnd)
  1732. [#t (interp_exp thn)]
  1733. [#f (interp_exp els)])]
  1734. ...
  1735. [else (super interp_exp e)]))
  1736. ...
  1737. ))
  1738. \end{lstlisting}
  1739. \end{minipage}
  1740. \fi}
  1741. {\if\edition\pythonEd
  1742. \begin{minipage}{0.45\textwidth}
  1743. \begin{lstlisting}
  1744. class InterpRvar:
  1745. def interp_exp(e):
  1746. match e:
  1747. case UnaryOp(USub(), e1):
  1748. return -self.interp_exp(e1)
  1749. ...
  1750. ...
  1751. \end{lstlisting}
  1752. \end{minipage}
  1753. \begin{minipage}{0.45\textwidth}
  1754. \begin{lstlisting}
  1755. def InterpRif(InterpRVar):
  1756. def interp_exp(e):
  1757. match e:
  1758. case IfExp(cnd, thn, els):
  1759. match self.interp_exp(cnd):
  1760. case True:
  1761. return self.interp_exp(thn)
  1762. case False:
  1763. return self.interp_exp(els)
  1764. ...
  1765. case _:
  1766. return super().interp_exp(e)
  1767. ...
  1768. \end{lstlisting}
  1769. \end{minipage}
  1770. \fi}
  1771. \end{center}
  1772. Getting back to the troublesome example, repeated here:
  1773. {\if\edition\racketEd\color{olive}
  1774. \begin{lstlisting}
  1775. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1776. \end{lstlisting}
  1777. \fi}
  1778. {\if\edition\pythonEd
  1779. \begin{lstlisting}
  1780. -(42 if True else 0)
  1781. \end{lstlisting}
  1782. \fi}
  1783. \noindent We can invoke the \code{interp\_exp} method for \LangIf{} on this
  1784. expression, call it \code{e0}, by creating an object of the \LangIf{} class
  1785. and calling the \code{interp\_exp} method.
  1786. {\if\edition\racketEd\color{olive}
  1787. \begin{lstlisting}
  1788. (send (new interp_Rif_class) interp_exp e0)
  1789. \end{lstlisting}
  1790. \fi}
  1791. {\if\edition\pythonEd
  1792. \begin{lstlisting}
  1793. InterpPif().interp_exp(e0)
  1794. \end{lstlisting}
  1795. \fi}
  1796. \noindent The default case of \code{interp\_exp} in \LangIf{} handles it by
  1797. dispatching to the \code{interp\_exp} method in \LangVar{}, which
  1798. handles the \code{-} operator. But then for the recursive method call,
  1799. it dispatches back to \code{interp\_exp} in \LangIf{}, where the
  1800. \code{If} is handled correctly. Thus, method overriding gives us the
  1801. open recursion that we need to implement our interpreters in an
  1802. extensible way.
  1803. \subsection{Definitional Interpreter for \LangVar{}}
  1804. {\if\edition\racketEd\color{olive}
  1805. \begin{figure}[tp]
  1806. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1807. \small
  1808. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1809. An \emph{association list} (alist) is a list of key-value pairs.
  1810. For example, we can map people to their ages with an alist.
  1811. \index{subject}{alist}\index{subject}{association list}
  1812. \begin{lstlisting}[basicstyle=\ttfamily]
  1813. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1814. \end{lstlisting}
  1815. The \emph{dictionary} interface is for mapping keys to values.
  1816. Every alist implements this interface. \index{subject}{dictionary} The package
  1817. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1818. provides many functions for working with dictionaries. Here
  1819. are a few of them:
  1820. \begin{description}
  1821. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1822. returns the value associated with the given $\itm{key}$.
  1823. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1824. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1825. but otherwise is the same as $\itm{dict}$.
  1826. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1827. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1828. of keys and values in $\itm{dict}$. For example, the following
  1829. creates a new alist in which the ages are incremented.
  1830. \end{description}
  1831. \vspace{-10pt}
  1832. \begin{lstlisting}[basicstyle=\ttfamily]
  1833. (for/list ([(k v) (in-dict ages)])
  1834. (cons k (add1 v)))
  1835. \end{lstlisting}
  1836. \end{tcolorbox}
  1837. %\end{wrapfigure}
  1838. \caption{Association lists implement the dictionary interface.}
  1839. \label{fig:alist}
  1840. \end{figure}
  1841. \fi}
  1842. Having justified the use of classes and methods to implement
  1843. interpreters, we turn to the definitional interpreter for \LangVar{}
  1844. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1845. \LangInt{} but adds two new \key{match} cases for variables and
  1846. \racket{\key{let}}\python{assignment}. For
  1847. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1848. value bound to a variable to all the uses of the variable. To
  1849. accomplish this, we maintain a mapping from variables to
  1850. values. Throughout the compiler we often need to map variables to
  1851. information about them. We refer to these mappings as
  1852. \emph{environments}\index{subject}{environment}.\footnote{Another
  1853. common term for environment in the compiler literature is \emph{symbol
  1854. table}\index{subject}{symbol table}.}
  1855. %
  1856. We use%
  1857. %
  1858. \racket{an association list (alist)}
  1859. %
  1860. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1861. to represent the environment.
  1862. %
  1863. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1864. and the \code{racket/dict} package.}
  1865. %
  1866. The \code{interp\_exp} function takes the current environment,
  1867. \code{env}, as an extra parameter. When the interpreter encounters a
  1868. variable, it looks up the corresponding value in the dictionary.
  1869. %
  1870. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1871. initializing expression, extends the environment with the result
  1872. value bound to the variable, using \code{dict-set}, then evaluates
  1873. the body of the \key{Let}.}
  1874. %
  1875. \python{When the interpreter encounters an assignment, it evaluates
  1876. the initializing expression and then associates the resulting value
  1877. with the variable in the environment.}
  1878. \begin{figure}[tp]
  1879. {\if\edition\racketEd\color{olive}
  1880. \begin{lstlisting}
  1881. (define interp_Rvar_class
  1882. (class object%
  1883. (super-new)
  1884. (define/public ((interp_exp env) e)
  1885. (match e
  1886. [(Int n) n]
  1887. [(Prim 'read '())
  1888. (define r (read))
  1889. (cond [(fixnum? r) r]
  1890. [else (error 'interp_exp "expected an integer" r)])]
  1891. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1892. [(Prim '+ (list e1 e2))
  1893. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1894. [(Var x) (dict-ref env x)]
  1895. [(Let x e body)
  1896. (define new-env (dict-set env x ((interp_exp env) e)))
  1897. ((interp_exp new-env) body)]))
  1898. (define/public (interp_program p)
  1899. (match p
  1900. [(Program '() e) ((interp_exp '()) e)]))
  1901. ))
  1902. (define (interp_Rvar p)
  1903. (send (new interp_Rvar_class) interp_program p))
  1904. \end{lstlisting}
  1905. \fi}
  1906. {\if\edition\pythonEd
  1907. \begin{lstlisting}
  1908. class InterpPvar:
  1909. def interp_exp(self, e, env):
  1910. match e:
  1911. case BinOp(left, Add(), right):
  1912. l = self.interp_exp(left, env)
  1913. r = self.interp_exp(right, env)
  1914. return l + r
  1915. case UnaryOp(USub(), v):
  1916. return - self.interp_exp(v, env)
  1917. case Name(id):
  1918. return env[id]
  1919. case Constant(value):
  1920. return value
  1921. case Call(Name('input_int'), []):
  1922. return int(input())
  1923. def interp_stmts(self, ss, env):
  1924. if len(ss) == 0:
  1925. return
  1926. match ss[0]:
  1927. case Assign([lhs], value):
  1928. env[lhs.id] = self.interp_exp(value, env)
  1929. return self.interp_stmts(ss[1:], env)
  1930. case Expr(Call(Name('print'), [arg])):
  1931. print(self.interp_exp(arg, env), end='')
  1932. return self.interp_stmts(ss[1:], env)
  1933. case Expr(value):
  1934. self.interp_exp(value, env)
  1935. return self.interp_stmts(ss[1:], env)
  1936. def interp_P(self, p):
  1937. match p:
  1938. case Module(body):
  1939. self.interp_stmts(body, {})
  1940. \end{lstlisting}
  1941. \fi}
  1942. \caption{Interpreter for the \LangVar{} language.}
  1943. \label{fig:interp-Rvar}
  1944. \end{figure}
  1945. The goal for this chapter is to implement a compiler that translates
  1946. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1947. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1948. computer as the $P_1$ program interpreted by \code{interp\_Rvar}. That
  1949. is, they output the same integer $n$. We depict this correctness
  1950. criteria in the following diagram.
  1951. \[
  1952. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1953. \node (p1) at (0, 0) {$P_1$};
  1954. \node (p2) at (4, 0) {$P_2$};
  1955. \node (o) at (4, -2) {$n$};
  1956. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1957. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Rvar}} (o);
  1958. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1959. \end{tikzpicture}
  1960. \]
  1961. In the next section we introduce the \LangXInt{} subset of x86 that
  1962. suffices for compiling \LangVar{}.
  1963. \section{The \LangXInt{} Assembly Language}
  1964. \label{sec:x86}
  1965. \index{subject}{x86}
  1966. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1967. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1968. assembler.
  1969. %
  1970. A program begins with a \code{main} label followed by a sequence of
  1971. instructions. The \key{globl} directive says that the \key{main}
  1972. procedure is externally visible, which is necessary so that the
  1973. operating system can call it. In the grammar, ellipses such as
  1974. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1975. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1976. %
  1977. An x86 program is stored in the computer's memory. For our purposes,
  1978. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1979. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1980. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1981. the address of the next instruction to be executed. For most
  1982. instructions, the program counter is incremented after the instruction
  1983. is executed, so it points to the next instruction in memory. Most x86
  1984. instructions take two operands, where each operand is either an
  1985. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1986. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1987. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  1988. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  1989. && \key{r8} \MID \key{r9} \MID \key{r10}
  1990. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  1991. \MID \key{r14} \MID \key{r15}}
  1992. \begin{figure}[tp]
  1993. \fbox{
  1994. \begin{minipage}{0.96\textwidth}
  1995. \[
  1996. \begin{array}{lcl}
  1997. \Reg &::=& \allregisters{} \\
  1998. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1999. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2000. \key{subq} \; \Arg\key{,} \Arg \MID
  2001. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2002. && \key{callq} \; \mathit{label} \MID
  2003. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  2004. && \itm{label}\key{:}\; \Instr \\
  2005. \LangXIntM{} &::= & \key{.globl main}\\
  2006. & & \key{main:} \; \Instr\ldots
  2007. \end{array}
  2008. \]
  2009. \end{minipage}
  2010. }
  2011. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2012. \label{fig:x86-int-concrete}
  2013. \end{figure}
  2014. A register is a special kind of variable. Each one holds a 64-bit
  2015. value; there are 16 general-purpose registers in the computer and
  2016. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2017. is written with a \key{\%} followed by the register name, such as
  2018. \key{\%rax}.
  2019. An immediate value is written using the notation \key{\$}$n$ where $n$
  2020. is an integer.
  2021. %
  2022. %
  2023. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2024. which obtains the address stored in register $r$ and then adds $n$
  2025. bytes to the address. The resulting address is used to load or store
  2026. to memory depending on whether it occurs as a source or destination
  2027. argument of an instruction.
  2028. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2029. source $s$ and destination $d$, applies the arithmetic operation, then
  2030. writes the result back to the destination $d$.
  2031. %
  2032. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2033. stores the result in $d$.
  2034. %
  2035. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2036. specified by the label and $\key{retq}$ returns from a procedure to
  2037. its caller.
  2038. %
  2039. We discuss procedure calls in more detail later in this chapter and in
  2040. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  2041. updates the program counter to the address of the instruction after
  2042. the specified label.
  2043. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2044. all of the x86 instructions used in this book.
  2045. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2046. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2047. \lstinline{movq $10, %rax}
  2048. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2049. adds $32$ to the $10$ in \key{rax} and
  2050. puts the result, $42$, back into \key{rax}.
  2051. %
  2052. The last instruction, \key{retq}, finishes the \key{main} function by
  2053. returning the integer in \key{rax} to the operating system. The
  2054. operating system interprets this integer as the program's exit
  2055. code. By convention, an exit code of 0 indicates that a program
  2056. completed successfully, and all other exit codes indicate various
  2057. errors. Nevertheless, in this book we return the result of the program
  2058. as the exit code.
  2059. \begin{figure}[tbp]
  2060. \begin{lstlisting}
  2061. .globl main
  2062. main:
  2063. movq $10, %rax
  2064. addq $32, %rax
  2065. retq
  2066. \end{lstlisting}
  2067. \caption{An x86 program that computes
  2068. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2069. \label{fig:p0-x86}
  2070. \end{figure}
  2071. The x86 assembly language varies in a couple of ways depending on what
  2072. operating system it is assembled in. The code examples shown here are
  2073. correct on Linux and most Unix-like platforms, but when assembled on
  2074. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  2075. as in \key{\_main}.
  2076. We exhibit the use of memory for storing intermediate results in the
  2077. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2078. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2079. uses a region of memory called the \emph{procedure call stack} (or
  2080. \emph{stack} for
  2081. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2082. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2083. for each procedure call. The memory layout for an individual frame is
  2084. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2085. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2086. item at the top of the stack. The stack grows downward in memory, so
  2087. we increase the size of the stack by subtracting from the stack
  2088. pointer. In the context of a procedure call, the \emph{return
  2089. address}\index{subject}{return address} is the instruction after the
  2090. call instruction on the caller side. The function call instruction,
  2091. \code{callq}, pushes the return address onto the stack prior to
  2092. jumping to the procedure. The register \key{rbp} is the \emph{base
  2093. pointer}\index{subject}{base pointer} and is used to access variables
  2094. that are stored in the frame of the current procedure call. The base
  2095. pointer of the caller is pushed onto the stack after the return
  2096. address and then the base pointer is set to the location of the old
  2097. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2098. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2099. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2100. \begin{figure}[tbp]
  2101. \begin{lstlisting}
  2102. start:
  2103. movq $10, -8(%rbp)
  2104. negq -8(%rbp)
  2105. movq -8(%rbp), %rax
  2106. addq $52, %rax
  2107. jmp conclusion
  2108. .globl main
  2109. main:
  2110. pushq %rbp
  2111. movq %rsp, %rbp
  2112. subq $16, %rsp
  2113. jmp start
  2114. conclusion:
  2115. addq $16, %rsp
  2116. popq %rbp
  2117. retq
  2118. \end{lstlisting}
  2119. \caption{An x86 program that computes
  2120. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2121. \label{fig:p1-x86}
  2122. \end{figure}
  2123. \begin{figure}[tbp]
  2124. \centering
  2125. \begin{tabular}{|r|l|} \hline
  2126. Position & Contents \\ \hline
  2127. 8(\key{\%rbp}) & return address \\
  2128. 0(\key{\%rbp}) & old \key{rbp} \\
  2129. -8(\key{\%rbp}) & variable $1$ \\
  2130. -16(\key{\%rbp}) & variable $2$ \\
  2131. \ldots & \ldots \\
  2132. 0(\key{\%rsp}) & variable $n$\\ \hline
  2133. \end{tabular}
  2134. \caption{Memory layout of a frame.}
  2135. \label{fig:frame}
  2136. \end{figure}
  2137. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2138. control is transferred from the operating system to the \code{main}
  2139. function. The operating system issues a \code{callq main} instruction
  2140. which pushes its return address on the stack and then jumps to
  2141. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2142. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2143. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2144. alignment (because the \code{callq} pushed the return address). The
  2145. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2146. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2147. pointer for the caller onto the stack and subtracts $8$ from the stack
  2148. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2149. base pointer so that it points the location of the old base
  2150. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2151. pointer down to make enough room for storing variables. This program
  2152. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2153. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2154. functions. The last instruction of the prelude is \code{jmp start},
  2155. which transfers control to the instructions that were generated from
  2156. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.
  2157. The first instruction under the \code{start} label is
  2158. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2159. %
  2160. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2161. %
  2162. The next instruction moves the $-10$ from variable $1$ into the
  2163. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2164. the value in \code{rax}, updating its contents to $42$.
  2165. The three instructions under the label \code{conclusion} are the
  2166. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  2167. two instructions restore the \code{rsp} and \code{rbp} registers to
  2168. the state they were in at the beginning of the procedure. The
  2169. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2170. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2171. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2172. instruction, \key{retq}, jumps back to the procedure that called this
  2173. one and adds $8$ to the stack pointer.
  2174. The compiler needs a convenient representation for manipulating x86
  2175. programs, so we define an abstract syntax for x86 in
  2176. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2177. \LangXInt{}.
  2178. %
  2179. {\if\edition\racketEd\color{olive}
  2180. The main difference compared to the concrete syntax of \LangXInt{}
  2181. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2182. front of every instruction. Instead instructions are grouped into
  2183. \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  2184. label associated with every block, which is why the \key{X86Program}
  2185. struct includes an alist mapping labels to blocks. The reason for this
  2186. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2187. introduce conditional branching. The \code{Block} structure includes
  2188. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2189. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2190. $\itm{info}$ field should contain an empty list.
  2191. \fi}
  2192. %
  2193. {\if\edition\pythonEd
  2194. %
  2195. The main difference compared to the concrete syntax of \LangXInt{}
  2196. (Figure~\ref{fig:x86-int-concrete}) is that we do not yet include a
  2197. way to label instructions but instead recommend inserting the
  2198. \key{main}, \key{start}, and \key{conclusion} labels when printing the
  2199. final x86 program.
  2200. %
  2201. \fi}
  2202. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2203. node includes an integer for representing the arity of the function,
  2204. i.e., the number of arguments, which is helpful to know during
  2205. register allocation (Chapter~\ref{ch:register-allocation-Rvar}).
  2206. \begin{figure}[tp]
  2207. \fbox{
  2208. \begin{minipage}{0.98\textwidth}
  2209. \small
  2210. {\if\edition\racketEd\color{olive}
  2211. \[
  2212. \begin{array}{lcl}
  2213. \Reg &::=& \allregisters{} \\
  2214. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2215. \MID \DEREF{\Reg}{\Int} \\
  2216. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2217. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2218. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2219. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2220. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2221. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2222. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2223. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2224. \end{array}
  2225. \]
  2226. \fi}
  2227. {\if\edition\pythonEd
  2228. \[
  2229. \begin{array}{lcl}
  2230. \Reg &::=& \allregisters{} \\
  2231. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2232. \MID \DEREF{\Reg}{\Int} \\
  2233. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2234. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2235. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2236. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2237. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2238. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2239. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2240. \end{array}
  2241. \]
  2242. \fi}
  2243. \end{minipage}
  2244. }
  2245. \caption{The abstract syntax of \LangXInt{} assembly.}
  2246. \label{fig:x86-int-ast}
  2247. \end{figure}
  2248. \section{Planning the trip to x86}
  2249. \label{sec:plan-s0-x86}
  2250. To compile one language to another it helps to focus on the
  2251. differences between the two languages because the compiler will need
  2252. to bridge those differences. What are the differences between \LangVar{}
  2253. and x86 assembly? Here are some of the most important ones:
  2254. \begin{enumerate}
  2255. \item x86 arithmetic instructions typically have two arguments
  2256. and update the second argument in place. In contrast, \LangVar{}
  2257. arithmetic operations take two arguments and produce a new value.
  2258. An x86 instruction may have at most one memory-accessing argument.
  2259. Furthermore, some instructions place special restrictions on their
  2260. arguments.
  2261. \item An argument of an \LangVar{} operator can be a deeply-nested
  2262. expression, whereas x86 instructions restrict their arguments to be
  2263. integer constants, registers, and memory locations.
  2264. {\if\edition\racketEd\color{olive}
  2265. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2266. sequence of instructions and jumps to labeled positions, whereas in
  2267. \LangVar{} the order of evaluation is a left-to-right depth-first
  2268. traversal of the abstract syntax tree.
  2269. \fi}
  2270. \item A program in \LangVar{} can have any number of variables
  2271. whereas x86 has 16 registers and the procedure calls stack.
  2272. {\if\edition\racketEd\color{olive}
  2273. \item Variables in \LangVar{} can shadow other variables with the
  2274. same name. In x86, registers have unique names and memory locations
  2275. have unique addresses.
  2276. \fi}
  2277. \end{enumerate}
  2278. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2279. the problem into several steps, dealing with the above differences one
  2280. at a time. Each of these steps is called a \emph{pass} of the
  2281. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2282. %
  2283. This terminology comes from the way each step passes over the AST of
  2284. the program.
  2285. %
  2286. We begin by sketching how we might implement each pass, and give them
  2287. names. We then figure out an ordering of the passes and the
  2288. input/output language for each pass. The very first pass has
  2289. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2290. its output language. In between we can choose whichever language is
  2291. most convenient for expressing the output of each pass, whether that
  2292. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2293. our own design. Finally, to implement each pass we write one
  2294. recursive function per non-terminal in the grammar of the input
  2295. language of the pass. \index{subject}{intermediate language}
  2296. \begin{description}
  2297. {\if\edition\racketEd\color{olive}
  2298. \item[\key{uniquify}] deals with the shadowing of variables by
  2299. renaming every variable to a unique name.
  2300. \fi}
  2301. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2302. of a primitive operation or function call is a variable or integer,
  2303. that is, an \emph{atomic} expression. We refer to non-atomic
  2304. expressions as \emph{complex}. This pass introduces temporary
  2305. variables to hold the results of complex
  2306. subexpressions.\index{subject}{atomic
  2307. expression}\index{subject}{complex expression}%
  2308. {\if\edition\racketEd\color{olive}
  2309. \item[\key{explicate\_control}] makes the execution order of the
  2310. program explicit. It convert the abstract syntax tree representation
  2311. into a control-flow graph in which each node contains a sequence of
  2312. statements and the edges between nodes say which nodes contain jumps
  2313. to other nodes.
  2314. \fi}
  2315. \item[\key{select\_instructions}] handles the difference between
  2316. \LangVar{} operations and x86 instructions. This pass converts each
  2317. \LangVar{} operation to a short sequence of instructions that
  2318. accomplishes the same task.
  2319. \item[\key{assign\_homes}] replaces the variables in \LangVar{} with
  2320. registers or stack locations in x86.
  2321. \end{description}
  2322. The next question is: in what order should we apply these passes? This
  2323. question can be challenging because it is difficult to know ahead of
  2324. time which orderings will be better (easier to implement, produce more
  2325. efficient code, etc.) so oftentimes trial-and-error is
  2326. involved. Nevertheless, we can try to plan ahead and make educated
  2327. choices regarding the ordering.
  2328. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2329. \key{uniquify}? The \key{uniquify} pass should come first because
  2330. \key{explicate\_control} changes all the \key{let}-bound variables to
  2331. become local variables whose scope is the entire program, which would
  2332. confuse variables with the same name.}
  2333. %
  2334. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2335. because the later removes the \key{let} form, but it is convenient to
  2336. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2337. %
  2338. \racket{The ordering of \key{uniquify} with respect to
  2339. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2340. \key{uniquify} to come first.}
  2341. The \key{select\_instructions} and \key{assign\_homes}. passes are
  2342. intertwined. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers
  2343. are used for passing arguments to functions and it is preferable to
  2344. assign parameters to their corresponding registers. On the other hand,
  2345. by selecting instructions first we may run into a dead end in
  2346. \key{assign\_homes}. Recall that only one argument of an x86
  2347. instruction may be a memory access but \key{assign\_homes} might fail
  2348. to assign even one of them to a register.
  2349. %
  2350. A sophisticated approach is to iteratively repeat the two passes until
  2351. a solution is found. However, to reduce implementation complexity we
  2352. recommend a simpler approach in which \key{select\_instructions} comes
  2353. first, followed by the \key{assign\_homes}, then a third pass named
  2354. \key{patch\_instructions} that uses a reserved register to fix
  2355. outstanding problems.
  2356. \begin{figure}[tbp]
  2357. {\if\edition\racketEd\color{olive}
  2358. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2359. \node (Rvar) at (0,2) {\large \LangVar{}};
  2360. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2361. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2362. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2363. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2364. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2365. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2366. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2367. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2368. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2369. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  2370. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2371. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2372. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2373. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2374. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print\_x86} (x86-5);
  2375. \end{tikzpicture}
  2376. \fi}
  2377. {\if\edition\pythonEd
  2378. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2379. \node (Rvar) at (0,2) {\large \LangVar{}};
  2380. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2381. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2382. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2383. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2384. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2385. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  2386. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2387. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2388. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2389. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  2390. \end{tikzpicture}
  2391. \fi}
  2392. \caption{Diagram of the passes for compiling \LangVar{}. }
  2393. \label{fig:Rvar-passes}
  2394. \end{figure}
  2395. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2396. passes and identifies the input and output language of each pass. The
  2397. last pass, \key{print\_x86}, converts from the abstract syntax of
  2398. \LangXInt{} to the concrete syntax.
  2399. %
  2400. \racket{In the following two sections we discuss the \LangCVar{}
  2401. intermediate language and the \LangXVar{} dialect of x86.}
  2402. %
  2403. \python{In the following section we discuss the \LangXVar{} dialect of
  2404. x86.}
  2405. %
  2406. The remainder of this chapter gives hints regarding the implementation
  2407. of each of the compiler passes in Figure~\ref{fig:Rvar-passes}.
  2408. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2409. %% are programs that are still in the \LangVar{} language, though the
  2410. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2411. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2412. %% %
  2413. %% The output of \code{explicate\_control} is in an intermediate language
  2414. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2415. %% syntax, which we introduce in the next section. The
  2416. %% \key{select-instruction} pass translates from \LangCVar{} to
  2417. %% \LangXVar{}. The \key{assign-homes} and
  2418. %% \key{patch-instructions}
  2419. %% passes input and output variants of x86 assembly.
  2420. {\if\edition\racketEd\color{olive}
  2421. \subsection{The \LangCVar{} Intermediate Language}
  2422. The output of \code{explicate\_control} is similar to the $C$
  2423. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2424. categories for expressions and statements, so we name it \LangCVar{}. The
  2425. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2426. \racket{(The concrete syntax for \LangCVar{} is in the Appendix,
  2427. Figure~\ref{fig:c0-concrete-syntax}.)}
  2428. %
  2429. The \LangCVar{} language supports the same operators as \LangVar{} but
  2430. the arguments of operators are restricted to atomic
  2431. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2432. assignment statements which can be executed in sequence using the
  2433. \key{Seq} form. A sequence of statements always ends with
  2434. \key{Return}, a guarantee that is baked into the grammar rules for
  2435. \itm{tail}. The naming of this non-terminal comes from the term
  2436. \emph{tail position}\index{subject}{tail position}, which refers to an
  2437. expression that is the last one to execute within a function.
  2438. A \LangCVar{} program consists of a control-flow graph represented as
  2439. an alist mapping labels to tails. This is more general than necessary
  2440. for the present chapter, as we do not yet introduce \key{goto} for
  2441. jumping to labels, but it saves us from having to change the syntax in
  2442. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2443. \key{start}, and the whole program is its tail.
  2444. %
  2445. The $\itm{info}$ field of the \key{CProgram} form, after the
  2446. \code{explicate\_control} pass, contains a mapping from the symbol
  2447. \key{locals} to a list of variables, that is, a list of all the
  2448. variables used in the program. At the start of the program, these
  2449. variables are uninitialized; they become initialized on their first
  2450. assignment.
  2451. \begin{figure}[tbp]
  2452. \fbox{
  2453. \begin{minipage}{0.96\textwidth}
  2454. \[
  2455. \begin{array}{lcl}
  2456. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2457. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2458. &\MID& \ADD{\Atm}{\Atm}\\
  2459. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2460. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2461. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2462. \end{array}
  2463. \]
  2464. \end{minipage}
  2465. }
  2466. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2467. \label{fig:c0-syntax}
  2468. \end{figure}
  2469. The definitional interpreter for \LangCVar{} is in the support code,
  2470. in the file \code{interp-Cvar.rkt}.
  2471. \fi}
  2472. \section{The \LangXVar{} dialect}
  2473. The \LangXVar{} language is the output of the pass
  2474. \key{select\_instructions}. It extends \LangXInt{} with an unbounded
  2475. number of program-scope variables and removes the restrictions
  2476. regarding instruction arguments.
  2477. {\if\edition\racketEd\color{olive}
  2478. \section{Uniquify Variables}
  2479. \label{sec:uniquify-Rvar}
  2480. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2481. programs in which every \key{let} binds a unique variable name. For
  2482. example, the \code{uniquify} pass should translate the program on the
  2483. left into the program on the right.
  2484. \begin{transformation}
  2485. \begin{lstlisting}
  2486. (let ([x 32])
  2487. (+ (let ([x 10]) x) x))
  2488. \end{lstlisting}
  2489. \compilesto
  2490. \begin{lstlisting}
  2491. (let ([x.1 32])
  2492. (+ (let ([x.2 10]) x.2) x.1))
  2493. \end{lstlisting}
  2494. \end{transformation}
  2495. The following is another example translation, this time of a program
  2496. with a \key{let} nested inside the initializing expression of another
  2497. \key{let}.
  2498. \begin{transformation}
  2499. \begin{lstlisting}
  2500. (let ([x (let ([x 4])
  2501. (+ x 1))])
  2502. (+ x 2))
  2503. \end{lstlisting}
  2504. \compilesto
  2505. \begin{lstlisting}
  2506. (let ([x.2 (let ([x.1 4])
  2507. (+ x.1 1))])
  2508. (+ x.2 2))
  2509. \end{lstlisting}
  2510. \end{transformation}
  2511. We recommend implementing \code{uniquify} by creating a structurally
  2512. recursive function named \code{uniquify-exp} that mostly just copies
  2513. an expression. However, when encountering a \key{let}, it should
  2514. generate a unique name for the variable and associate the old name
  2515. with the new name in an alist.\footnote{The Racket function
  2516. \code{gensym} is handy for generating unique variable names.} The
  2517. \code{uniquify-exp} function needs to access this alist when it gets
  2518. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2519. for the alist.
  2520. The skeleton of the \code{uniquify-exp} function is shown in
  2521. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2522. convenient to partially apply it to an alist and then apply it to
  2523. different expressions, as in the last case for primitive operations in
  2524. Figure~\ref{fig:uniquify-Rvar}. The
  2525. %
  2526. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2527. %
  2528. form of Racket is useful for transforming each element of a list to
  2529. produce a new list.\index{subject}{for/list}
  2530. \begin{figure}[tbp]
  2531. \begin{lstlisting}
  2532. (define (uniquify-exp env)
  2533. (lambda (e)
  2534. (match e
  2535. [(Var x) ___]
  2536. [(Int n) (Int n)]
  2537. [(Let x e body) ___]
  2538. [(Prim op es)
  2539. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2540. (define (uniquify p)
  2541. (match p
  2542. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2543. \end{lstlisting}
  2544. \caption{Skeleton for the \key{uniquify} pass.}
  2545. \label{fig:uniquify-Rvar}
  2546. \end{figure}
  2547. \begin{exercise}
  2548. \normalfont % I don't like the italics for exercises. -Jeremy
  2549. Complete the \code{uniquify} pass by filling in the blanks in
  2550. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2551. variables and for the \key{let} form in the file \code{compiler.rkt}
  2552. in the support code.
  2553. \end{exercise}
  2554. \begin{exercise}
  2555. \normalfont % I don't like the italics for exercises. -Jeremy
  2556. \label{ex:Rvar}
  2557. Create five \LangVar{} programs that exercise the most interesting
  2558. parts of the \key{uniquify} pass, that is, the programs should include
  2559. \key{let} forms, variables, and variables that shadow each other.
  2560. The five programs should be placed in the subdirectory named
  2561. \key{tests} and the file names should start with \code{var\_test\_}
  2562. followed by a unique integer and end with the file extension
  2563. \key{.rkt}.
  2564. %
  2565. The \key{run-tests.rkt} script in the support code checks whether the
  2566. output programs produce the same result as the input programs. The
  2567. script uses the \key{interp-tests} function
  2568. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2569. your \key{uniquify} pass on the example programs. The \code{passes}
  2570. parameter of \key{interp-tests} is a list that should have one entry
  2571. for each pass in your compiler. For now, define \code{passes} to
  2572. contain just one entry for \code{uniquify} as shown below.
  2573. \begin{lstlisting}
  2574. (define passes
  2575. (list (list "uniquify" uniquify interp_Rvar type-check-Rvar)))
  2576. \end{lstlisting}
  2577. Run the \key{run-tests.rkt} script in the support code to check
  2578. whether the output programs produce the same result as the input
  2579. programs.
  2580. \end{exercise}
  2581. \fi}
  2582. \section{Remove Complex Operands}
  2583. \label{sec:remove-complex-opera-Rvar}
  2584. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2585. into a restricted form in which the arguments of operations are atomic
  2586. expressions. Put another way, this pass removes complex
  2587. operands\index{subject}{complex operand}, such as the expression
  2588. \racket{\code{(- 10)}}\python{\code{-10}}
  2589. in the program below. This is accomplished by introducing a new
  2590. temporary variable, assigning the complex operand to the new
  2591. variable, and then using the new variable in place of the complex
  2592. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2593. right.
  2594. {\if\edition\racketEd\color{olive}
  2595. \begin{transformation}
  2596. % var_test_19.rkt
  2597. \begin{lstlisting}
  2598. (let ([x (+ 42 (- 10))])
  2599. (+ x 10))
  2600. \end{lstlisting}
  2601. \compilesto
  2602. \begin{lstlisting}
  2603. (let ([x (let ([tmp.1 (- 10)])
  2604. (+ 42 tmp.1))])
  2605. (+ x 10))
  2606. \end{lstlisting}
  2607. \end{transformation}
  2608. \fi}
  2609. {\if\edition\pythonEd
  2610. \begin{transformation}
  2611. \begin{lstlisting}
  2612. x = 42 + -10
  2613. print(x + 10)
  2614. \end{lstlisting}
  2615. \compilesto
  2616. \begin{lstlisting}
  2617. tmp_0 = -10
  2618. x = 42 + tmp_0
  2619. tmp_1 = x + 10
  2620. print(tmp_1)
  2621. \end{lstlisting}
  2622. \end{transformation}
  2623. \fi}
  2624. \begin{figure}[tp]
  2625. \centering
  2626. \fbox{
  2627. \begin{minipage}{0.96\textwidth}
  2628. {\if\edition\racketEd\color{olive}
  2629. \[
  2630. \begin{array}{rcl}
  2631. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2632. \Exp &::=& \Atm \MID \READ{} \\
  2633. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2634. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2635. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2636. \end{array}
  2637. \]
  2638. \fi}
  2639. {\if\edition\pythonEd
  2640. \[
  2641. \begin{array}{rcl}
  2642. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2643. \Exp{} &::=& \Atm \MID \READ{} \\
  2644. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  2645. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2646. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2647. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2648. \end{array}
  2649. \]
  2650. \fi}
  2651. \end{minipage}
  2652. }
  2653. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2654. atomic expressions, like administrative normal form (ANF).}
  2655. \label{fig:Rvar-anf-syntax}
  2656. \end{figure}
  2657. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  2658. this pass, the language \LangVarANF{}. The only difference is that
  2659. operator arguments are restricted to be atomic expressions that are
  2660. defined by the \Atm{} non-terminal. In particular, integer constants
  2661. and variables are atomic. In the literature, restricting arguments to
  2662. be atomic expressions is one of the ideas in \emph{administrative
  2663. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2664. \index{subject}{administrative normal form} \index{subject}{ANF}
  2665. {\if\edition\racketEd\color{olive}
  2666. We recommend implementing this pass with two mutually recursive
  2667. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2668. \code{rco\_atom} to subexpressions that need to become atomic and to
  2669. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2670. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2671. returns an expression. The \code{rco\_atom} function returns two
  2672. things: an atomic expression and an alist mapping temporary variables to
  2673. complex subexpressions. You can return multiple things from a function
  2674. using Racket's \key{values} form and you can receive multiple things
  2675. from a function call using the \key{define-values} form.
  2676. Also, the
  2677. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2678. form is useful for applying a function to each element of a list, in
  2679. the case where the function returns multiple values.
  2680. \index{subject}{for/lists}
  2681. \fi}
  2682. %
  2683. {\if\edition\pythonEd
  2684. %
  2685. We recommend implementing this pass with an auxiliary method named
  2686. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2687. Boolean that specifies whether the expression needs to become atomic
  2688. or not. The \code{rco\_exp} method should return a pair consisting of
  2689. the new expression and a list of pairs, associating new temporary
  2690. variables with their initializing expressions.
  2691. %
  2692. \fi}
  2693. {\if\edition\racketEd\color{olive}
  2694. Returning to the example program with the expression \code{(+ 42 (-
  2695. 10))}, the subexpression \code{(- 10)} should be processed using the
  2696. \code{rco\_atom} function because it is an argument of the \code{+} and
  2697. therefore needs to become atomic. The output of \code{rco\_atom}
  2698. applied to \code{(- 10)} is as follows.
  2699. \begin{transformation}
  2700. \begin{lstlisting}
  2701. (- 10)
  2702. \end{lstlisting}
  2703. \compilesto
  2704. \begin{lstlisting}
  2705. tmp.1
  2706. ((tmp.1 . (- 10)))
  2707. \end{lstlisting}
  2708. \end{transformation}
  2709. \fi}
  2710. %
  2711. {\if\edition\pythonEd
  2712. %
  2713. Returning to the example program with the expression \code{42 + -10},
  2714. the subexpression \code{-10} should be processed using the
  2715. \code{rco\_exp} function with \code{True} as the second argument
  2716. because \code{-10} is an argument of the \code{+} operator and
  2717. therefore needs to become atomic. The output of \code{rco\_exp}
  2718. applied to \code{-10} is as follows.
  2719. \begin{transformation}
  2720. \begin{lstlisting}
  2721. -10
  2722. \end{lstlisting}
  2723. \compilesto
  2724. \begin{lstlisting}
  2725. tmp_1
  2726. [(tmp_1, -10)]
  2727. \end{lstlisting}
  2728. \end{transformation}
  2729. %
  2730. \fi}
  2731. Take special care of programs such as the following that \racket{bind
  2732. a variable to an atomic expression}\python{assign an atomic
  2733. expression to a variable}. You should leave such \racket{variable
  2734. bindings}\python{assignments} unchanged, as shown in the program on
  2735. the right\\
  2736. %
  2737. {\if\edition\racketEd\color{olive}
  2738. \begin{transformation}
  2739. % var_test_20.rkt
  2740. \begin{lstlisting}
  2741. (let ([a 42])
  2742. (let ([b a])
  2743. b))
  2744. \end{lstlisting}
  2745. \compilesto
  2746. \begin{lstlisting}
  2747. (let ([a 42])
  2748. (let ([b a])
  2749. b))
  2750. \end{lstlisting}
  2751. \end{transformation}
  2752. \fi}
  2753. {\if\edition\pythonEd
  2754. \begin{transformation}
  2755. \begin{lstlisting}
  2756. a = 42
  2757. b = a
  2758. print(b)
  2759. \end{lstlisting}
  2760. \compilesto
  2761. \begin{lstlisting}
  2762. a = 42
  2763. b = a
  2764. print(b)
  2765. \end{lstlisting}
  2766. \end{transformation}
  2767. \fi}
  2768. A careless implementation might produce the following output with
  2769. unnecessary temporary variables.
  2770. \begin{center}
  2771. \begin{minipage}{0.4\textwidth}
  2772. {\if\edition\racketEd\color{olive}
  2773. \begin{lstlisting}
  2774. (let ([tmp.1 42])
  2775. (let ([a tmp.1])
  2776. (let ([tmp.2 a])
  2777. (let ([b tmp.2])
  2778. b))))
  2779. \end{lstlisting}
  2780. \fi}
  2781. {\if\edition\pythonEd
  2782. \begin{lstlisting}
  2783. tmp_1 = 42
  2784. a = tmp_1
  2785. tmp_2 = a
  2786. b = tmp_2
  2787. print(b)
  2788. \end{lstlisting}
  2789. \fi}
  2790. \end{minipage}
  2791. \end{center}
  2792. \begin{exercise}
  2793. \normalfont
  2794. {\if\edition\racketEd\color{olive}
  2795. Implement the \code{remove\_complex\_operands} function in
  2796. \code{compiler.rkt}.
  2797. %
  2798. Create three new \LangVar{} programs that exercise the interesting
  2799. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2800. regarding file names described in Exercise~\ref{ex:Rvar}.
  2801. %
  2802. In the \code{run-tests.rkt} script, add the following entry to the
  2803. list of \code{passes} and then run the script to test your compiler.
  2804. \begin{lstlisting}
  2805. (list "remove-complex" remove-complex-opera* interp_Rvar type-check-Rvar)
  2806. \end{lstlisting}
  2807. While debugging your compiler, it is often useful to see the
  2808. intermediate programs that are output from each pass. To print the
  2809. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2810. \code{interp-tests} in \code{run-tests.rkt}.
  2811. \fi}
  2812. %
  2813. {\if\edition\pythonEd
  2814. Implement the \code{remove\_complex\_operands} function in
  2815. \code{compiler.py}, creating auxiliary functions for each
  2816. non-terminal in the grammar, i.e., \code{rco\_exp}
  2817. and \code{rco\_stmt}.
  2818. \fi}
  2819. \end{exercise}
  2820. {\if\edition\pythonEd
  2821. \begin{exercise}
  2822. \normalfont % I don't like the italics for exercises. -Jeremy
  2823. \label{ex:Rvar}
  2824. Create five \LangVar{} programs that exercise the most interesting
  2825. parts of the Remove Complex Operands pass. The five programs should
  2826. be placed in the subdirectory named \key{tests} and the file names
  2827. should start with \code{var\_test\_} followed by a unique integer and
  2828. end with the file extension \key{.py}.
  2829. % TODO: come up with passes infrastructure for Python -Jeremy
  2830. %% The \key{run-tests.rkt} script in the support code checks whether the
  2831. %% output programs produce the same result as the input programs. The
  2832. %% script uses the \key{interp-tests} function
  2833. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2834. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2835. %% parameter of \key{interp-tests} is a list that should have one entry
  2836. %% for each pass in your compiler. For now, define \code{passes} to
  2837. %% contain just one entry for \code{uniquify} as shown below.
  2838. %% \begin{lstlisting}
  2839. %% (define passes
  2840. %% (list (list "uniquify" uniquify interp_Rvar type-check-Rvar)))
  2841. %% \end{lstlisting}
  2842. Run the \key{run-tests.py} script in the support code to check
  2843. whether the output programs produce the same result as the input
  2844. programs.
  2845. \end{exercise}
  2846. \fi}
  2847. {\if\edition\racketEd\color{olive}
  2848. \section{Explicate Control}
  2849. \label{sec:explicate-control-Rvar}
  2850. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  2851. programs that make the order of execution explicit in their
  2852. syntax. For now this amounts to flattening \key{let} constructs into a
  2853. sequence of assignment statements. For example, consider the following
  2854. \LangVar{} program.\\
  2855. % var_test_11.rkt
  2856. \begin{minipage}{0.96\textwidth}
  2857. \begin{lstlisting}
  2858. (let ([y (let ([x 20])
  2859. (+ x (let ([x 22]) x)))])
  2860. y)
  2861. \end{lstlisting}
  2862. \end{minipage}\\
  2863. %
  2864. The output of the previous pass and of \code{explicate\_control} is
  2865. shown below. Recall that the right-hand-side of a \key{let} executes
  2866. before its body, so the order of evaluation for this program is to
  2867. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2868. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2869. output of \code{explicate\_control} makes this ordering explicit.
  2870. \begin{transformation}
  2871. \begin{lstlisting}
  2872. (let ([y (let ([x.1 20])
  2873. (let ([x.2 22])
  2874. (+ x.1 x.2)))])
  2875. y)
  2876. \end{lstlisting}
  2877. \compilesto
  2878. \begin{lstlisting}[language=C]
  2879. start:
  2880. x.1 = 20;
  2881. x.2 = 22;
  2882. y = (+ x.1 x.2);
  2883. return y;
  2884. \end{lstlisting}
  2885. \end{transformation}
  2886. \begin{figure}[tbp]
  2887. \begin{lstlisting}
  2888. (define (explicate-tail e)
  2889. (match e
  2890. [(Var x) ___]
  2891. [(Int n) (Return (Int n))]
  2892. [(Let x rhs body) ___]
  2893. [(Prim op es) ___]
  2894. [else (error "explicate-tail unhandled case" e)]))
  2895. (define (explicate-assign e x cont)
  2896. (match e
  2897. [(Var x) ___]
  2898. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2899. [(Let y rhs body) ___]
  2900. [(Prim op es) ___]
  2901. [else (error "explicate-assign unhandled case" e)]))
  2902. (define (explicate-control p)
  2903. (match p
  2904. [(Program info body) ___]))
  2905. \end{lstlisting}
  2906. \caption{Skeleton for the \code{explicate\_control} pass.}
  2907. \label{fig:explicate-control-Rvar}
  2908. \end{figure}
  2909. The organization of this pass depends on the notion of tail position
  2910. that we have alluded to earlier.
  2911. \begin{definition}
  2912. The following rules define when an expression is in \textbf{\emph{tail
  2913. position}}\index{subject}{tail position} for the language \LangVar{}.
  2914. \begin{enumerate}
  2915. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2916. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2917. \end{enumerate}
  2918. \end{definition}
  2919. We recommend implementing \code{explicate\_control} using two mutually
  2920. recursive functions, \code{explicate-tail} and
  2921. \code{explicate-assign}, as suggested in the skeleton code in
  2922. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2923. function should be applied to expressions in tail position whereas the
  2924. \code{explicate-assign} should be applied to expressions that occur on
  2925. the right-hand-side of a \key{let}.
  2926. %
  2927. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2928. input and produces a \Tail{} in \LangCVar{} (see
  2929. Figure~\ref{fig:c0-syntax}).
  2930. %
  2931. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2932. the variable that it is to be assigned to, and a \Tail{} in
  2933. \LangCVar{} for the code that comes after the assignment. The
  2934. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2935. The \code{explicate-assign} function is in accumulator-passing style:
  2936. the \code{cont} parameter is used for accumulating the output. This
  2937. accumulator-passing style plays an important role in how we generate
  2938. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2939. \begin{exercise}\normalfont
  2940. %
  2941. Implement the \code{explicate\_control} function in
  2942. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2943. exercise the code in \code{explicate\_control}.
  2944. %
  2945. In the \code{run-tests.rkt} script, add the following entry to the
  2946. list of \code{passes} and then run the script to test your compiler.
  2947. \begin{lstlisting}
  2948. (list "explicate control" explicate-control interp_Cvar type-check-Cvar)
  2949. \end{lstlisting}
  2950. \end{exercise}
  2951. \fi}
  2952. \section{Select Instructions}
  2953. \label{sec:select-Rvar}
  2954. \index{subject}{instruction selection}
  2955. In the \code{select\_instructions} pass we begin the work of
  2956. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  2957. language of this pass is a variant of x86 that still uses variables,
  2958. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  2959. non-terminal of the \LangXInt{} abstract syntax
  2960. (Figure~\ref{fig:x86-int-ast}).
  2961. \racket{We recommend implementing the
  2962. \code{select\_instructions} with three auxiliary functions, one for
  2963. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  2964. $\Tail$.}
  2965. \python{We recommend implementing an auxiliary function
  2966. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  2967. \racket{
  2968. The cases for $\Atm$ are straightforward; variables stay
  2969. the same and integer constants change to immediates:
  2970. $\INT{n}$ changes to $\IMM{n}$.}
  2971. We consider the cases for the $\Stmt$ non-terminal, starting with
  2972. arithmetic operations. For example, consider the addition
  2973. operation. We can use the \key{addq} instruction, but it performs an
  2974. in-place update. So we could move $\itm{arg}_1$ into the left-hand
  2975. side \itm{var} and then add $\itm{arg}_2$ to \itm{var}.
  2976. \begin{transformation}
  2977. {\if\edition\racketEd\color{olive}
  2978. \begin{lstlisting}
  2979. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2980. \end{lstlisting}
  2981. \fi}
  2982. {\if\edition\pythonEd
  2983. \begin{lstlisting}
  2984. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{arg}_2$|
  2985. \end{lstlisting}
  2986. \fi}
  2987. \compilesto
  2988. \begin{lstlisting}
  2989. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2990. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2991. \end{lstlisting}
  2992. \end{transformation}
  2993. There are also cases that require special care to avoid generating
  2994. needlessly complicated code. For example, if one of the arguments of
  2995. the addition is the same variable as the left-hand side of the
  2996. assignment, then there is no need for the extra move instruction. The
  2997. assignment statement can be translated into a single \key{addq}
  2998. instruction as follows.
  2999. \begin{transformation}
  3000. {\if\edition\racketEd\color{olive}
  3001. \begin{lstlisting}
  3002. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  3003. \end{lstlisting}
  3004. \fi}
  3005. {\if\edition\pythonEd
  3006. \begin{lstlisting}
  3007. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{var}$|
  3008. \end{lstlisting}
  3009. \fi}
  3010. \compilesto
  3011. \begin{lstlisting}
  3012. addq |$\itm{arg}_1$|, |$\itm{var}$|
  3013. \end{lstlisting}
  3014. \end{transformation}
  3015. The \key{read} operation does not have a direct counterpart in x86
  3016. assembly, so we provide this functionality with the function
  3017. \code{read\_int} in the file \code{runtime.c}, written in
  3018. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3019. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3020. system}, or simply the \emph{runtime} for short. When compiling your
  3021. generated x86 assembly code, you need to compile \code{runtime.c} to
  3022. \code{runtime.o} (an ``object file'', using \code{gcc} option
  3023. \code{-c}) and link it into the executable. For our purposes of code
  3024. generation, all you need to do is translate an assignment of
  3025. \key{read} into a call to the \code{read\_int} function followed by a
  3026. move from \code{rax} to the left-hand-side variable. (Recall that the
  3027. return value of a function goes into \code{rax}.)
  3028. \begin{transformation}
  3029. {\if\edition\racketEd\color{olive}
  3030. \begin{lstlisting}
  3031. |$\itm{var}$| = (read);
  3032. \end{lstlisting}
  3033. \fi}
  3034. {\if\edition\pythonEd
  3035. \begin{lstlisting}
  3036. |$\itm{var}$| = input_int();
  3037. \end{lstlisting}
  3038. \fi}
  3039. \compilesto
  3040. \begin{lstlisting}
  3041. callq read_int
  3042. movq %rax, |$\itm{var}$|
  3043. \end{lstlisting}
  3044. \end{transformation}
  3045. {\if\edition\racketEd\color{olive}
  3046. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3047. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3048. assignment to the \key{rax} register followed by a jump to the
  3049. conclusion of the program (so the conclusion needs to be labeled).
  3050. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3051. recursively and then append the resulting instructions.
  3052. \fi}
  3053. \begin{exercise}
  3054. \normalfont
  3055. {\if\edition\racketEd\color{olive}
  3056. Implement the \key{select-instructions} pass in
  3057. \code{compiler.rkt}. Create three new example programs that are
  3058. designed to exercise all of the interesting cases in this pass.
  3059. %
  3060. In the \code{run-tests.rkt} script, add the following entry to the
  3061. list of \code{passes} and then run the script to test your compiler.
  3062. \begin{lstlisting}
  3063. (list "instruction selection" select-instructions interp_pseudo-x86-0)
  3064. \end{lstlisting}
  3065. \fi}
  3066. {\if\edition\pythonEd
  3067. Implement the \key{select\_instructions} pass in
  3068. \code{compiler.py}. Create three new example programs that are
  3069. designed to exercise all of the interesting cases in this pass.
  3070. Run the \code{run-tests.py} script to to check
  3071. whether the output programs produce the same result as the input
  3072. programs.
  3073. \fi}
  3074. \end{exercise}
  3075. \section{Assign Homes}
  3076. \label{sec:assign-Rvar}
  3077. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3078. \LangXVar{} programs that no longer use program variables.
  3079. Thus, the \key{assign-homes} pass is responsible for placing all of
  3080. the program variables in registers or on the stack. For runtime
  3081. efficiency, it is better to place variables in registers, but as there
  3082. are only 16 registers, some programs must necessarily resort to
  3083. placing some variables on the stack. In this chapter we focus on the
  3084. mechanics of placing variables on the stack. We study an algorithm for
  3085. placing variables in registers in
  3086. Chapter~\ref{ch:register-allocation-Rvar}.
  3087. Consider again the following \LangVar{} program from
  3088. Section~\ref{sec:remove-complex-opera-Rvar}.
  3089. % var_test_20.rkt
  3090. {\if\edition\racketEd\color{olive}
  3091. \begin{lstlisting}
  3092. (let ([a 42])
  3093. (let ([b a])
  3094. b))
  3095. \end{lstlisting}
  3096. \fi}
  3097. {\if\edition\pythonEd
  3098. \begin{lstlisting}
  3099. a = 42
  3100. b = a
  3101. print(b)
  3102. \end{lstlisting}
  3103. \fi}
  3104. The output of \code{select\_instructions} is shown on the left and the
  3105. output of \code{assign\_homes} on the right. In this example, we
  3106. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  3107. variable \code{b} to location \code{-16(\%rbp)}.
  3108. \begin{transformation}
  3109. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3110. start:
  3111. movq $42, a
  3112. movq a, b
  3113. movq b, %rax
  3114. jmp conclusion
  3115. \end{lstlisting}
  3116. \compilesto
  3117. %stack-space: 16
  3118. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3119. start:
  3120. movq $42, -8(%rbp)
  3121. movq -8(%rbp), -16(%rbp)
  3122. movq -16(%rbp), %rax
  3123. jmp conclusion
  3124. \end{lstlisting}
  3125. \end{transformation}
  3126. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3127. \code{X86Program} node is an alist mapping all the variables in the
  3128. program to their types (for now just \code{Integer}). The
  3129. \code{assign\_homes} pass should replace all uses of those variables
  3130. with stack locations. As an aside, the \code{locals-types} entry is
  3131. computed by \code{type-check-Cvar} in the support code, which installs
  3132. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  3133. be propagated to the \code{X86Program} node.}
  3134. %
  3135. \python{The \code{assign\_homes} pass should replace all uses of
  3136. variables with stack locations.}
  3137. %
  3138. In the process of assigning variables to stack locations, it is
  3139. convenient for you to compute and store the size of the frame (in
  3140. bytes) in%
  3141. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3142. %
  3143. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3144. which is needed later to generate the conclusion of the \code{main}
  3145. procedure. The x86-64 standard requires the frame size to be a
  3146. multiple of 16 bytes.\index{subject}{frame}
  3147. % TODO: store the number of variables instead? -Jeremy
  3148. \begin{exercise}\normalfont
  3149. Implement the \key{assign\_homes} pass in
  3150. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3151. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  3152. \Block{}. We recommend that the auxiliary functions take an extra
  3153. parameter that maps variable names to homes (stack locations for now).
  3154. %
  3155. {\if\edition\racketEd\color{olive}
  3156. In the \code{run-tests.rkt} script, add the following entry to the
  3157. list of \code{passes} and then run the script to test your compiler.
  3158. \begin{lstlisting}
  3159. (list "assign homes" assign-homes interp_x86-0)
  3160. \end{lstlisting}
  3161. \fi}
  3162. {\if\edition\pythonEd
  3163. Run the \code{run-tests.py} script to to check
  3164. whether the output programs produce the same result as the input
  3165. programs.
  3166. \fi}
  3167. \end{exercise}
  3168. \section{Patch Instructions}
  3169. \label{sec:patch-s0}
  3170. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3171. \LangXInt{} by making sure that each instruction adheres to the
  3172. restriction that at most one argument of an instruction may be a
  3173. memory reference.
  3174. We return to the following example.\\
  3175. \begin{minipage}{0.5\textwidth}
  3176. % var_test_20.rkt
  3177. {\if\edition\racketEd\color{olive}
  3178. \begin{lstlisting}
  3179. (let ([a 42])
  3180. (let ([b a])
  3181. b))
  3182. \end{lstlisting}
  3183. \fi}
  3184. {\if\edition\pythonEd
  3185. \begin{lstlisting}
  3186. a = 42
  3187. b = a
  3188. print(b)
  3189. \end{lstlisting}
  3190. \fi}
  3191. \end{minipage}\\
  3192. The \key{assign\_homes} pass produces the following translation. \\
  3193. \begin{minipage}{0.5\textwidth}
  3194. {\if\edition\racketEd\color{olive}
  3195. \begin{lstlisting}
  3196. movq $42, -8(%rbp)
  3197. movq -8(%rbp), -16(%rbp)
  3198. movq -16(%rbp), %rax
  3199. \end{lstlisting}
  3200. \fi}
  3201. {\if\edition\pythonEd
  3202. \begin{lstlisting}
  3203. movq 42, -8(%rbp)
  3204. movq -8(%rbp), -16(%rbp)
  3205. movq -16(%rbp), %rdi
  3206. callq print_int
  3207. \end{lstlisting}
  3208. \fi}
  3209. \end{minipage}\\
  3210. The second \key{movq} instruction is problematic because both
  3211. arguments are stack locations. We suggest fixing this problem by
  3212. moving from the source location to the register \key{rax} and then
  3213. from \key{rax} to the destination location, as follows.
  3214. \begin{lstlisting}
  3215. movq -8(%rbp), %rax
  3216. movq %rax, -16(%rbp)
  3217. \end{lstlisting}
  3218. \begin{exercise}
  3219. \normalfont Implement the \key{patch\_instructions} pass in
  3220. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3221. Create three new example programs that are
  3222. designed to exercise all of the interesting cases in this pass.
  3223. %
  3224. {\if\edition\racketEd\color{olive}
  3225. In the \code{run-tests.rkt} script, add the following entry to the
  3226. list of \code{passes} and then run the script to test your compiler.
  3227. \begin{lstlisting}
  3228. (list "patch instructions" patch-instructions interp_x86-0)
  3229. \end{lstlisting}
  3230. \fi}
  3231. {\if\edition\pythonEd
  3232. Run the \code{run-tests.py} script to to check
  3233. whether the output programs produce the same result as the input
  3234. programs.
  3235. \fi}
  3236. \end{exercise}
  3237. \section{Print x86}
  3238. \label{sec:print-x86}
  3239. The last step of the compiler from \LangVar{} to x86 is to convert the
  3240. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  3241. string representation (defined in
  3242. Figure~\ref{fig:x86-int-concrete}). \racket{The Racket \key{format} and
  3243. \key{string-append} functions are useful in this regard.} The main work
  3244. that this step needs to perform is to create the \key{main} function
  3245. and the standard instructions for its prelude and conclusion, as shown
  3246. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  3247. know the amount of space needed for the stack frame, which you can
  3248. obtain from the \racket{\code{stack-space} entry in the $\itm{info}$ field}
  3249. \python{\code{stack\_space} field}
  3250. of the \key{X86Program} node.
  3251. When running on Mac OS X, your compiler should prefix an underscore to
  3252. labels like \key{main}. \racket{The Racket call \code{(system-type 'os)} is
  3253. useful for determining which operating system the compiler is running
  3254. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3255. \python{The Python \code{platform} library includes a \code{system()} function
  3256. that returns \code{'Linux'}, \code{'Windows'}, or \code{'Darwin'} (for Mac).}
  3257. \begin{exercise}\normalfont
  3258. %
  3259. Implement the \key{print\_x86} pass in \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3260. %
  3261. {\if\edition\racketEd\color{olive}
  3262. In the \code{run-tests.rkt} script, add the following entry to the
  3263. list of \code{passes} and then run the script to test your compiler.
  3264. \begin{lstlisting}
  3265. (list "print x86" print-x86 #f)
  3266. \end{lstlisting}
  3267. %
  3268. Uncomment the call to the \key{compiler-tests} function
  3269. (Appendix~\ref{appendix:utilities}), which tests your complete
  3270. compiler by executing the generated x86 code. Compile the provided
  3271. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  3272. script to test your compiler.
  3273. \fi}
  3274. {\if\edition\pythonEd
  3275. Run the \code{run-tests.py} script to to check
  3276. whether the output programs produce the same result as the input
  3277. programs.
  3278. \fi}
  3279. \end{exercise}
  3280. \section{Challenge: Partial Evaluator for \LangVar{}}
  3281. \label{sec:pe-Rvar}
  3282. \index{subject}{partial evaluation}
  3283. This section describes optional challenge exercises that involve
  3284. adapting and improving the partial evaluator for \LangInt{} that was
  3285. introduced in Section~\ref{sec:partial-evaluation}.
  3286. \begin{exercise}\label{ex:pe-Rvar}
  3287. \normalfont
  3288. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3289. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3290. instead of \LangInt{} programs. Recall that \LangVar{} adds
  3291. \racket{\key{let} binding}\python{assignment}
  3292. and variables to the \LangInt{} language, so you will need to add cases for
  3293. them in the \code{pe\_exp} \racket{function}\python{and \code{pe\_stmt functions}}. Once complete, add the partial
  3294. evaluation pass to the front of your compiler and make sure that your
  3295. compiler still passes all of the tests.
  3296. \end{exercise}
  3297. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3298. \begin{exercise}
  3299. \normalfont
  3300. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3301. \code{pe\_add} auxiliary functions with functions that know more about
  3302. arithmetic. For example, your partial evaluator should translate
  3303. {\if\edition\racketEd\color{olive}
  3304. \[
  3305. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3306. \code{(+ 2 (read))}
  3307. \]
  3308. \fi}
  3309. {\if\edition\pythonEd
  3310. \[
  3311. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3312. \code{2 + input\_int()}
  3313. \]
  3314. \fi}
  3315. To accomplish this, the \code{pe\_exp} function should produce output
  3316. in the form of the $\itm{residual}$ non-terminal of the following
  3317. grammar. The idea is that when processing an addition expression, we
  3318. can always produce either 1) an integer constant, 2) an addition
  3319. expression with an integer constant on the left-hand side but not the
  3320. right-hand side, or 3) or an addition expression in which neither
  3321. subexpression is a constant.
  3322. {\if\edition\racketEd\color{olive}
  3323. \[
  3324. \begin{array}{lcl}
  3325. \itm{inert} &::=& \Var
  3326. \MID \LP\key{read}\RP
  3327. \MID \LP\key{-} ~\Var\RP
  3328. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3329. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3330. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3331. \itm{residual} &::=& \Int
  3332. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3333. \MID \itm{inert}
  3334. \end{array}
  3335. \]
  3336. \fi}
  3337. {\if\edition\pythonEd
  3338. \[
  3339. \begin{array}{lcl}
  3340. \itm{inert} &::=& \Var
  3341. \MID \key{input\_int}\LP\RP
  3342. \MID \key{-} \Var
  3343. \MID \key{-} \key{input\_int}\LP\RP
  3344. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3345. \itm{residual} &::=& \Int
  3346. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3347. \MID \itm{inert}
  3348. \end{array}
  3349. \]
  3350. \fi}
  3351. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3352. inputs are $\itm{residual}$ expressions and they should return
  3353. $\itm{residual}$ expressions. Once the improvements are complete,
  3354. make sure that your compiler still passes all of the tests. After
  3355. all, fast code is useless if it produces incorrect results!
  3356. \end{exercise}
  3357. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3358. \chapter{Register Allocation}
  3359. \label{ch:register-allocation-Rvar}
  3360. \index{subject}{register allocation}
  3361. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3362. stack. In this Chapter we learn how to improve the performance of the
  3363. generated code by placing some variables into registers. The CPU can
  3364. access a register in a single cycle, whereas accessing the stack can
  3365. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3366. serves as a running example. The source program is on the left and the
  3367. output of instruction selection is on the right. The program is almost
  3368. in the x86 assembly language but it still uses variables.
  3369. \begin{figure}
  3370. \begin{minipage}{0.45\textwidth}
  3371. Example \LangVar{} program:
  3372. % var_test_28.rkt
  3373. {\if\edition\racketEd\color{olive}
  3374. \begin{lstlisting}
  3375. (let ([v 1])
  3376. (let ([w 42])
  3377. (let ([x (+ v 7)])
  3378. (let ([y x])
  3379. (let ([z (+ x w)])
  3380. (+ z (- y)))))))
  3381. \end{lstlisting}
  3382. \fi}
  3383. {\if\edition\pythonEd
  3384. \begin{lstlisting}
  3385. v = 1
  3386. w = 42
  3387. x = v + 7
  3388. y = x
  3389. z = x + w
  3390. print(z + (- y))
  3391. \end{lstlisting}
  3392. \fi}
  3393. \end{minipage}
  3394. \begin{minipage}{0.45\textwidth}
  3395. After instruction selection:
  3396. {\if\edition\racketEd\color{olive}
  3397. \begin{lstlisting}
  3398. locals-types:
  3399. x : Integer, y : Integer,
  3400. z : Integer, t : Integer,
  3401. v : Integer, w : Integer
  3402. start:
  3403. movq $1, v
  3404. movq $42, w
  3405. movq v, x
  3406. addq $7, x
  3407. movq x, y
  3408. movq x, z
  3409. addq w, z
  3410. movq y, t
  3411. negq t
  3412. movq z, %rax
  3413. addq t, %rax
  3414. jmp conclusion
  3415. \end{lstlisting}
  3416. \fi}
  3417. {\if\edition\pythonEd
  3418. \begin{lstlisting}
  3419. movq $1, v
  3420. movq $42, w
  3421. movq v, x
  3422. addq $7, x
  3423. movq x, y
  3424. movq x, z
  3425. addq w, z
  3426. movq y, tmp_0
  3427. negq tmp_0
  3428. movq z, tmp_1
  3429. addq tmp_0, tmp_1
  3430. movq tmp_1, %rdi
  3431. callq print_int
  3432. \end{lstlisting}
  3433. \fi}
  3434. \end{minipage}
  3435. \caption{A running example for register allocation.}
  3436. \label{fig:reg-eg}
  3437. \end{figure}
  3438. The goal of register allocation is to fit as many variables into
  3439. registers as possible. Some programs have more variables than
  3440. registers so we cannot always map each variable to a different
  3441. register. Fortunately, it is common for different variables to be
  3442. needed during different periods of time during program execution, and
  3443. in such cases several variables can be mapped to the same register.
  3444. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3445. After the variable \code{x} is moved to \code{z} it is no longer
  3446. needed. Variable \code{z}, on the other hand, is used only after this
  3447. point, so \code{x} and \code{z} could share the same register. The
  3448. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3449. where a variable is needed. Once we have that information, we compute
  3450. which variables are needed at the same time, i.e., which ones
  3451. \emph{interfere} with each other, and represent this relation as an
  3452. undirected graph whose vertices are variables and edges indicate when
  3453. two variables interfere (Section~\ref{sec:build-interference}). We
  3454. then model register allocation as a graph coloring problem
  3455. (Section~\ref{sec:graph-coloring}).
  3456. If we run out of registers despite these efforts, we place the
  3457. remaining variables on the stack, similar to what we did in
  3458. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3459. for assigning a variable to a stack location. The decision to spill a
  3460. variable is handled as part of the graph coloring process
  3461. (Section~\ref{sec:graph-coloring}).
  3462. We make the simplifying assumption that each variable is assigned to
  3463. one location (a register or stack address). A more sophisticated
  3464. approach is to assign a variable to one or more locations in different
  3465. regions of the program. For example, if a variable is used many times
  3466. in short sequence and then only used again after many other
  3467. instructions, it could be more efficient to assign the variable to a
  3468. register during the initial sequence and then move it to the stack for
  3469. the rest of its lifetime. We refer the interested reader to
  3470. \citet{Cooper:2011aa} for more information about that approach.
  3471. % discuss prioritizing variables based on how much they are used.
  3472. \section{Registers and Calling Conventions}
  3473. \label{sec:calling-conventions}
  3474. \index{subject}{calling conventions}
  3475. As we perform register allocation, we need to be aware of the
  3476. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3477. functions calls are performed in x86.
  3478. %
  3479. Even though \LangVar{} does not include programmer-defined functions,
  3480. our generated code includes a \code{main} function that is called by
  3481. the operating system and our generated code contains calls to the
  3482. \code{read\_int} function.
  3483. Function calls require coordination between two pieces of code that
  3484. may be written by different programmers or generated by different
  3485. compilers. Here we follow the System V calling conventions that are
  3486. used by the GNU C compiler on Linux and
  3487. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3488. %
  3489. The calling conventions include rules about how functions share the
  3490. use of registers. In particular, the caller is responsible for freeing
  3491. up some registers prior to the function call for use by the callee.
  3492. These are called the \emph{caller-saved registers}
  3493. \index{subject}{caller-saved registers}
  3494. and they are
  3495. \begin{lstlisting}
  3496. rax rcx rdx rsi rdi r8 r9 r10 r11
  3497. \end{lstlisting}
  3498. On the other hand, the callee is responsible for preserving the values
  3499. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3500. which are
  3501. \begin{lstlisting}
  3502. rsp rbp rbx r12 r13 r14 r15
  3503. \end{lstlisting}
  3504. We can think about this caller/callee convention from two points of
  3505. view, the caller view and the callee view:
  3506. \begin{itemize}
  3507. \item The caller should assume that all the caller-saved registers get
  3508. overwritten with arbitrary values by the callee. On the other hand,
  3509. the caller can safely assume that all the callee-saved registers
  3510. contain the same values after the call that they did before the
  3511. call.
  3512. \item The callee can freely use any of the caller-saved registers.
  3513. However, if the callee wants to use a callee-saved register, the
  3514. callee must arrange to put the original value back in the register
  3515. prior to returning to the caller. This can be accomplished by saving
  3516. the value to the stack in the prelude of the function and restoring
  3517. the value in the conclusion of the function.
  3518. \end{itemize}
  3519. In x86, registers are also used for passing arguments to a function
  3520. and for the return value. In particular, the first six arguments to a
  3521. function are passed in the following six registers, in this order.
  3522. \begin{lstlisting}
  3523. rdi rsi rdx rcx r8 r9
  3524. \end{lstlisting}
  3525. If there are more than six arguments, then the convention is to use
  3526. space on the frame of the caller for the rest of the
  3527. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3528. need more than six arguments. For now, the only function we care about
  3529. is \code{read\_int} and it takes zero arguments.
  3530. %
  3531. The register \code{rax} is used for the return value of a function.
  3532. The next question is how these calling conventions impact register
  3533. allocation. Consider the \LangVar{} program in
  3534. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3535. example from the caller point of view and then from the callee point
  3536. of view.
  3537. The program makes two calls to the \code{read} function. Also, the
  3538. variable \code{x} is in use during the second call to \code{read}, so
  3539. we need to make sure that the value in \code{x} does not get
  3540. accidentally wiped out by the call to \code{read}. One obvious
  3541. approach is to save all the values in caller-saved registers to the
  3542. stack prior to each function call, and restore them after each
  3543. call. That way, if the register allocator chooses to assign \code{x}
  3544. to a caller-saved register, its value will be preserved across the
  3545. call to \code{read}. However, saving and restoring to the stack is
  3546. relatively slow. If \code{x} is not used many times, it may be better
  3547. to assign \code{x} to a stack location in the first place. Or better
  3548. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3549. register, then it won't need to be saved and restored during function
  3550. calls.
  3551. The approach that we recommend for variables that are in use during a
  3552. function call is to either assign them to callee-saved registers or to
  3553. spill them to the stack. On the other hand, for variables that are not
  3554. in use during a function call, we try the following alternatives in
  3555. order 1) look for an available caller-saved register (to leave room
  3556. for other variables in the callee-saved register), 2) look for a
  3557. callee-saved register, and 3) spill the variable to the stack.
  3558. It is straightforward to implement this approach in a graph coloring
  3559. register allocator. First, we know which variables are in use during
  3560. every function call because we compute that information for every
  3561. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3562. build the interference graph (Section~\ref{sec:build-interference}),
  3563. we can place an edge between each of these variables and the
  3564. caller-saved registers in the interference graph. This will prevent
  3565. the graph coloring algorithm from assigning those variables to
  3566. caller-saved registers.
  3567. Returning to the example in
  3568. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3569. generated x86 code on the right-hand side, focusing on the
  3570. \code{start} block. Notice that variable \code{x} is assigned to
  3571. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3572. place during the second call to \code{read\_int}. Next, notice that
  3573. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3574. because there are no function calls in the remainder of the block.
  3575. Next we analyze the example from the callee point of view, focusing on
  3576. the prelude and conclusion of the \code{main} function. As usual the
  3577. prelude begins with saving the \code{rbp} register to the stack and
  3578. setting the \code{rbp} to the current stack pointer. We now know why
  3579. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3580. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3581. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3582. (\code{x}). The other callee-saved registers are not saved in the
  3583. prelude because they are not used. The prelude subtracts 8 bytes from
  3584. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3585. conclusion, we see that \code{rbx} is restored from the stack with a
  3586. \code{popq} instruction.
  3587. \index{subject}{prelude}\index{subject}{conclusion}
  3588. \begin{figure}[tp]
  3589. \begin{minipage}{0.45\textwidth}
  3590. Example \LangVar{} program:
  3591. %var_test_14.rkt
  3592. {\if\edition\racketEd\color{olive}
  3593. \begin{lstlisting}
  3594. (let ([x (read)])
  3595. (let ([y (read)])
  3596. (+ (+ x y) 42)))
  3597. \end{lstlisting}
  3598. \fi}
  3599. {\if\edition\pythonEd
  3600. \begin{lstlisting}
  3601. x = input_int()
  3602. y = input_int()
  3603. print((x + y) + 42)
  3604. \end{lstlisting}
  3605. \fi}
  3606. \end{minipage}
  3607. \begin{minipage}{0.45\textwidth}
  3608. Generated x86 assembly:
  3609. {\if\edition\racketEd\color{olive}
  3610. \begin{lstlisting}
  3611. start:
  3612. callq read_int
  3613. movq %rax, %rbx
  3614. callq read_int
  3615. movq %rax, %rcx
  3616. addq %rcx, %rbx
  3617. movq %rbx, %rax
  3618. addq $42, %rax
  3619. jmp _conclusion
  3620. .globl main
  3621. main:
  3622. pushq %rbp
  3623. movq %rsp, %rbp
  3624. pushq %rbx
  3625. subq $8, %rsp
  3626. jmp start
  3627. conclusion:
  3628. addq $8, %rsp
  3629. popq %rbx
  3630. popq %rbp
  3631. retq
  3632. \end{lstlisting}
  3633. \fi}
  3634. {\if\edition\pythonEd
  3635. \begin{lstlisting}
  3636. .globl main
  3637. main:
  3638. pushq %rbp
  3639. movq %rsp, %rbp
  3640. pushq %rbx
  3641. subq $8, %rsp
  3642. callq read_int
  3643. movq %rax, %rbx
  3644. callq read_int
  3645. movq %rax, %rcx
  3646. movq %rbx, %rdx
  3647. addq %rcx, %rdx
  3648. movq %rdx, %rcx
  3649. addq $42, %rcx
  3650. movq %rcx, %rdi
  3651. callq print_int
  3652. addq $8, %rsp
  3653. popq %rbx
  3654. popq %rbp
  3655. retq
  3656. \end{lstlisting}
  3657. \fi}
  3658. \end{minipage}
  3659. \caption{An example with function calls.}
  3660. \label{fig:example-calling-conventions}
  3661. \end{figure}
  3662. %\clearpage
  3663. \section{Liveness Analysis}
  3664. \label{sec:liveness-analysis-Rvar}
  3665. \index{subject}{liveness analysis}
  3666. The \code{uncover\_live} \racket{pass}\python{function}
  3667. performs \emph{liveness analysis}, that
  3668. is, it discovers which variables are in-use in different regions of a
  3669. program.
  3670. %
  3671. A variable or register is \emph{live} at a program point if its
  3672. current value is used at some later point in the program. We
  3673. refer to variables and registers collectively as \emph{locations}.
  3674. %
  3675. Consider the following code fragment in which there are two writes to
  3676. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3677. \begin{center}
  3678. \begin{minipage}{0.96\textwidth}
  3679. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3680. movq $5, a
  3681. movq $30, b
  3682. movq a, c
  3683. movq $10, b
  3684. addq b, c
  3685. \end{lstlisting}
  3686. \end{minipage}
  3687. \end{center}
  3688. The answer is no because \code{a} is live from line 1 to 3 and
  3689. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3690. line 2 is never used because it is overwritten (line 4) before the
  3691. next read (line 5).
  3692. The live locations can be computed by traversing the instruction
  3693. sequence back to front (i.e., backwards in execution order). Let
  3694. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3695. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3696. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3697. locations before instruction $I_k$.
  3698. \racket{We recommend representing these
  3699. sets with the Racket \code{set} data structure described in
  3700. Figure~\ref{fig:set}.}
  3701. \python{We recommend representing these sets with the Python
  3702. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3703. data structure.}
  3704. {\if\edition\racketEd\color{olive}
  3705. \begin{figure}[tp]
  3706. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3707. \small
  3708. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3709. A \emph{set} is an unordered collection of elements without duplicates.
  3710. Here are some of the operations defined on sets.
  3711. \index{subject}{set}
  3712. \begin{description}
  3713. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3714. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3715. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3716. difference of the two sets.
  3717. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3718. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3719. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3720. \end{description}
  3721. \end{tcolorbox}
  3722. %\end{wrapfigure}
  3723. \caption{The \code{set} data structure.}
  3724. \label{fig:set}
  3725. \end{figure}
  3726. \fi}
  3727. The live locations after an instruction are always the same as the
  3728. live locations before the next instruction.
  3729. \index{subject}{live-after} \index{subject}{live-before}
  3730. \begin{equation} \label{eq:live-after-before-next}
  3731. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3732. \end{equation}
  3733. To start things off, there are no live locations after the last
  3734. instruction, so
  3735. \begin{equation}\label{eq:live-last-empty}
  3736. L_{\mathsf{after}}(n) = \emptyset
  3737. \end{equation}
  3738. We then apply the following rule repeatedly, traversing the
  3739. instruction sequence back to front.
  3740. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3741. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3742. \end{equation}
  3743. where $W(k)$ are the locations written to by instruction $I_k$ and
  3744. $R(k)$ are the locations read by instruction $I_k$.
  3745. {\if\edition\racketEd\color{olive}
  3746. There is a special case for \code{jmp} instructions. The locations
  3747. that are live before a \code{jmp} should be the locations in
  3748. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3749. maintaining an alist named \code{label->live} that maps each label to
  3750. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3751. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3752. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3753. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3754. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3755. \fi}
  3756. Let us walk through the above example, applying these formulas
  3757. starting with the instruction on line 5. We collect the answers in
  3758. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3759. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3760. instruction (formula~\ref{eq:live-last-empty}). The
  3761. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3762. because it reads from variables \code{b} and \code{c}
  3763. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3764. \[
  3765. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3766. \]
  3767. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3768. the live-before set from line 5 to be the live-after set for this
  3769. instruction (formula~\ref{eq:live-after-before-next}).
  3770. \[
  3771. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3772. \]
  3773. This move instruction writes to \code{b} and does not read from any
  3774. variables, so we have the following live-before set
  3775. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3776. \[
  3777. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3778. \]
  3779. The live-before for instruction \code{movq a, c}
  3780. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3781. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3782. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3783. variable that is not live and does not read from a variable.
  3784. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3785. because it writes to variable \code{a}.
  3786. \begin{figure}[tbp]
  3787. \begin{minipage}{0.45\textwidth}
  3788. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3789. movq $5, a
  3790. movq $30, b
  3791. movq a, c
  3792. movq $10, b
  3793. addq b, c
  3794. \end{lstlisting}
  3795. \end{minipage}
  3796. \vrule\hspace{10pt}
  3797. \begin{minipage}{0.45\textwidth}
  3798. \begin{align*}
  3799. L_{\mathsf{before}}(1)= \emptyset,
  3800. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3801. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3802. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3803. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3804. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3805. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3806. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3807. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3808. L_{\mathsf{after}}(5)= \emptyset
  3809. \end{align*}
  3810. \end{minipage}
  3811. \caption{Example output of liveness analysis on a short example.}
  3812. \label{fig:liveness-example-0}
  3813. \end{figure}
  3814. \begin{exercise}\normalfont
  3815. Perform liveness analysis on the running example in
  3816. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3817. sets for each instruction. Compare your answers to the solution
  3818. shown in Figure~\ref{fig:live-eg}.
  3819. \end{exercise}
  3820. \begin{figure}[tp]
  3821. \hspace{20pt}
  3822. \begin{minipage}{0.45\textwidth}
  3823. {\if\edition\racketEd\color{olive}
  3824. \begin{lstlisting}
  3825. |$\{\ttm{rsp}\}$|
  3826. movq $1, v
  3827. |$\{\ttm{v},\ttm{rsp}\}$|
  3828. movq $42, w
  3829. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3830. movq v, x
  3831. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3832. addq $7, x
  3833. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3834. movq x, y
  3835. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3836. movq x, z
  3837. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3838. addq w, z
  3839. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3840. movq y, t
  3841. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3842. negq t
  3843. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3844. movq z, %rax
  3845. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3846. addq t, %rax
  3847. |$\{\ttm{rax},\ttm{rsp}\}$|
  3848. jmp conclusion
  3849. \end{lstlisting}
  3850. \fi}
  3851. {\if\edition\pythonEd
  3852. \begin{lstlisting}
  3853. movq $1, v
  3854. |$\{\ttm{v}\}$|
  3855. movq $42, w
  3856. |$\{\ttm{w}, \ttm{v}\}$|
  3857. movq v, x
  3858. |$\{\ttm{w}, \ttm{x}\}$|
  3859. addq $7, x
  3860. |$\{\ttm{w}, \ttm{x}\}$|
  3861. movq x, y
  3862. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  3863. movq x, z
  3864. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  3865. addq w, z
  3866. |$\{\ttm{y}, \ttm{z}\}$|
  3867. movq y, tmp_0
  3868. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3869. negq tmp_0
  3870. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3871. movq z, tmp_1
  3872. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  3873. addq tmp_0, tmp_1
  3874. |$\{\ttm{tmp\_1}\}$|
  3875. movq tmp_1, %rdi
  3876. |$\{\ttm{rdi}\}$|
  3877. callq print_int
  3878. |$\{\}$|
  3879. \end{lstlisting}
  3880. \fi}
  3881. \end{minipage}
  3882. \caption{The running example annotated with live-after sets.}
  3883. \label{fig:live-eg}
  3884. \end{figure}
  3885. \begin{exercise}\normalfont
  3886. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  3887. %
  3888. \racket{Store the sequence of live-after sets in the $\itm{info}$
  3889. field of the \code{Block} structure.}
  3890. %
  3891. \python{Return a dictionary that maps each instruction to its
  3892. live-after set.}
  3893. %
  3894. \racket{We recommend creating an auxiliary function that takes a list
  3895. of instructions and an initial live-after set (typically empty) and
  3896. returns the list of live-after sets.}
  3897. %
  3898. We recommend creating auxiliary functions to 1) compute the set
  3899. of locations that appear in an \Arg{}, 2) compute the locations read
  3900. by an instruction (the $R$ function), and 3) the locations written by
  3901. an instruction (the $W$ function). The \code{callq} instruction should
  3902. include all of the caller-saved registers in its write-set $W$ because
  3903. the calling convention says that those registers may be written to
  3904. during the function call. Likewise, the \code{callq} instruction
  3905. should include the appropriate argument-passing registers in its
  3906. read-set $R$, depending on the arity of the function being
  3907. called. (This is why the abstract syntax for \code{callq} includes the
  3908. arity.)
  3909. \end{exercise}
  3910. %\clearpage
  3911. \section{Build the Interference Graph}
  3912. \label{sec:build-interference}
  3913. {\if\edition\racketEd\color{olive}
  3914. \begin{figure}[tp]
  3915. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3916. \small
  3917. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3918. A \emph{graph} is a collection of vertices and edges where each
  3919. edge connects two vertices. A graph is \emph{directed} if each
  3920. edge points from a source to a target. Otherwise the graph is
  3921. \emph{undirected}.
  3922. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3923. \begin{description}
  3924. %% We currently don't use directed graphs. We instead use
  3925. %% directed multi-graphs. -Jeremy
  3926. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3927. directed graph from a list of edges. Each edge is a list
  3928. containing the source and target vertex.
  3929. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3930. undirected graph from a list of edges. Each edge is represented by
  3931. a list containing two vertices.
  3932. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3933. inserts a vertex into the graph.
  3934. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3935. inserts an edge between the two vertices.
  3936. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3937. returns a sequence of vertices adjacent to the vertex.
  3938. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3939. returns a sequence of all vertices in the graph.
  3940. \end{description}
  3941. \end{tcolorbox}
  3942. %\end{wrapfigure}
  3943. \caption{The Racket \code{graph} package.}
  3944. \label{fig:graph}
  3945. \end{figure}
  3946. \fi}
  3947. Based on the liveness analysis, we know where each location is live.
  3948. However, during register allocation, we need to answer questions of
  3949. the specific form: are locations $u$ and $v$ live at the same time?
  3950. (And therefore cannot be assigned to the same register.) To make this
  3951. question more efficient to answer, we create an explicit data
  3952. structure, an \emph{interference graph}\index{subject}{interference
  3953. graph}. An interference graph is an undirected graph that has an
  3954. edge between two locations if they are live at the same time, that is,
  3955. if they interfere with each other.
  3956. %
  3957. \racket{We recommend using the Racket \code{graph} package
  3958. (Figure~\ref{fig:graph}) to represent the interference graph.}
  3959. %
  3960. \python{We provide implementations of directed and undirected graph
  3961. data structures in the file \code{graph.py} of the support code.}
  3962. A straightforward way to compute the interference graph is to look at
  3963. the set of live locations between each instruction and the next and
  3964. add an edge to the graph for every pair of variables in the same set.
  3965. This approach is less than ideal for two reasons. First, it can be
  3966. expensive because it takes $O(n^2)$ time to consider at every pair in
  3967. a set of $n$ live locations. Second, in the special case where two
  3968. locations hold the same value (because one was assigned to the other),
  3969. they can be live at the same time without interfering with each other.
  3970. A better way to compute the interference graph is to focus on
  3971. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3972. must not overwrite something in a live location. So for each
  3973. instruction, we create an edge between the locations being written to
  3974. and the live locations. (Except that one should not create self
  3975. edges.) Note that for the \key{callq} instruction, we consider all of
  3976. the caller-saved registers as being written to, so an edge is added
  3977. between every live variable and every caller-saved register. For
  3978. \key{movq}, we deal with the above-mentioned special case by not
  3979. adding an edge between a live variable $v$ and the destination if $v$
  3980. matches the source. So we have the following two rules.
  3981. \begin{enumerate}
  3982. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3983. $d$, then add the edge $(d,v)$ for every $v \in
  3984. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3985. \item For any other instruction $I_k$, for every $d \in W(k)$
  3986. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3987. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3988. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3989. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3990. %% \item If instruction $I_k$ is of the form \key{callq}
  3991. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3992. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3993. \end{enumerate}
  3994. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3995. the above rules to each instruction. We highlight a few of the
  3996. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  3997. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  3998. so \code{v} interferes with \code{rsp}.}
  3999. %
  4000. \python{The first instruction is \lstinline{movq $1, v} and the
  4001. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4002. no interference because $\ttm{v}$ is the destination of the move.}
  4003. %
  4004. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4005. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4006. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4007. %
  4008. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4009. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4010. $\ttm{x}$ interferes with \ttm{w}.}
  4011. %
  4012. \racket{The next instruction is \lstinline{movq x, y} and the
  4013. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4014. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4015. \ttm{x} because \ttm{x} is the source of the move and therefore
  4016. \ttm{x} and \ttm{y} hold the same value.}
  4017. %
  4018. \python{The next instruction is \lstinline{movq x, y} and the
  4019. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4020. applies, so \ttm{y} interferes with \ttm{w} but not
  4021. \ttm{x} because \ttm{x} is the source of the move and therefore
  4022. \ttm{x} and \ttm{y} hold the same value.}
  4023. %
  4024. Figure~\ref{fig:interference-results} lists the interference results
  4025. for all of the instructions and the resulting interference graph is
  4026. shown in Figure~\ref{fig:interfere}.
  4027. \begin{figure}[tbp]
  4028. \begin{quote}
  4029. {\if\edition\racketEd\color{olive}
  4030. \begin{tabular}{ll}
  4031. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4032. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4033. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4034. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4035. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4036. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4037. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4038. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4039. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4040. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4041. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4042. \lstinline!jmp conclusion!& no interference.
  4043. \end{tabular}
  4044. \fi}
  4045. {\if\edition\pythonEd
  4046. \begin{tabular}{ll}
  4047. \lstinline!movq $1, v!& no interference\\
  4048. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4049. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4050. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4051. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4052. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4053. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4054. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4055. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4056. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4057. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4058. \lstinline!movq tmp_1, %rdi! & no interference \\
  4059. \lstinline!callq print_int!& no interference.
  4060. \end{tabular}
  4061. \fi}
  4062. \end{quote}
  4063. \caption{Interference results for the running example.}
  4064. \label{fig:interference-results}
  4065. \end{figure}
  4066. \begin{figure}[tbp]
  4067. \large
  4068. {\if\edition\racketEd\color{olive}
  4069. \[
  4070. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4071. \node (rax) at (0,0) {$\ttm{rax}$};
  4072. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4073. \node (t1) at (0,2) {$\ttm{t}$};
  4074. \node (z) at (3,2) {$\ttm{z}$};
  4075. \node (x) at (6,2) {$\ttm{x}$};
  4076. \node (y) at (3,0) {$\ttm{y}$};
  4077. \node (w) at (6,0) {$\ttm{w}$};
  4078. \node (v) at (9,0) {$\ttm{v}$};
  4079. \draw (t1) to (rax);
  4080. \draw (t1) to (z);
  4081. \draw (z) to (y);
  4082. \draw (z) to (w);
  4083. \draw (x) to (w);
  4084. \draw (y) to (w);
  4085. \draw (v) to (w);
  4086. \draw (v) to (rsp);
  4087. \draw (w) to (rsp);
  4088. \draw (x) to (rsp);
  4089. \draw (y) to (rsp);
  4090. \path[-.,bend left=15] (z) edge node {} (rsp);
  4091. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4092. \draw (rax) to (rsp);
  4093. \end{tikzpicture}
  4094. \]
  4095. \fi}
  4096. {\if\edition\pythonEd
  4097. \[
  4098. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4099. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4100. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4101. \node (z) at (3,2) {$\ttm{z}$};
  4102. \node (x) at (6,2) {$\ttm{x}$};
  4103. \node (y) at (3,0) {$\ttm{y}$};
  4104. \node (w) at (6,0) {$\ttm{w}$};
  4105. \node (v) at (9,0) {$\ttm{v}$};
  4106. \draw (t0) to (t1);
  4107. \draw (t0) to (z);
  4108. \draw (z) to (y);
  4109. \draw (z) to (w);
  4110. \draw (x) to (w);
  4111. \draw (y) to (w);
  4112. \draw (v) to (w);
  4113. \end{tikzpicture}
  4114. \]
  4115. \fi}
  4116. \caption{The interference graph of the example program.}
  4117. \label{fig:interfere}
  4118. \end{figure}
  4119. %% Our next concern is to choose a data structure for representing the
  4120. %% interference graph. There are many choices for how to represent a
  4121. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4122. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4123. %% data structure is to study the algorithm that uses the data structure,
  4124. %% determine what operations need to be performed, and then choose the
  4125. %% data structure that provide the most efficient implementations of
  4126. %% those operations. Often times the choice of data structure can have an
  4127. %% effect on the time complexity of the algorithm, as it does here. If
  4128. %% you skim the next section, you will see that the register allocation
  4129. %% algorithm needs to ask the graph for all of its vertices and, given a
  4130. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4131. %% correct choice of graph representation is that of an adjacency
  4132. %% list. There are helper functions in \code{utilities.rkt} for
  4133. %% representing graphs using the adjacency list representation:
  4134. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4135. %% (Appendix~\ref{appendix:utilities}).
  4136. %% %
  4137. %% \margincomment{\footnotesize To do: change to use the
  4138. %% Racket graph library. \\ --Jeremy}
  4139. %% %
  4140. %% In particular, those functions use a hash table to map each vertex to
  4141. %% the set of adjacent vertices, and the sets are represented using
  4142. %% Racket's \key{set}, which is also a hash table.
  4143. \begin{exercise}\normalfont
  4144. \racket{Implement the compiler pass named \code{build\_interference} according
  4145. to the algorithm suggested above. We recommend using the Racket
  4146. \code{graph} package to create and inspect the interference graph.
  4147. The output graph of this pass should be stored in the $\itm{info}$ field of
  4148. the program, under the key \code{conflicts}.}
  4149. %
  4150. \python{Implement a function named \code{build\_interference}
  4151. according to the algorithm suggested above that
  4152. returns the interference graph.}
  4153. \end{exercise}
  4154. \section{Graph Coloring via Sudoku}
  4155. \label{sec:graph-coloring}
  4156. \index{subject}{graph coloring}
  4157. \index{subject}{Sudoku}
  4158. \index{subject}{color}
  4159. We come to the main event, mapping variables to registers and stack
  4160. locations. Variables that interfere with each other must be mapped to
  4161. different locations. In terms of the interference graph, this means
  4162. that adjacent vertices must be mapped to different locations. If we
  4163. think of locations as colors, the register allocation problem becomes
  4164. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4165. The reader may be more familiar with the graph coloring problem than he
  4166. or she realizes; the popular game of Sudoku is an instance of the
  4167. graph coloring problem. The following describes how to build a graph
  4168. out of an initial Sudoku board.
  4169. \begin{itemize}
  4170. \item There is one vertex in the graph for each Sudoku square.
  4171. \item There is an edge between two vertices if the corresponding squares
  4172. are in the same row, in the same column, or if the squares are in
  4173. the same $3\times 3$ region.
  4174. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4175. \item Based on the initial assignment of numbers to squares in the
  4176. Sudoku board, assign the corresponding colors to the corresponding
  4177. vertices in the graph.
  4178. \end{itemize}
  4179. If you can color the remaining vertices in the graph with the nine
  4180. colors, then you have also solved the corresponding game of Sudoku.
  4181. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4182. the corresponding graph with colored vertices. We map the Sudoku
  4183. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4184. sampling of the vertices (the colored ones) because showing edges for
  4185. all of the vertices would make the graph unreadable.
  4186. \begin{figure}[tbp]
  4187. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4188. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4189. \caption{A Sudoku game board and the corresponding colored graph.}
  4190. \label{fig:sudoku-graph}
  4191. \end{figure}
  4192. Some techniques for playing Sudoku correspond to heuristics used in
  4193. graph coloring algorithms. For example, one of the basic techniques
  4194. for Sudoku is called Pencil Marks. The idea is to use a process of
  4195. elimination to determine what numbers are no longer available for a
  4196. square and write down those numbers in the square (writing very
  4197. small). For example, if the number $1$ is assigned to a square, then
  4198. write the pencil mark $1$ in all the squares in the same row, column,
  4199. and region to indicate that $1$ is no longer an option for those other
  4200. squares.
  4201. %
  4202. The Pencil Marks technique corresponds to the notion of
  4203. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4204. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4205. are no longer available. In graph terminology, we have the following
  4206. definition:
  4207. \begin{equation*}
  4208. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4209. \text{ and } \mathrm{color}(v) = c \}
  4210. \end{equation*}
  4211. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4212. edge with $u$.
  4213. Using the Pencil Marks technique leads to a simple strategy for
  4214. filling in numbers: if there is a square with only one possible number
  4215. left, then choose that number! But what if there are no squares with
  4216. only one possibility left? One brute-force approach is to try them
  4217. all: choose the first one and if that ultimately leads to a solution,
  4218. great. If not, backtrack and choose the next possibility. One good
  4219. thing about Pencil Marks is that it reduces the degree of branching in
  4220. the search tree. Nevertheless, backtracking can be terribly time
  4221. consuming. One way to reduce the amount of backtracking is to use the
  4222. most-constrained-first heuristic (aka. minimum remaining
  4223. values)~\citep{Russell2003}. That is, when choosing a square, always
  4224. choose one with the fewest possibilities left (the vertex with the
  4225. highest saturation). The idea is that choosing highly constrained
  4226. squares earlier rather than later is better because later on there may
  4227. not be any possibilities left in the highly saturated squares.
  4228. However, register allocation is easier than Sudoku because the
  4229. register allocator can map variables to stack locations when the
  4230. registers run out. Thus, it makes sense to replace backtracking with
  4231. greedy search: make the best choice at the time and keep going. We
  4232. still wish to minimize the number of colors needed, so we use the
  4233. most-constrained-first heuristic in the greedy search.
  4234. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4235. algorithm for register allocation based on saturation and the
  4236. most-constrained-first heuristic. It is roughly equivalent to the
  4237. DSATUR
  4238. algorithm~\citep{Brelaz:1979eu}.
  4239. %,Gebremedhin:1999fk,Omari:2006uq
  4240. Just as in Sudoku, the algorithm represents colors with integers. The
  4241. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4242. for register allocation. The integers $k$ and larger correspond to
  4243. stack locations. The registers that are not used for register
  4244. allocation, such as \code{rax}, are assigned to negative integers. In
  4245. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4246. %% One might wonder why we include registers at all in the liveness
  4247. %% analysis and interference graph. For example, we never allocate a
  4248. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4249. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  4250. %% to use register for passing arguments to functions, it will be
  4251. %% necessary for those registers to appear in the interference graph
  4252. %% because those registers will also be assigned to variables, and we
  4253. %% don't want those two uses to encroach on each other. Regarding
  4254. %% registers such as \code{rax} and \code{rsp} that are not used for
  4255. %% variables, we could omit them from the interference graph but that
  4256. %% would require adding special cases to our algorithm, which would
  4257. %% complicate the logic for little gain.
  4258. \begin{figure}[btp]
  4259. \centering
  4260. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4261. Algorithm: DSATUR
  4262. Input: a graph |$G$|
  4263. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4264. |$W \gets \mathrm{vertices}(G)$|
  4265. while |$W \neq \emptyset$| do
  4266. pick a vertex |$u$| from |$W$| with the highest saturation,
  4267. breaking ties randomly
  4268. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4269. |$\mathrm{color}[u] \gets c$|
  4270. |$W \gets W - \{u\}$|
  4271. \end{lstlisting}
  4272. \caption{The saturation-based greedy graph coloring algorithm.}
  4273. \label{fig:satur-algo}
  4274. \end{figure}
  4275. {\if\edition\racketEd\color{olive}
  4276. With the DSATUR algorithm in hand, let us return to the running
  4277. example and consider how to color the interference graph in
  4278. Figure~\ref{fig:interfere}.
  4279. %
  4280. We start by assigning the register nodes to their own color. For
  4281. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4282. assigned $-2$. The variables are not yet colored, so they are
  4283. annotated with a dash. We then update the saturation for vertices that
  4284. are adjacent to a register, obtaining the following annotated
  4285. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4286. it interferes with both \code{rax} and \code{rsp}.
  4287. \[
  4288. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4289. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4290. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4291. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4292. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4293. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4294. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4295. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4296. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4297. \draw (t1) to (rax);
  4298. \draw (t1) to (z);
  4299. \draw (z) to (y);
  4300. \draw (z) to (w);
  4301. \draw (x) to (w);
  4302. \draw (y) to (w);
  4303. \draw (v) to (w);
  4304. \draw (v) to (rsp);
  4305. \draw (w) to (rsp);
  4306. \draw (x) to (rsp);
  4307. \draw (y) to (rsp);
  4308. \path[-.,bend left=15] (z) edge node {} (rsp);
  4309. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4310. \draw (rax) to (rsp);
  4311. \end{tikzpicture}
  4312. \]
  4313. The algorithm says to select a maximally saturated vertex. So we pick
  4314. $\ttm{t}$ and color it with the first available integer, which is
  4315. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4316. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4317. \[
  4318. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4319. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4320. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4321. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4322. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4323. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4324. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4325. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4326. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4327. \draw (t1) to (rax);
  4328. \draw (t1) to (z);
  4329. \draw (z) to (y);
  4330. \draw (z) to (w);
  4331. \draw (x) to (w);
  4332. \draw (y) to (w);
  4333. \draw (v) to (w);
  4334. \draw (v) to (rsp);
  4335. \draw (w) to (rsp);
  4336. \draw (x) to (rsp);
  4337. \draw (y) to (rsp);
  4338. \path[-.,bend left=15] (z) edge node {} (rsp);
  4339. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4340. \draw (rax) to (rsp);
  4341. \end{tikzpicture}
  4342. \]
  4343. We repeat the process, selecting a maximally saturated vertex,
  4344. choosing is \code{z}, and color it with the first available number, which
  4345. is $1$. We add $1$ to the saturation for the neighboring vertices
  4346. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4347. \[
  4348. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4349. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4350. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4351. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4352. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4353. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4354. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4355. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4356. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4357. \draw (t1) to (rax);
  4358. \draw (t1) to (z);
  4359. \draw (z) to (y);
  4360. \draw (z) to (w);
  4361. \draw (x) to (w);
  4362. \draw (y) to (w);
  4363. \draw (v) to (w);
  4364. \draw (v) to (rsp);
  4365. \draw (w) to (rsp);
  4366. \draw (x) to (rsp);
  4367. \draw (y) to (rsp);
  4368. \path[-.,bend left=15] (z) edge node {} (rsp);
  4369. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4370. \draw (rax) to (rsp);
  4371. \end{tikzpicture}
  4372. \]
  4373. The most saturated vertices are now \code{w} and \code{y}. We color
  4374. \code{w} with the first available color, which is $0$.
  4375. \[
  4376. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4377. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4378. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4379. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4380. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4381. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4382. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4383. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4384. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4385. \draw (t1) to (rax);
  4386. \draw (t1) to (z);
  4387. \draw (z) to (y);
  4388. \draw (z) to (w);
  4389. \draw (x) to (w);
  4390. \draw (y) to (w);
  4391. \draw (v) to (w);
  4392. \draw (v) to (rsp);
  4393. \draw (w) to (rsp);
  4394. \draw (x) to (rsp);
  4395. \draw (y) to (rsp);
  4396. \path[-.,bend left=15] (z) edge node {} (rsp);
  4397. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4398. \draw (rax) to (rsp);
  4399. \end{tikzpicture}
  4400. \]
  4401. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4402. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4403. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4404. and \code{z}, whose colors are $0$ and $1$ respectively.
  4405. \[
  4406. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4407. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4408. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4409. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4410. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4411. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4412. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4413. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4414. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4415. \draw (t1) to (rax);
  4416. \draw (t1) to (z);
  4417. \draw (z) to (y);
  4418. \draw (z) to (w);
  4419. \draw (x) to (w);
  4420. \draw (y) to (w);
  4421. \draw (v) to (w);
  4422. \draw (v) to (rsp);
  4423. \draw (w) to (rsp);
  4424. \draw (x) to (rsp);
  4425. \draw (y) to (rsp);
  4426. \path[-.,bend left=15] (z) edge node {} (rsp);
  4427. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4428. \draw (rax) to (rsp);
  4429. \end{tikzpicture}
  4430. \]
  4431. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4432. \[
  4433. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4434. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4435. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4436. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4437. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4438. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4439. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4440. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4441. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4442. \draw (t1) to (rax);
  4443. \draw (t1) to (z);
  4444. \draw (z) to (y);
  4445. \draw (z) to (w);
  4446. \draw (x) to (w);
  4447. \draw (y) to (w);
  4448. \draw (v) to (w);
  4449. \draw (v) to (rsp);
  4450. \draw (w) to (rsp);
  4451. \draw (x) to (rsp);
  4452. \draw (y) to (rsp);
  4453. \path[-.,bend left=15] (z) edge node {} (rsp);
  4454. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4455. \draw (rax) to (rsp);
  4456. \end{tikzpicture}
  4457. \]
  4458. In the last step of the algorithm, we color \code{x} with $1$.
  4459. \[
  4460. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4461. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4462. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4463. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4464. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4465. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4466. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4467. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4468. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4469. \draw (t1) to (rax);
  4470. \draw (t1) to (z);
  4471. \draw (z) to (y);
  4472. \draw (z) to (w);
  4473. \draw (x) to (w);
  4474. \draw (y) to (w);
  4475. \draw (v) to (w);
  4476. \draw (v) to (rsp);
  4477. \draw (w) to (rsp);
  4478. \draw (x) to (rsp);
  4479. \draw (y) to (rsp);
  4480. \path[-.,bend left=15] (z) edge node {} (rsp);
  4481. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4482. \draw (rax) to (rsp);
  4483. \end{tikzpicture}
  4484. \]
  4485. So we obtain the following coloring:
  4486. \[
  4487. \{
  4488. \ttm{rax} \mapsto -1,
  4489. \ttm{rsp} \mapsto -2,
  4490. \ttm{t} \mapsto 0,
  4491. \ttm{z} \mapsto 1,
  4492. \ttm{x} \mapsto 1,
  4493. \ttm{y} \mapsto 2,
  4494. \ttm{w} \mapsto 0,
  4495. \ttm{v} \mapsto 1
  4496. \}
  4497. \]
  4498. \fi}
  4499. %
  4500. {\if\edition\pythonEd
  4501. %
  4502. With the DSATUR algorithm in hand, let us return to the running
  4503. example and consider how to color the interference graph in
  4504. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4505. to indicate that it has not yet been assigned a color. The saturation
  4506. sets are also shown for each node; all of them start as the empty set.
  4507. (We do not include the register nodes in the graph below because there
  4508. were no interference edges involving registers in this program, but in
  4509. general there can be.)
  4510. %
  4511. \[
  4512. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4513. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4514. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4515. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4516. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4517. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4518. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4519. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4520. \draw (t0) to (t1);
  4521. \draw (t0) to (z);
  4522. \draw (z) to (y);
  4523. \draw (z) to (w);
  4524. \draw (x) to (w);
  4525. \draw (y) to (w);
  4526. \draw (v) to (w);
  4527. \end{tikzpicture}
  4528. \]
  4529. The algorithm says to select a maximally saturated vertex. So we pick
  4530. $\ttm{tmp\_0}$ and color it with the first available integer, which is
  4531. $0$. We mark $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$
  4532. because they interfere with $\ttm{tmp\_0}$.
  4533. \[
  4534. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4535. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4536. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4537. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4538. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4539. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4540. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4541. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4542. \draw (t0) to (t1);
  4543. \draw (t0) to (z);
  4544. \draw (z) to (y);
  4545. \draw (z) to (w);
  4546. \draw (x) to (w);
  4547. \draw (y) to (w);
  4548. \draw (v) to (w);
  4549. \end{tikzpicture}
  4550. \]
  4551. We repeat the process, selecting a maximally saturated vertex,
  4552. choosing \code{z}, and color it with the first available number, which
  4553. is $1$. We add $1$ to the saturation for the neighboring vertices
  4554. \code{tmp\_0}, \code{y}, and \code{w}.
  4555. \[
  4556. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4557. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4558. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4559. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4560. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4561. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4562. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4563. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4564. \draw (t0) to (t1);
  4565. \draw (t0) to (z);
  4566. \draw (z) to (y);
  4567. \draw (z) to (w);
  4568. \draw (x) to (w);
  4569. \draw (y) to (w);
  4570. \draw (v) to (w);
  4571. \end{tikzpicture}
  4572. \]
  4573. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4574. \code{y}. We color \code{w} with the first available color, which
  4575. is $0$.
  4576. \[
  4577. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4578. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4579. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4580. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4581. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4582. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4583. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4584. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4585. \draw (t0) to (t1);
  4586. \draw (t0) to (z);
  4587. \draw (z) to (y);
  4588. \draw (z) to (w);
  4589. \draw (x) to (w);
  4590. \draw (y) to (w);
  4591. \draw (v) to (w);
  4592. \end{tikzpicture}
  4593. \]
  4594. Now \code{y} is the most saturated, so we color it with $2$.
  4595. \[
  4596. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4597. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4598. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4599. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4600. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4601. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4602. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4603. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4604. \draw (t0) to (t1);
  4605. \draw (t0) to (z);
  4606. \draw (z) to (y);
  4607. \draw (z) to (w);
  4608. \draw (x) to (w);
  4609. \draw (y) to (w);
  4610. \draw (v) to (w);
  4611. \end{tikzpicture}
  4612. \]
  4613. Now \code{tmp\_1}, \code{x}, and \code{v} are equally saturated.
  4614. We choose to color \code{v} with $1$.
  4615. \[
  4616. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4617. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4618. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4619. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4620. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4621. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4622. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4623. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4624. \draw (t0) to (t1);
  4625. \draw (t0) to (z);
  4626. \draw (z) to (y);
  4627. \draw (z) to (w);
  4628. \draw (x) to (w);
  4629. \draw (y) to (w);
  4630. \draw (v) to (w);
  4631. \end{tikzpicture}
  4632. \]
  4633. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4634. \[
  4635. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4636. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4637. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4638. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4639. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4640. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4641. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4642. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4643. \draw (t0) to (t1);
  4644. \draw (t0) to (z);
  4645. \draw (z) to (y);
  4646. \draw (z) to (w);
  4647. \draw (x) to (w);
  4648. \draw (y) to (w);
  4649. \draw (v) to (w);
  4650. \end{tikzpicture}
  4651. \]
  4652. So we obtain the following coloring:
  4653. \[
  4654. \{ \ttm{tmp\_0} \mapsto 0,
  4655. \ttm{tmp\_1} \mapsto 1,
  4656. \ttm{z} \mapsto 1,
  4657. \ttm{x} \mapsto 1,
  4658. \ttm{y} \mapsto 2,
  4659. \ttm{w} \mapsto 0,
  4660. \ttm{v} \mapsto 1 \}
  4661. \]
  4662. \fi}
  4663. We recommend creating an auxiliary function named \code{color\_graph}
  4664. that takes an interference graph and a list of all the variables in
  4665. the program. This function should return a mapping of variables to
  4666. their colors (represented as natural numbers). By creating this helper
  4667. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4668. when we add support for functions.
  4669. To prioritize the processing of highly saturated nodes inside the
  4670. \code{color\_graph} function, we recommend using the priority queue
  4671. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4672. addition, you will need to maintain a mapping from variables to their
  4673. ``handles'' in the priority queue so that you can notify the priority
  4674. queue when their saturation changes.}
  4675. {\if\edition\racketEd\color{olive}
  4676. \begin{figure}[tp]
  4677. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4678. \small
  4679. \begin{tcolorbox}[title=Priority Queue]
  4680. A \emph{priority queue} is a collection of items in which the
  4681. removal of items is governed by priority. In a ``min'' queue,
  4682. lower priority items are removed first. An implementation is in
  4683. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4684. queue} \index{subject}{minimum priority queue}
  4685. \begin{description}
  4686. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4687. priority queue that uses the $\itm{cmp}$ predicate to determine
  4688. whether its first argument has lower or equal priority to its
  4689. second argument.
  4690. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4691. items in the queue.
  4692. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4693. the item into the queue and returns a handle for the item in the
  4694. queue.
  4695. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4696. the lowest priority.
  4697. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4698. notifies the queue that the priority has decreased for the item
  4699. associated with the given handle.
  4700. \end{description}
  4701. \end{tcolorbox}
  4702. %\end{wrapfigure}
  4703. \caption{The priority queue data structure.}
  4704. \label{fig:priority-queue}
  4705. \end{figure}
  4706. \fi}
  4707. With the coloring complete, we finalize the assignment of variables to
  4708. registers and stack locations. We map the first $k$ colors to the $k$
  4709. registers and the rest of the colors to stack locations. Suppose for
  4710. the moment that we have just one register to use for register
  4711. allocation, \key{rcx}. Then we have the following map from colors to
  4712. locations.
  4713. \[
  4714. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4715. \]
  4716. Composing this mapping with the coloring, we arrive at the following
  4717. assignment of variables to locations.
  4718. {\if\edition\racketEd\color{olive}
  4719. \begin{gather*}
  4720. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4721. \ttm{w} \mapsto \key{\%rcx}, \,
  4722. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4723. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4724. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4725. \ttm{t} \mapsto \key{\%rcx} \}
  4726. \end{gather*}
  4727. \fi}
  4728. {\if\edition\pythonEd
  4729. \begin{gather*}
  4730. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4731. \ttm{w} \mapsto \key{\%rcx}, \,
  4732. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4733. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4734. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4735. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4736. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4737. \end{gather*}
  4738. \fi}
  4739. Adapt the code from the \code{assign\_homes} pass
  4740. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4741. assigned location. Applying the above assignment to our running
  4742. example, on the left, yields the program on the right.
  4743. % why frame size of 32? -JGS
  4744. \begin{center}
  4745. {\if\edition\racketEd\color{olive}
  4746. \begin{minipage}{0.3\textwidth}
  4747. \begin{lstlisting}
  4748. movq $1, v
  4749. movq $42, w
  4750. movq v, x
  4751. addq $7, x
  4752. movq x, y
  4753. movq x, z
  4754. addq w, z
  4755. movq y, t
  4756. negq t
  4757. movq z, %rax
  4758. addq t, %rax
  4759. jmp conclusion
  4760. \end{lstlisting}
  4761. \end{minipage}
  4762. $\Rightarrow\qquad$
  4763. \begin{minipage}{0.45\textwidth}
  4764. \begin{lstlisting}
  4765. movq $1, -8(%rbp)
  4766. movq $42, %rcx
  4767. movq -8(%rbp), -8(%rbp)
  4768. addq $7, -8(%rbp)
  4769. movq -8(%rbp), -16(%rbp)
  4770. movq -8(%rbp), -8(%rbp)
  4771. addq %rcx, -8(%rbp)
  4772. movq -16(%rbp), %rcx
  4773. negq %rcx
  4774. movq -8(%rbp), %rax
  4775. addq %rcx, %rax
  4776. jmp conclusion
  4777. \end{lstlisting}
  4778. \end{minipage}
  4779. \fi}
  4780. {\if\edition\pythonEd
  4781. \begin{minipage}{0.3\textwidth}
  4782. \begin{lstlisting}
  4783. movq $1, v
  4784. movq $42, w
  4785. movq v, x
  4786. addq $7, x
  4787. movq x, y
  4788. movq x, z
  4789. addq w, z
  4790. movq y, tmp_0
  4791. negq tmp_0
  4792. movq z, tmp_1
  4793. addq tmp_0, tmp_1
  4794. movq tmp_1, %rdi
  4795. callq print_int
  4796. \end{lstlisting}
  4797. \end{minipage}
  4798. $\Rightarrow\qquad$
  4799. \begin{minipage}{0.45\textwidth}
  4800. \begin{lstlisting}
  4801. movq $1, -8(%rbp)
  4802. movq $42, %rcx
  4803. movq -8(%rbp), -8(%rbp)
  4804. addq $7, -8(%rbp)
  4805. movq -8(%rbp), -16(%rbp)
  4806. movq -8(%rbp), -8(%rbp)
  4807. addq %rcx, -8(%rbp)
  4808. movq -16(%rbp), %rcx
  4809. negq %rcx
  4810. movq -8(%rbp), -8(%rbp)
  4811. addq %rcx, -8(%rbp)
  4812. movq -8(%rbp), %rdi
  4813. callq print_int
  4814. \end{lstlisting}
  4815. \end{minipage}
  4816. \fi}
  4817. \end{center}
  4818. \begin{exercise}\normalfont
  4819. %
  4820. Implement the compiler pass \code{allocate\_registers}.
  4821. %
  4822. Create five programs that exercise all of the register allocation
  4823. algorithm, including spilling variables to the stack.
  4824. %
  4825. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4826. \code{run-tests.rkt} script with the three new passes:
  4827. \code{uncover\_live}, \code{build\_interference}, and
  4828. \code{allocate\_registers}.
  4829. %
  4830. Temporarily remove the \code{print\_x86} pass from the list of passes
  4831. and the call to \code{compiler-tests}.
  4832. Run the script to test the register allocator.
  4833. }
  4834. %
  4835. \python{Run the \code{run-tests.py} script to to check whether the
  4836. output programs produce the same result as the input programs.}
  4837. \end{exercise}
  4838. \section{Patch Instructions}
  4839. \label{sec:patch-instructions}
  4840. The remaining step in the compilation to x86 is to ensure that the
  4841. instructions have at most one argument that is a memory access.
  4842. %
  4843. In the running example, the instruction \code{movq -8(\%rbp),
  4844. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4845. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4846. then move \code{rax} into \code{-16(\%rbp)}.
  4847. %
  4848. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4849. problematic, but it can simply be deleted. In general, we recommend
  4850. deleting all the trivial moves whose source and destination are the
  4851. same location.
  4852. %
  4853. The following is the output of \code{patch\_instructions} on the
  4854. running example.
  4855. \begin{center}
  4856. {\if\edition\racketEd\color{olive}
  4857. \begin{minipage}{0.4\textwidth}
  4858. \begin{lstlisting}
  4859. movq $1, -8(%rbp)
  4860. movq $42, %rcx
  4861. movq -8(%rbp), -8(%rbp)
  4862. addq $7, -8(%rbp)
  4863. movq -8(%rbp), -16(%rbp)
  4864. movq -8(%rbp), -8(%rbp)
  4865. addq %rcx, -8(%rbp)
  4866. movq -16(%rbp), %rcx
  4867. negq %rcx
  4868. movq -8(%rbp), %rax
  4869. addq %rcx, %rax
  4870. jmp conclusion
  4871. \end{lstlisting}
  4872. \end{minipage}
  4873. $\Rightarrow\qquad$
  4874. \begin{minipage}{0.45\textwidth}
  4875. \begin{lstlisting}
  4876. movq $1, -8(%rbp)
  4877. movq $42, %rcx
  4878. addq $7, -8(%rbp)
  4879. movq -8(%rbp), %rax
  4880. movq %rax, -16(%rbp)
  4881. addq %rcx, -8(%rbp)
  4882. movq -16(%rbp), %rcx
  4883. negq %rcx
  4884. movq -8(%rbp), %rax
  4885. addq %rcx, %rax
  4886. jmp conclusion
  4887. \end{lstlisting}
  4888. \end{minipage}
  4889. \fi}
  4890. {\if\edition\pythonEd
  4891. \begin{minipage}{0.4\textwidth}
  4892. \begin{lstlisting}
  4893. movq $1, -8(%rbp)
  4894. movq $42, %rcx
  4895. movq -8(%rbp), -8(%rbp)
  4896. addq $7, -8(%rbp)
  4897. movq -8(%rbp), -16(%rbp)
  4898. movq -8(%rbp), -8(%rbp)
  4899. addq %rcx, -8(%rbp)
  4900. movq -16(%rbp), %rcx
  4901. negq %rcx
  4902. movq -8(%rbp), -8(%rbp)
  4903. addq %rcx, -8(%rbp)
  4904. movq -8(%rbp), %rdi
  4905. callq print_int
  4906. \end{lstlisting}
  4907. \end{minipage}
  4908. $\Rightarrow\qquad$
  4909. \begin{minipage}{0.45\textwidth}
  4910. \begin{lstlisting}
  4911. movq $1, -8(%rbp)
  4912. movq $42, %rcx
  4913. addq $7, -8(%rbp)
  4914. movq -8(%rbp), %rax
  4915. movq %rax, -16(%rbp)
  4916. addq %rcx, -8(%rbp)
  4917. movq -16(%rbp), %rcx
  4918. negq %rcx
  4919. addq %rcx, -8(%rbp)
  4920. movq -8(%rbp), %rdi
  4921. callq print_int
  4922. \end{lstlisting}
  4923. \end{minipage}
  4924. \fi}
  4925. \end{center}
  4926. \begin{exercise}\normalfont
  4927. %
  4928. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  4929. %
  4930. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  4931. %in the \code{run-tests.rkt} script.
  4932. %
  4933. Run the script to test the \code{patch\_instructions} pass.
  4934. \end{exercise}
  4935. \section{Print x86}
  4936. \label{sec:print-x86-reg-alloc}
  4937. \index{subject}{calling conventions}
  4938. \index{subject}{prelude}\index{subject}{conclusion}
  4939. Recall that the \code{print\_x86} pass generates the prelude and
  4940. conclusion instructions to satisfy the x86 calling conventions
  4941. (Section~\ref{sec:calling-conventions}). With the addition of the
  4942. register allocator, the callee-saved registers used by the register
  4943. allocator must be saved in the prelude and restored in the conclusion.
  4944. In the \code{allocate\_registers} pass,
  4945. %
  4946. \racket{add an entry to the \itm{info}
  4947. of \code{X86Program} named \code{used\_callee}}
  4948. %
  4949. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  4950. %
  4951. that stores the set of
  4952. callee-saved registers that were assigned to variables. The
  4953. \code{print\_x86} pass can then access this information to decide which
  4954. callee-saved registers need to be saved and restored.
  4955. %
  4956. When calculating the size of the frame to adjust the \code{rsp} in the
  4957. prelude, make sure to take into account the space used for saving the
  4958. callee-saved registers. Also, don't forget that the frame needs to be
  4959. a multiple of 16 bytes!
  4960. An overview of all of the passes involved in register allocation is
  4961. shown in Figure~\ref{fig:reg-alloc-passes}.
  4962. \begin{figure}[tbp]
  4963. {\if\edition\racketEd\color{olive}
  4964. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4965. \node (Rvar) at (0,2) {\large \LangVar{}};
  4966. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4967. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4968. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4969. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4970. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4971. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4972. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4973. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4974. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4975. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4976. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  4977. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  4978. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  4979. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  4980. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  4981. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  4982. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  4983. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  4984. \end{tikzpicture}
  4985. \fi}
  4986. {\if\edition\pythonEd
  4987. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4988. \node (Rvar-1) at (0,2) {\large \LangVar{}};
  4989. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4990. \node (x86-1) at (3,0) {\large \LangXVar{}};
  4991. \node (x86-2) at (6,0) {\large \LangXVar{}};
  4992. \node (x86-3) at (9,0) {\large \LangXInt{}};
  4993. \node (x86-4) at (11,0) {\large \LangXInt{}};
  4994. \path[->,bend left=15] (Rvar-1) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  4995. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  4996. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize allocate\_reg.} (x86-2);
  4997. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  4998. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  4999. \end{tikzpicture}
  5000. \fi}
  5001. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5002. \label{fig:reg-alloc-passes}
  5003. \end{figure}
  5004. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5005. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5006. use of registers and the stack, we have limited the register allocator
  5007. to use just two registers: \code{rbx} and \code{rcx}. In the
  5008. prelude\index{subject}{prelude} of the \code{main} function, we push
  5009. \code{rbx} onto the stack because it is a callee-saved register and it
  5010. was assigned to variable by the register allocator. We subtract
  5011. \code{8} from the \code{rsp} at the end of the prelude to reserve
  5012. space for the one spilled variable. After that subtraction, the
  5013. \code{rsp} is aligned to 16 bytes.
  5014. Moving on to the program proper, we see how the registers were
  5015. allocated.
  5016. %
  5017. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5018. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5019. %
  5020. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5021. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5022. were assigned to \code{rbx}.}
  5023. %
  5024. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5025. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5026. callee-save register \code{rbx} onto the stack. The spilled variables
  5027. must be placed lower on the stack than the saved callee-save
  5028. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5029. \code{-16(\%rbp)}.
  5030. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5031. done in the prelude. We move the stack pointer up by \code{8} bytes
  5032. (the room for spilled variables), then we pop the old values of
  5033. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5034. \code{retq} to return control to the operating system.
  5035. \begin{figure}[tbp]
  5036. % var_test_28.rkt
  5037. % (use-minimal-set-of-registers! #t)
  5038. % and only rbx rcx
  5039. % tmp 0 rbx
  5040. % z 1 rcx
  5041. % y 0 rbx
  5042. % w 2 16(%rbp)
  5043. % v 0 rbx
  5044. % x 0 rbx
  5045. {\if\edition\racketEd\color{olive}
  5046. \begin{lstlisting}
  5047. start:
  5048. movq $1, %rbx
  5049. movq $42, -16(%rbp)
  5050. addq $7, %rbx
  5051. movq %rbx, %rcx
  5052. addq -16(%rbp), %rcx
  5053. negq %rbx
  5054. movq %rcx, %rax
  5055. addq %rbx, %rax
  5056. jmp conclusion
  5057. .globl main
  5058. main:
  5059. pushq %rbp
  5060. movq %rsp, %rbp
  5061. pushq %rbx
  5062. subq $8, %rsp
  5063. jmp start
  5064. conclusion:
  5065. addq $8, %rsp
  5066. popq %rbx
  5067. popq %rbp
  5068. retq
  5069. \end{lstlisting}
  5070. \fi}
  5071. {\if\edition\pythonEd
  5072. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5073. \begin{lstlisting}
  5074. .globl main
  5075. main:
  5076. pushq %rbp
  5077. movq %rsp, %rbp
  5078. pushq %rbx
  5079. subq $8, %rsp
  5080. movq $1, %rcx
  5081. movq $42, %rbx
  5082. addq $7, %rcx
  5083. movq %rcx, -16(%rbp)
  5084. addq %rbx, -16(%rbp)
  5085. negq %rcx
  5086. movq -16(%rbp), %rbx
  5087. addq %rcx, %rbx
  5088. movq %rbx, %rdi
  5089. callq print_int
  5090. addq $8, %rsp
  5091. popq %rbx
  5092. popq %rbp
  5093. retq
  5094. \end{lstlisting}
  5095. \fi}
  5096. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  5097. \label{fig:running-example-x86}
  5098. \end{figure}
  5099. \begin{exercise}\normalfont
  5100. Update the \code{print\_x86} pass as described in this section.
  5101. %
  5102. \racket{
  5103. In the \code{run-tests.rkt} script, reinstate \code{print\_x86} in the
  5104. list of passes and the call to \code{compiler-tests}.}
  5105. %
  5106. Run the script to test the complete compiler for \LangVar{} that
  5107. performs register allocation.
  5108. \end{exercise}
  5109. \section{Challenge: Move Biasing}
  5110. \label{sec:move-biasing}
  5111. \index{subject}{move biasing}
  5112. This section describes an enhancement to the register allocator for
  5113. students looking for an extra challenge or who have a deeper interest
  5114. in register allocation.
  5115. {\if\edition\racketEd\color{olive}
  5116. To motivate the need for move biasing we return to the running example
  5117. but this time use all of the general purpose registers. So we have
  5118. the following mapping of color numbers to registers.
  5119. \[
  5120. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5121. \]
  5122. Using the same assignment of variables to color numbers that was
  5123. produced by the register allocator described in the last section, we
  5124. get the following program.
  5125. \begin{center}
  5126. \begin{minipage}{0.3\textwidth}
  5127. \begin{lstlisting}
  5128. movq $1, v
  5129. movq $42, w
  5130. movq v, x
  5131. addq $7, x
  5132. movq x, y
  5133. movq x, z
  5134. addq w, z
  5135. movq y, t
  5136. negq t
  5137. movq z, %rax
  5138. addq t, %rax
  5139. jmp conclusion
  5140. \end{lstlisting}
  5141. \end{minipage}
  5142. $\Rightarrow\qquad$
  5143. \begin{minipage}{0.45\textwidth}
  5144. \begin{lstlisting}
  5145. movq $1, %rdx
  5146. movq $42, %rcx
  5147. movq %rdx, %rdx
  5148. addq $7, %rdx
  5149. movq %rdx, %rsi
  5150. movq %rdx, %rdx
  5151. addq %rcx, %rdx
  5152. movq %rsi, %rcx
  5153. negq %rcx
  5154. movq %rdx, %rax
  5155. addq %rcx, %rax
  5156. jmp conclusion
  5157. \end{lstlisting}
  5158. \end{minipage}
  5159. \end{center}
  5160. In the above output code there are two \key{movq} instructions that
  5161. can be removed because their source and target are the same. However,
  5162. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5163. register, we could instead remove three \key{movq} instructions. We
  5164. can accomplish this by taking into account which variables appear in
  5165. \key{movq} instructions with which other variables.
  5166. \fi}
  5167. {\if\edition\pythonEd
  5168. %
  5169. To motivate the need for move biasing we return to the running example
  5170. and recall that Section~\ref{sec:patch-instructions} we were able to
  5171. remove three trivial move instructions from the running
  5172. example. However, we could remove another trivial move if we were able
  5173. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5174. We say that two variables $p$ and $q$ are \emph{move
  5175. related}\index{subject}{move related} if they participate together in a
  5176. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5177. \key{movq} $q$\key{,} $p$. When deciding which variable to
  5178. color next, when there are multiple variables with the same
  5179. saturation, prefer variables that can be assigned the same
  5180. color as a move related variable that has already been colored.
  5181. Furthermore, when the register allocator chooses a color
  5182. for a variable, it should prefer a color that has already been used
  5183. for a move-related variable (assuming that they do not interfere). Of
  5184. course, this preference should not override the preference for
  5185. registers over stack locations. This preference should be used as a
  5186. tie breaker when choosing between registers or when choosing between
  5187. stack locations.
  5188. We recommend representing the move relationships in a graph, similar
  5189. to how we represented interference. The following is the \emph{move
  5190. graph} for our running example.
  5191. {\if\edition\racketEd\color{olive}
  5192. \[
  5193. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5194. \node (rax) at (0,0) {$\ttm{rax}$};
  5195. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5196. \node (t) at (0,2) {$\ttm{t}$};
  5197. \node (z) at (3,2) {$\ttm{z}$};
  5198. \node (x) at (6,2) {$\ttm{x}$};
  5199. \node (y) at (3,0) {$\ttm{y}$};
  5200. \node (w) at (6,0) {$\ttm{w}$};
  5201. \node (v) at (9,0) {$\ttm{v}$};
  5202. \draw (v) to (x);
  5203. \draw (x) to (y);
  5204. \draw (x) to (z);
  5205. \draw (y) to (t);
  5206. \end{tikzpicture}
  5207. \]
  5208. \fi}
  5209. %
  5210. {\if\edition\pythonEd
  5211. \[
  5212. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5213. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5214. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5215. \node (z) at (3,2) {$\ttm{z}$};
  5216. \node (x) at (6,2) {$\ttm{x}$};
  5217. \node (y) at (3,0) {$\ttm{y}$};
  5218. \node (w) at (6,0) {$\ttm{w}$};
  5219. \node (v) at (9,0) {$\ttm{v}$};
  5220. \draw (y) to (t0);
  5221. \draw (z) to (x);
  5222. \draw (z) to (t1);
  5223. \draw (x) to (y);
  5224. \draw (x) to (v);
  5225. \end{tikzpicture}
  5226. \]
  5227. \fi}
  5228. {\if\edition\racketEd\color{olive}
  5229. Now we replay the graph coloring, pausing to see the coloring of
  5230. \code{y}. Recall the following configuration. The most saturated vertices
  5231. were \code{w} and \code{y}.
  5232. \[
  5233. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5234. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5235. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5236. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5237. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5238. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5239. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5240. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5241. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5242. \draw (t1) to (rax);
  5243. \draw (t1) to (z);
  5244. \draw (z) to (y);
  5245. \draw (z) to (w);
  5246. \draw (x) to (w);
  5247. \draw (y) to (w);
  5248. \draw (v) to (w);
  5249. \draw (v) to (rsp);
  5250. \draw (w) to (rsp);
  5251. \draw (x) to (rsp);
  5252. \draw (y) to (rsp);
  5253. \path[-.,bend left=15] (z) edge node {} (rsp);
  5254. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5255. \draw (rax) to (rsp);
  5256. \end{tikzpicture}
  5257. \]
  5258. %
  5259. Last time we chose to color \code{w} with $0$. But this time we see
  5260. that \code{w} is not move related to any vertex, but \code{y} is move
  5261. related to \code{t}. So we choose to color \code{y} the same color as
  5262. \code{t}, $0$.
  5263. \[
  5264. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5265. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5266. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5267. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5268. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5269. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5270. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5271. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5272. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5273. \draw (t1) to (rax);
  5274. \draw (t1) to (z);
  5275. \draw (z) to (y);
  5276. \draw (z) to (w);
  5277. \draw (x) to (w);
  5278. \draw (y) to (w);
  5279. \draw (v) to (w);
  5280. \draw (v) to (rsp);
  5281. \draw (w) to (rsp);
  5282. \draw (x) to (rsp);
  5283. \draw (y) to (rsp);
  5284. \path[-.,bend left=15] (z) edge node {} (rsp);
  5285. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5286. \draw (rax) to (rsp);
  5287. \end{tikzpicture}
  5288. \]
  5289. Now \code{w} is the most saturated, so we color it $2$.
  5290. \[
  5291. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5292. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5293. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5294. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5295. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5296. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5297. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5298. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5299. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5300. \draw (t1) to (rax);
  5301. \draw (t1) to (z);
  5302. \draw (z) to (y);
  5303. \draw (z) to (w);
  5304. \draw (x) to (w);
  5305. \draw (y) to (w);
  5306. \draw (v) to (w);
  5307. \draw (v) to (rsp);
  5308. \draw (w) to (rsp);
  5309. \draw (x) to (rsp);
  5310. \draw (y) to (rsp);
  5311. \path[-.,bend left=15] (z) edge node {} (rsp);
  5312. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5313. \draw (rax) to (rsp);
  5314. \end{tikzpicture}
  5315. \]
  5316. At this point, vertices \code{x} and \code{v} are most saturated, but
  5317. \code{x} is move related to \code{y} and \code{z}, so we color
  5318. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5319. \[
  5320. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5321. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5322. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5323. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5324. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5325. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5326. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5327. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5328. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5329. \draw (t1) to (rax);
  5330. \draw (t) to (z);
  5331. \draw (z) to (y);
  5332. \draw (z) to (w);
  5333. \draw (x) to (w);
  5334. \draw (y) to (w);
  5335. \draw (v) to (w);
  5336. \draw (v) to (rsp);
  5337. \draw (w) to (rsp);
  5338. \draw (x) to (rsp);
  5339. \draw (y) to (rsp);
  5340. \path[-.,bend left=15] (z) edge node {} (rsp);
  5341. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5342. \draw (rax) to (rsp);
  5343. \end{tikzpicture}
  5344. \]
  5345. \fi}
  5346. %
  5347. {\if\edition\pythonEd
  5348. Now we replay the graph coloring, pausing before the coloring of
  5349. \code{w}. Recall the following configuration. The most saturated vertices
  5350. were \code{tmp\_1}, \code{w}, and \code{y}.
  5351. \[
  5352. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5353. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5354. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5355. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5356. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5357. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5358. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5359. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5360. \draw (t0) to (t1);
  5361. \draw (t0) to (z);
  5362. \draw (z) to (y);
  5363. \draw (z) to (w);
  5364. \draw (x) to (w);
  5365. \draw (y) to (w);
  5366. \draw (v) to (w);
  5367. \end{tikzpicture}
  5368. \]
  5369. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5370. or \code{y}, but note that \code{w} is not move related to any
  5371. variables, wheras \code{y} and \code{tmp\_1} are move related to
  5372. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5373. \code{y} and color it $0$, we can delete another move instruction.
  5374. \[
  5375. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5376. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5377. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5378. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5379. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5380. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5381. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5382. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5383. \draw (t0) to (t1);
  5384. \draw (t0) to (z);
  5385. \draw (z) to (y);
  5386. \draw (z) to (w);
  5387. \draw (x) to (w);
  5388. \draw (y) to (w);
  5389. \draw (v) to (w);
  5390. \end{tikzpicture}
  5391. \]
  5392. Now \code{w} is the most saturated, so we color it $2$.
  5393. \[
  5394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5395. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5396. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5397. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5398. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5399. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5400. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5401. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5402. \draw (t0) to (t1);
  5403. \draw (t0) to (z);
  5404. \draw (z) to (y);
  5405. \draw (z) to (w);
  5406. \draw (x) to (w);
  5407. \draw (y) to (w);
  5408. \draw (v) to (w);
  5409. \end{tikzpicture}
  5410. \]
  5411. To finish the coloring, \code{x} and \code{v} get $0$ and
  5412. \code{tmp\_1} gets $1$.
  5413. \[
  5414. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5415. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5416. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5417. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5418. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5419. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5420. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5421. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5422. \draw (t0) to (t1);
  5423. \draw (t0) to (z);
  5424. \draw (z) to (y);
  5425. \draw (z) to (w);
  5426. \draw (x) to (w);
  5427. \draw (y) to (w);
  5428. \draw (v) to (w);
  5429. \end{tikzpicture}
  5430. \]
  5431. \fi}
  5432. So we have the following assignment of variables to registers.
  5433. {\if\edition\racketEd\color{olive}
  5434. \begin{gather*}
  5435. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5436. \ttm{w} \mapsto \key{\%rsi}, \,
  5437. \ttm{x} \mapsto \key{\%rcx}, \,
  5438. \ttm{y} \mapsto \key{\%rcx}, \,
  5439. \ttm{z} \mapsto \key{\%rdx}, \,
  5440. \ttm{t} \mapsto \key{\%rcx} \}
  5441. \end{gather*}
  5442. \fi}
  5443. {\if\edition\pythonEd
  5444. \begin{gather*}
  5445. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5446. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5447. \ttm{x} \mapsto \key{\%rcx}, \,
  5448. \ttm{y} \mapsto \key{\%rcx}, \\
  5449. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5450. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5451. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5452. \end{gather*}
  5453. \fi}
  5454. We apply this register assignment to the running example, on the left,
  5455. to obtain the code in the middle. The \code{patch\_instructions} then
  5456. deletes the trivial moves to obtain the code on the right.
  5457. {\if\edition\racketEd\color{olive}
  5458. \begin{minipage}{0.25\textwidth}
  5459. \begin{lstlisting}
  5460. movq $1, v
  5461. movq $42, w
  5462. movq v, x
  5463. addq $7, x
  5464. movq x, y
  5465. movq x, z
  5466. addq w, z
  5467. movq y, t
  5468. negq t
  5469. movq z, %rax
  5470. addq t, %rax
  5471. jmp conclusion
  5472. \end{lstlisting}
  5473. \end{minipage}
  5474. $\Rightarrow\qquad$
  5475. \begin{minipage}{0.25\textwidth}
  5476. \begin{lstlisting}
  5477. movq $1, %rcx
  5478. movq $42, %rsi
  5479. movq %rcx, %rcx
  5480. addq $7, %rcx
  5481. movq %rcx, %rcx
  5482. movq %rcx, %rdx
  5483. addq %rsi, %rdx
  5484. movq %rcx, %rcx
  5485. negq %rcx
  5486. movq %rdx, %rax
  5487. addq %rcx, %rax
  5488. jmp conclusion
  5489. \end{lstlisting}
  5490. \end{minipage}
  5491. $\Rightarrow\qquad$
  5492. \begin{minipage}{0.25\textwidth}
  5493. \begin{lstlisting}
  5494. movq $1, %rcx
  5495. movq $42, %rsi
  5496. addq $7, %rcx
  5497. movq %rcx, %rdx
  5498. addq %rsi, %rdx
  5499. negq %rcx
  5500. movq %rdx, %rax
  5501. addq %rcx, %rax
  5502. jmp conclusion
  5503. \end{lstlisting}
  5504. \end{minipage}
  5505. \fi}
  5506. {\if\edition\pythonEd
  5507. \begin{minipage}{0.25\textwidth}
  5508. \begin{lstlisting}
  5509. movq $1, v
  5510. movq $42, w
  5511. movq v, x
  5512. addq $7, x
  5513. movq x, y
  5514. movq x, z
  5515. addq w, z
  5516. movq y, tmp_0
  5517. negq tmp_0
  5518. movq z, tmp_1
  5519. addq tmp_0, tmp_1
  5520. movq tmp_1, %rdi
  5521. callq _print_int\end{lstlisting}
  5522. \end{minipage}
  5523. $\Rightarrow\qquad$
  5524. \begin{minipage}{0.25\textwidth}
  5525. \begin{lstlisting}
  5526. movq $1, %rcx
  5527. movq $42, -16(%rbp)
  5528. movq %rcx, %rcx
  5529. addq $7, %rcx
  5530. movq %rcx, %rcx
  5531. movq %rcx, -8(%rbp)
  5532. addq -16(%rbp), -8(%rbp)
  5533. movq %rcx, %rcx
  5534. negq %rcx
  5535. movq -8(%rbp), -8(%rbp)
  5536. addq %rcx, -8(%rbp)
  5537. movq -8(%rbp), %rdi
  5538. callq _print_int
  5539. \end{lstlisting}
  5540. \end{minipage}
  5541. $\Rightarrow\qquad$
  5542. \begin{minipage}{0.25\textwidth}
  5543. \begin{lstlisting}
  5544. movq $1, %rcx
  5545. movq $42, -16(%rbp)
  5546. addq $7, %rcx
  5547. movq %rcx, -8(%rbp)
  5548. movq -16(%rbp), %rax
  5549. addq %rax, -8(%rbp)
  5550. negq %rcx
  5551. addq %rcx, -8(%rbp)
  5552. movq -8(%rbp), %rdi
  5553. callq print_int
  5554. \end{lstlisting}
  5555. \end{minipage}
  5556. \fi}
  5557. \begin{exercise}\normalfont
  5558. Change your implementation of \code{allocate\_registers} to take move
  5559. biasing into account. Create two new tests that include at least one
  5560. opportunity for move biasing and visually inspect the output x86
  5561. programs to make sure that your move biasing is working properly. Make
  5562. sure that your compiler still passes all of the tests.
  5563. \end{exercise}
  5564. %To do: another neat challenge would be to do
  5565. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5566. %% \subsection{Output of the Running Example}
  5567. %% \label{sec:reg-alloc-output}
  5568. % challenge: prioritize variables based on execution frequencies
  5569. % and the number of uses of a variable
  5570. % challenge: enhance the coloring algorithm using Chaitin's
  5571. % approach of prioritizing high-degree variables
  5572. % by removing low-degree variables (coloring them later)
  5573. % from the interference graph
  5574. \section{Further Reading}
  5575. \label{sec:register-allocation-further-reading}
  5576. Early register allocation algorithms were developed for Fortran
  5577. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5578. of graph coloring began in the late 1970s and early 1980s with the
  5579. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5580. algorithm is based on the following observation of
  5581. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  5582. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  5583. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  5584. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5585. different colors, but since there are less than $k$ of them, there
  5586. will be one or more colors left over to use for coloring $v$ in $G$.
  5587. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5588. less than $k$ from the graph and recursively colors the rest of the
  5589. graph. Upon returning from the recursion, it colors $v$ with one of
  5590. the available colors and returns. \citet{Chaitin:1982vn} augments
  5591. this algorithm to handle spilling as follows. If there are no vertices
  5592. of degree lower than $k$ then pick a vertex at random, spill it,
  5593. remove it from the graph, and proceed recursively to color the rest of
  5594. the graph.
  5595. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5596. move-related and that don't interfere with each other, a process
  5597. called \emph{coalescing}. While coalescing decreases the number of
  5598. moves, it can make the graph more difficult to
  5599. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5600. which two variables are merged only if they have fewer than $k$
  5601. neighbors of high degree. \citet{George:1996aa} observe that
  5602. conservative coalescing is sometimes too conservative and make it more
  5603. aggressive by iterating the coalescing with the removal of low-degree
  5604. vertices.
  5605. %
  5606. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5607. also propose \emph{biased coloring} in which a variable is assigned to
  5608. the same color as another move-related variable if possible, as
  5609. discussed in Section~\ref{sec:move-biasing}.
  5610. %
  5611. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5612. performs coalescing, graph coloring, and spill code insertion until
  5613. all variables have been assigned a location.
  5614. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5615. spills variables that don't have to be: a high-degree variable can be
  5616. colorable if many of its neighbors are assigned the same color.
  5617. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5618. high-degree vertex is not immediately spilled. Instead the decision is
  5619. deferred until after the recursive call, at which point it is apparent
  5620. whether there is actually an available color or not. We observe that
  5621. this algorithm is equivalent to the smallest-last ordering
  5622. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5623. be registers and the rest to be stack locations.
  5624. %% biased coloring
  5625. Earlier editions of the compiler course at Indiana University
  5626. \citep{Dybvig:2010aa} were based on the algorithm of
  5627. \citet{Briggs:1994kx}.
  5628. The smallest-last ordering algorithm is one of many \emph{greedy}
  5629. coloring algorithms. A greedy coloring algorithm visits all the
  5630. vertices in a particular order and assigns each one the first
  5631. available color. An \emph{offline} greedy algorithm chooses the
  5632. ordering up-front, prior to assigning colors. The algorithm of
  5633. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5634. ordering does not depend on the colors assigned, so the algorithm
  5635. could be split into two phases. Other orderings are possible. For
  5636. example, \citet{Chow:1984ys} order variables according to an estimate
  5637. of runtime cost.
  5638. An \emph{online} greedy coloring algorithm uses information about the
  5639. current assignment of colors to influence the order in which the
  5640. remaining vertices are colored. The saturation-based algorithm
  5641. described in this chapter is one such algorithm. We choose to use
  5642. saturation-based coloring is because it is fun to introduce graph
  5643. coloring via Sudoku.
  5644. A register allocator may choose to map each variable to just one
  5645. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5646. variable to one or more locations. The later can be achieved by
  5647. \emph{live range splitting}, where a variable is replaced by several
  5648. variables that each handle part of its live
  5649. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5650. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5651. %% replacement algorithm, bottom-up local
  5652. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5653. %% Cooper: top-down (priority bassed), bottom-up
  5654. %% top-down
  5655. %% order variables by priority (estimated cost)
  5656. %% caveat: split variables into two groups:
  5657. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5658. %% color the constrained ones first
  5659. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5660. %% cite J. Cocke for an algorithm that colors variables
  5661. %% in a high-degree first ordering
  5662. %Register Allocation via Usage Counts, Freiburghouse CACM
  5663. \citet{Palsberg:2007si} observe that many of the interference graphs
  5664. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5665. that is, every cycle with four or more edges has an edge which is not
  5666. part of the cycle but which connects two vertices on the cycle. Such
  5667. graphs can be optimally colored by the greedy algorithm with a vertex
  5668. ordering determined by maximum cardinality search.
  5669. In situations where compile time is of utmost importance, such as in
  5670. just-in-time compilers, graph coloring algorithms can be too expensive
  5671. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  5672. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5673. \chapter{Booleans and Conditionals}
  5674. \label{ch:Rif}
  5675. \index{subject}{Boolean}
  5676. \index{subject}{control flow}
  5677. \index{subject}{conditional expression}
  5678. The \LangInt{} and \LangVar{} languages only have a single kind of
  5679. value, integers. In this chapter we add a second kind of value, the
  5680. Booleans, to create the \LangIf{} language. The Boolean values
  5681. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5682. respectively in \racket{Racket}\python{Python}.
  5683. The \LangIf{} language includes several
  5684. operations that involve Booleans (\key{and}, \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if} expression \python{and statement}.
  5685. With the addition of \key{if}, programs can have non-trivial control flow which
  5686. \racket{impacts \code{explicate\_control} and liveness analysis}
  5687. \python{impacts liveness analysis and motivates a new pass named
  5688. \code{explicate\_control}}. Also, because
  5689. we now have two kinds of values, we need to handle programs that apply
  5690. an operation to the wrong kind of value, such as
  5691. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5692. There are two language design options for such situations. One option
  5693. is to signal an error and the other is to provide a wider
  5694. interpretation of the operation. \racket{The Racket
  5695. language}\python{Python} uses a mixture of these two options,
  5696. depending on the operation and the kind of value. For example, the
  5697. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5698. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5699. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5700. %
  5701. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5702. in Racket because \code{car} expects a pair.}
  5703. %
  5704. \python{On the other hand, \code{1[0]} results in a run-time error
  5705. in Python because an ``\code{int} object is not subscriptable''.}
  5706. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5707. design choices as \racket{Racket}\python{Python}, except much of the
  5708. error detection happens at compile time instead of run
  5709. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5710. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5711. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5712. Racket}\python{MyPy} reports a compile-time error
  5713. %
  5714. \racket{because Racket expects the type of the argument to be of the form
  5715. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5716. %
  5717. \python{stating that a ``value of type \code{int} is not indexable''.}
  5718. The \LangIf{} language performs type checking during compilation like
  5719. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5720. alternative choice, that is, a dynamically typed language like
  5721. \racket{Racket}\python{Python}.
  5722. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5723. for some operations we are more restrictive, for example, rejecting
  5724. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5725. This chapter is organized as follows. We begin by defining the syntax
  5726. and interpreter for the \LangIf{} language
  5727. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5728. checking and build a type checker for \LangIf{}
  5729. (Section~\ref{sec:type-check-Rif}).
  5730. %
  5731. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5732. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5733. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5734. %
  5735. The remaining sections of this chapter discuss how our compiler passes
  5736. change to accommodate Booleans and conditional control flow. There is
  5737. a new pass, named \code{shrink}, that translates some operators into
  5738. others, thereby reducing the number of operators that need to be
  5739. handled in later passes.
  5740. %
  5741. \racket{The largest changes occur in \code{explicate\_control}, to
  5742. translate \code{if} expressions into control-flow graphs
  5743. (Section~\ref{sec:explicate-control-Rif}).}
  5744. %
  5745. \python{The largest addition is a new pass named
  5746. \code{explicate\_control} that translates \code{if} expressions and
  5747. statements into conditional \code{goto}'s
  5748. (Section~\ref{sec:explicate-control-Rif}).}
  5749. %
  5750. Regarding register allocation, there is the interesting question of
  5751. how to handle conditional \code{goto}'s during liveness analysis.
  5752. \section{The \LangIf{} Language}
  5753. \label{sec:lang-if}
  5754. The concrete syntax of the \LangIf{} language is defined in
  5755. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  5756. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  5757. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5758. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5759. operators to include
  5760. \begin{enumerate}
  5761. \item subtraction on integers,
  5762. \item the logical operators \key{and}, \key{or} and \key{not},
  5763. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5764. for comparing two integers or two Booleans for equality, and
  5765. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5766. comparing integers.
  5767. \end{enumerate}
  5768. \racket{We reorganize the abstract syntax for the primitive
  5769. operations in Figure~\ref{fig:Rif-syntax}, using only one grammar
  5770. rule for all of them. This means that the grammar no longer checks
  5771. whether the arity of an operators matches the number of
  5772. arguments. That responsibility is moved to the type checker for
  5773. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Rif}.}
  5774. \begin{figure}[tp]
  5775. \centering
  5776. \fbox{
  5777. \begin{minipage}{0.96\textwidth}
  5778. {\if\edition\racketEd\color{olive}
  5779. \[
  5780. \begin{array}{lcl}
  5781. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5782. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5783. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5784. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5785. &\MID& \itm{bool}
  5786. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5787. \MID (\key{not}\;\Exp) \\
  5788. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5789. \LangIfM{} &::=& \Exp
  5790. \end{array}
  5791. \]
  5792. \fi}
  5793. {\if\edition\pythonEd
  5794. \[
  5795. \begin{array}{rcl}
  5796. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5797. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  5798. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \itm{uniop}\;\Exp \MID \Exp \; \itm{binop} \; \Exp \MID \Var{} \\
  5799. &\MID& \TRUE \MID \FALSE \MID \Exp\;\key{if}\;\Exp\;\key{else}\;\Exp\\
  5800. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp
  5801. \MID \key{if}\; \Exp \;\key{:}\; \Stmt^{+} \;\key{else:}\; \Stmt^{+}\\
  5802. \LangVarM{} &::=& \Stmt^{*}
  5803. \end{array}
  5804. \]
  5805. \fi}
  5806. \end{minipage}
  5807. }
  5808. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5809. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  5810. \label{fig:Rif-concrete-syntax}
  5811. \end{figure}
  5812. \begin{figure}[tp]
  5813. \centering
  5814. \fbox{
  5815. \begin{minipage}{0.96\textwidth}
  5816. {\if\edition\racketEd\color{olive}
  5817. \[
  5818. \begin{array}{lcl}
  5819. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5820. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5821. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5822. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5823. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5824. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5825. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5826. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5827. \end{array}
  5828. \]
  5829. \fi}
  5830. {\if\edition\pythonEd
  5831. \[
  5832. \begin{array}{lcl}
  5833. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  5834. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  5835. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5836. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5837. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5838. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  5839. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  5840. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  5841. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  5842. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  5843. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5844. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  5845. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  5846. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  5847. \end{array}
  5848. \]
  5849. \fi}
  5850. \end{minipage}
  5851. }
  5852. \caption{The abstract syntax of \LangIf{}.}
  5853. \label{fig:Rif-syntax}
  5854. \end{figure}
  5855. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  5856. which inherits from the interpreter for \LangVar{}
  5857. (Figure~\ref{fig:interp-Rvar}). The literals \TRUE{} and \FALSE{}
  5858. evaluate to the corresponding Boolean values. The conditional
  5859. expression $\CIF{\itm{cnd}}{\itm{thn}}{\itm{els}}$ evaluates \itm{cnd}
  5860. and then either evaluates \itm{thn} or \itm{els} depending on whether
  5861. \itm{cnd} produced \TRUE{} or \FALSE{}. The logical operations
  5862. \code{and}, \code{or}, and \code{not} behave as you might expect, but
  5863. note that the \code{and} an \code{or} operations are
  5864. short-circuiting.
  5865. %
  5866. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  5867. is not evaluated if $e_1$ evaluates to \FALSE{}.
  5868. %
  5869. Similarly, given the expression $\COR{e_1}{e_2}$, the expression $e_2$
  5870. is not evaluated if $e_1$ evaluates to \TRUE{}.
  5871. \racket{With the increase in the number of primitive operations, the
  5872. interpreter would become repetitive without some care. We refactor
  5873. the case for \code{Prim}, moving the code that differs with each
  5874. operation into the \code{interp\_op} method shown in in
  5875. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  5876. separately because of its short-circuiting behavior.}
  5877. \begin{figure}[tbp]
  5878. {\if\edition\racketEd\color{olive}
  5879. \begin{lstlisting}
  5880. (define interp_Rif_class
  5881. (class interp_Rvar_class
  5882. (super-new)
  5883. (define/public (interp_op op) ...)
  5884. (define/override ((interp_exp env) e)
  5885. (define recur (interp_exp env))
  5886. (match e
  5887. [(Bool b) b]
  5888. [(If cnd thn els)
  5889. (match (recur cnd)
  5890. [#t (recur thn)]
  5891. [#f (recur els)])]
  5892. [(Prim 'and (list e1 e2))
  5893. (match (recur e1)
  5894. [#t (match (recur e2) [#t #t] [#f #f])]
  5895. [#f #f])]
  5896. [(Prim op args)
  5897. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  5898. [else ((super interp_exp env) e)]))
  5899. ))
  5900. (define (interp_Rif p)
  5901. (send (new interp_Rif_class) interp_program p))
  5902. \end{lstlisting}
  5903. \fi}
  5904. {\if\edition\pythonEd
  5905. \begin{lstlisting}
  5906. class InterpPif(InterpPvar):
  5907. def interp_exp(self, e, env):
  5908. match e:
  5909. case IfExp(test, body, orelse):
  5910. match self.interp_exp(test, env):
  5911. case True:
  5912. return self.interp_exp(body, env)
  5913. case False:
  5914. return self.interp_exp(orelse, env)
  5915. case BinOp(left, Sub(), right):
  5916. l = self.interp_exp(left, env)
  5917. r = self.interp_exp(right, env)
  5918. return l - r
  5919. case UnaryOp(Not(), v):
  5920. return not self.interp_exp(v, env)
  5921. case BoolOp(And(), values):
  5922. left = values[0]; right = values[1]
  5923. match self.interp_exp(left, env):
  5924. case True:
  5925. return self.interp_exp(right, env)
  5926. case False:
  5927. return False
  5928. case BoolOp(Or(), values):
  5929. left = values[0]; right = values[1]
  5930. match self.interp_exp(left, env):
  5931. case True:
  5932. return True
  5933. case False:
  5934. return self.interp_exp(right, env)
  5935. case Compare(left, [cmp], [right]):
  5936. l = self.interp_exp(left, env)
  5937. r = self.interp_exp(right, env)
  5938. return self.interp_cmp(cmp)(l, r)
  5939. case _:
  5940. return super().interp_exp(e, env)
  5941. def interp_stmts(self, ss, env):
  5942. if len(ss) == 0:
  5943. return
  5944. match ss[0]:
  5945. case If(test, body, orelse):
  5946. match self.interp_exp(test, env):
  5947. case True:
  5948. return self.interp_stmts(body + ss[1:], env)
  5949. case False:
  5950. return self.interp_stmts(orelse + ss[1:], env)
  5951. case _:
  5952. return super().interp_stmts(ss, env)
  5953. ...
  5954. \end{lstlisting}
  5955. \fi}
  5956. \caption{Interpreter for the \LangIf{} language. \racket{(See
  5957. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  5958. \python{(See Figure~\ref{fig:interp-cmp-Rif} for \code{interp\_cmp}.)}}
  5959. \label{fig:interp-Rif}
  5960. \end{figure}
  5961. {\if\edition\racketEd\color{olive}
  5962. \begin{figure}[tbp]
  5963. \begin{lstlisting}
  5964. (define/public (interp_op op)
  5965. (match op
  5966. ['+ fx+]
  5967. ['- fx-]
  5968. ['read read-fixnum]
  5969. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  5970. ['or (lambda (v1 v2)
  5971. (cond [(and (boolean? v1) (boolean? v2))
  5972. (or v1 v2)]))]
  5973. ['eq? (lambda (v1 v2)
  5974. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5975. (and (boolean? v1) (boolean? v2))
  5976. (and (vector? v1) (vector? v2)))
  5977. (eq? v1 v2)]))]
  5978. ['< (lambda (v1 v2)
  5979. (cond [(and (fixnum? v1) (fixnum? v2))
  5980. (< v1 v2)]))]
  5981. ['<= (lambda (v1 v2)
  5982. (cond [(and (fixnum? v1) (fixnum? v2))
  5983. (<= v1 v2)]))]
  5984. ['> (lambda (v1 v2)
  5985. (cond [(and (fixnum? v1) (fixnum? v2))
  5986. (> v1 v2)]))]
  5987. ['>= (lambda (v1 v2)
  5988. (cond [(and (fixnum? v1) (fixnum? v2))
  5989. (>= v1 v2)]))]
  5990. [else (error 'interp_op "unknown operator")]))
  5991. \end{lstlisting}
  5992. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  5993. \label{fig:interp-op-Rif}
  5994. \end{figure}
  5995. \fi}
  5996. {\if\edition\pythonEd
  5997. \begin{figure}
  5998. \begin{lstlisting}
  5999. class InterpPif(InterpPvar):
  6000. ...
  6001. def interp_cmp(self, cmp):
  6002. match cmp:
  6003. case Lt():
  6004. return lambda x, y: x < y
  6005. case LtE():
  6006. return lambda x, y: x <= y
  6007. case Gt():
  6008. return lambda x, y: x > y
  6009. case GtE():
  6010. return lambda x, y: x >= y
  6011. case Eq():
  6012. return lambda x, y: x == y
  6013. case NotEq():
  6014. return lambda x, y: x != y
  6015. \end{lstlisting}
  6016. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6017. \label{fig:interp-cmp-Rif}
  6018. \end{figure}
  6019. \fi}
  6020. \section{Type Checking \LangIf{} Programs}
  6021. \label{sec:type-check-Rif}
  6022. \index{subject}{type checking}
  6023. \index{subject}{semantic analysis}
  6024. It is helpful to think about type checking in two complementary
  6025. ways. A type checker predicts the type of value that will be produced
  6026. by each expression in the program. For \LangIf{}, we have just two types,
  6027. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6028. {\if\edition\racketEd\color{olive}
  6029. \begin{lstlisting}
  6030. (+ 10 (- (+ 12 20)))
  6031. \end{lstlisting}
  6032. \fi}
  6033. {\if\edition\pythonEd
  6034. \begin{lstlisting}
  6035. 10 + -(12 + 20)
  6036. \end{lstlisting}
  6037. \fi}
  6038. \noindent produces a value of type \INTTY{} while
  6039. {\if\edition\racketEd\color{olive}
  6040. \begin{lstlisting}
  6041. (and (not #f) #t)
  6042. \end{lstlisting}
  6043. \fi}
  6044. {\if\edition\pythonEd
  6045. \begin{lstlisting}
  6046. (not False) and True
  6047. \end{lstlisting}
  6048. \fi}
  6049. \noindent produces a value of type \BOOLTY{}.
  6050. Another way to think about type checking is that it enforces a set of
  6051. rules about which operators can be applied to which kinds of
  6052. values. For example, our type checker for \LangIf{} signals an error
  6053. for the below expression
  6054. {\if\edition\racketEd\color{olive}
  6055. \begin{lstlisting}
  6056. (not (+ 10 (- (+ 12 20))))
  6057. \end{lstlisting}
  6058. \fi}
  6059. {\if\edition\pythonEd
  6060. \begin{lstlisting}
  6061. not (10 + -(12 + 20))
  6062. \end{lstlisting}
  6063. \fi}
  6064. The subexpression
  6065. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6066. has type \INTTY{} but the type checker enforces the rule that the argument of
  6067. \code{not} must be an expression of type \BOOLTY{}.
  6068. We implement type checking using classes and methods because they
  6069. provide the open recursion needed to reuse code as we extend the type
  6070. checker in later chapters, analogous to the use of classes and methods
  6071. for the interpreters (Section~\ref{sec:extensible-interp}).
  6072. We separate the type checker for the \LangVar{} fragment into its own
  6073. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  6074. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  6075. from the type checker for \LangVar{}. These type checkers are in the
  6076. files
  6077. \racket{\code{type-check-Rvar.rkt}}\python{\code{type\_check\_Pvar.py}}
  6078. and
  6079. \racket{\code{type-check-Rif.rkt}}\python{\code{type\_check\_Pif.py}}
  6080. of the support code.
  6081. %
  6082. Each type checker is a structurally recursive function over the AST.
  6083. Given an input expression \code{e}, the type checker either signals an
  6084. error or returns an expression and its type (\INTTY{} or
  6085. \BOOLTY{}). It returns an expression because there are situations
  6086. in which we want to change or update the expression.
  6087. Next we discuss the \code{type\_check\_exp} function in
  6088. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  6089. \INTTY{}. To handle variables, the type checker uses the environment
  6090. \code{env} to map variables to types.
  6091. %
  6092. \racket{Consider the case for \key{let}. We type check the
  6093. initializing expression to obtain its type \key{T} and then
  6094. associate type \code{T} with the variable \code{x} in the
  6095. environment used to type check the body of the \key{let}. Thus,
  6096. when the type checker encounters a use of variable \code{x}, it can
  6097. find its type in the environment.}
  6098. %
  6099. \python{Consider the case for assignment. We type check the
  6100. initializing expression to obtain its type \key{t}. If the variable
  6101. \code{lhs.id} is already in the environment because there was a
  6102. prior assignment, we check that this initializer has the same type
  6103. as the prior one. If this is the first assignment to the variable,
  6104. we associate type \code{t} with the variable \code{lhs.id} in the
  6105. environment. Thus, when the type checker encounters a use of
  6106. variable \code{x}, it can find its type in the environment.}
  6107. %
  6108. \racket{Regarding primitive operators, we recursively analyze the
  6109. arguments and then invoke \code{type\_check\_op} to check whether
  6110. the argument types are allowed.}
  6111. %
  6112. \python{Regarding addition and negation, we recursively analyze the
  6113. arguments, check that they have type \INT{}, and return \INT{}.}
  6114. \racket{Several auxiliary methods are used in the type checker. The
  6115. method \code{operator-types} defines a dictionary that maps the
  6116. operator names to their parameter and return types. The
  6117. \code{type-equal?} method determines whether two types are equal,
  6118. which for now simply dispatches to \code{equal?} (deep
  6119. equality). The \code{check-type-equal?} method triggers an error if
  6120. the two types are not equal. The \code{type-check-op} method looks
  6121. up the operator in the \code{operator-types} dictionary and then
  6122. checks whether the argument types are equal to the parameter types.
  6123. The result is the return type of the operator.}
  6124. %
  6125. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6126. an error if the two types are not equal.}
  6127. \begin{figure}[tbp]
  6128. {\if\edition\racketEd\color{olive}
  6129. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6130. (define type-check-Rvar_class
  6131. (class object%
  6132. (super-new)
  6133. (define/public (operator-types)
  6134. '((+ . ((Integer Integer) . Integer))
  6135. (- . ((Integer) . Integer))
  6136. (read . (() . Integer))))
  6137. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6138. (define/public (check-type-equal? t1 t2 e)
  6139. (unless (type-equal? t1 t2)
  6140. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6141. (define/public (type-check-op op arg-types e)
  6142. (match (dict-ref (operator-types) op)
  6143. [`(,param-types . ,return-type)
  6144. (for ([at arg-types] [pt param-types])
  6145. (check-type-equal? at pt e))
  6146. return-type]
  6147. [else (error 'type-check-op "unrecognized ~a" op)]))
  6148. (define/public (type-check-exp env)
  6149. (lambda (e)
  6150. (match e
  6151. [(Int n) (values (Int n) 'Integer)]
  6152. [(Var x) (values (Var x) (dict-ref env x))]
  6153. [(Let x e body)
  6154. (define-values (e^ Te) ((type-check-exp env) e))
  6155. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6156. (values (Let x e^ b) Tb)]
  6157. [(Prim op es)
  6158. (define-values (new-es ts)
  6159. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6160. (values (Prim op new-es) (type-check-op op ts e))]
  6161. [else (error 'type-check-exp "couldn't match" e)])))
  6162. (define/public (type-check-program e)
  6163. (match e
  6164. [(Program info body)
  6165. (define-values (body^ Tb) ((type-check-exp '()) body))
  6166. (check-type-equal? Tb 'Integer body)
  6167. (Program info body^)]
  6168. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  6169. ))
  6170. (define (type-check-Rvar p)
  6171. (send (new type-check-Rvar_class) type-check-program p))
  6172. \end{lstlisting}
  6173. \fi}
  6174. {\if\edition\pythonEd
  6175. \begin{lstlisting}
  6176. class TypeCheckPvar:
  6177. def check_type_equal(self, t1, t2, e):
  6178. if t1 != t2:
  6179. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6180. raise Exception(msg)
  6181. def type_check_exp(self, e, env):
  6182. match e:
  6183. case BinOp(left, Add(), right):
  6184. l = self.type_check_exp(left, env)
  6185. check_type_equal(l, int, left)
  6186. r = self.type_check_exp(right, env)
  6187. check_type_equal(r, int, right)
  6188. return int
  6189. case UnaryOp(USub(), v):
  6190. t = self.type_check_exp(v, env)
  6191. check_type_equal(t, int, v)
  6192. return int
  6193. case Name(id):
  6194. return env[id]
  6195. case Constant(value) if isinstance(value, int):
  6196. return int
  6197. case Call(Name('input_int'), []):
  6198. return int
  6199. def type_check_stmts(self, ss, env):
  6200. if len(ss) == 0:
  6201. return
  6202. match ss[0]:
  6203. case Assign([lhs], value):
  6204. t = self.type_check_exp(value, env)
  6205. if lhs.id in env:
  6206. check_type_equal(env[lhs.id], t, value)
  6207. else:
  6208. env[lhs.id] = t
  6209. return self.type_check_stmts(ss[1:], env)
  6210. case Expr(Call(Name('print'), [arg])):
  6211. t = self.type_check_exp(arg, env)
  6212. check_type_equal(t, int, arg)
  6213. return self.type_check_stmts(ss[1:], env)
  6214. case Expr(value):
  6215. self.type_check_exp(value, env)
  6216. return self.type_check_stmts(ss[1:], env)
  6217. def type_check_P(self, p):
  6218. match p:
  6219. case Module(body):
  6220. self.type_check_stmts(body, {})
  6221. \end{lstlisting}
  6222. \fi}
  6223. \caption{Type checker for the \LangVar{} language.}
  6224. \label{fig:type-check-Rvar}
  6225. \end{figure}
  6226. \begin{figure}[tbp]
  6227. {\if\edition\racketEd\color{olive}
  6228. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6229. (define type-check-Rif_class
  6230. (class type-check-Rvar_class
  6231. (super-new)
  6232. (inherit check-type-equal?)
  6233. (define/override (operator-types)
  6234. (append '((- . ((Integer Integer) . Integer))
  6235. (and . ((Boolean Boolean) . Boolean))
  6236. (or . ((Boolean Boolean) . Boolean))
  6237. (< . ((Integer Integer) . Boolean))
  6238. (<= . ((Integer Integer) . Boolean))
  6239. (> . ((Integer Integer) . Boolean))
  6240. (>= . ((Integer Integer) . Boolean))
  6241. (not . ((Boolean) . Boolean))
  6242. )
  6243. (super operator-types)))
  6244. (define/override (type-check-exp env)
  6245. (lambda (e)
  6246. (match e
  6247. [(Bool b) (values (Bool b) 'Boolean)]
  6248. [(Prim 'eq? (list e1 e2))
  6249. (define-values (e1^ T1) ((type-check-exp env) e1))
  6250. (define-values (e2^ T2) ((type-check-exp env) e2))
  6251. (check-type-equal? T1 T2 e)
  6252. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6253. [(If cnd thn els)
  6254. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6255. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6256. (define-values (els^ Te) ((type-check-exp env) els))
  6257. (check-type-equal? Tc 'Boolean e)
  6258. (check-type-equal? Tt Te e)
  6259. (values (If cnd^ thn^ els^) Te)]
  6260. [else ((super type-check-exp env) e)])))
  6261. ))
  6262. (define (type-check-Rif p)
  6263. (send (new type-check-Rif_class) type-check-program p))
  6264. \end{lstlisting}
  6265. \fi}
  6266. {\if\edition\pythonEd
  6267. \begin{lstlisting}
  6268. class TypeCheckPif(TypeCheckPvar):
  6269. def type_check_exp(self, e, env):
  6270. match e:
  6271. case Constant(value) if isinstance(value, bool):
  6272. return bool
  6273. case BinOp(left, Sub(), right):
  6274. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6275. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6276. return int
  6277. case UnaryOp(Not(), v):
  6278. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6279. return bool
  6280. case BoolOp(op, values):
  6281. left = values[0] ; right = values[1]
  6282. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6283. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6284. return bool
  6285. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6286. or isinstance(cmp, NotEq):
  6287. l = self.type_check_exp(left, env)
  6288. r = self.type_check_exp(right, env)
  6289. check_type_equal(l, r, e)
  6290. return bool
  6291. case Compare(left, [cmp], [right]):
  6292. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6293. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6294. return bool
  6295. case IfExp(test, body, orelse):
  6296. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6297. b = self.type_check_exp(body, env)
  6298. o = self.type_check_exp(orelse, env)
  6299. check_type_equal(b, o, e)
  6300. return b
  6301. case _:
  6302. return super().type_check_exp(e, env)
  6303. def type_check_stmts(self, ss, env):
  6304. if len(ss) == 0:
  6305. return
  6306. match ss[0]:
  6307. case If(test, body, orelse):
  6308. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6309. b = self.type_check_stmts(body, env)
  6310. o = self.type_check_stmts(orelse, env)
  6311. check_type_equal(b, o, ss[0])
  6312. return self.type_check_stmts(ss[1:], env)
  6313. case _:
  6314. return super().type_check_stmts(ss, env)
  6315. \end{lstlisting}
  6316. \fi}
  6317. \caption{Type checker for the \LangIf{} language.}
  6318. \label{fig:type-check-Rif}
  6319. \end{figure}
  6320. Next we discuss the type checker for \LangIf{} in
  6321. Figure~\ref{fig:type-check-Rif}.
  6322. %
  6323. The type of a Boolean constant is \code{Boolean}.
  6324. %
  6325. \racket{The \code{operator-types} function adds dictionary entries for
  6326. the other new operators.}
  6327. %
  6328. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6329. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6330. produces a \BOOLTY{}. Similarly for logical-and and logical-or. }
  6331. %
  6332. The equality operators requires the two arguments to have the same
  6333. type.
  6334. %
  6335. \python{The other comparisons (less-than, etc.) require their
  6336. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6337. %
  6338. The condition of an \code{if} must
  6339. be of \BOOLTY{} type and the two branches must have the same type.
  6340. \begin{exercise}\normalfont
  6341. Create 10 new test programs in \LangIf{}. Half of the programs should
  6342. have a type error. For those programs, create an empty file with the
  6343. same base name but with file extension \code{.tyerr}. For example, if
  6344. the test
  6345. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6346. is expected to error, then create
  6347. an empty file named \code{cond\_test\_14.tyerr}.
  6348. %
  6349. \racket{This indicates to \code{interp-tests} and
  6350. \code{compiler-tests} that a type error is expected. }
  6351. %
  6352. \racket{This indicates to the \code{run-tests.py} scripts that a type
  6353. error is expected.}
  6354. %
  6355. The other half of the test programs should not have type errors.
  6356. %
  6357. \racket{In the \code{run-tests.rkt} script, change the second argument
  6358. of \code{interp-tests} and \code{compiler-tests} to
  6359. \code{type-check-Rif}, which causes the type checker to run prior to
  6360. the compiler passes. Temporarily change the \code{passes} to an
  6361. empty list and run the script, thereby checking that the new test
  6362. programs either type check or not as intended.}
  6363. %
  6364. Run the test script to check that these test programs type check as
  6365. expected.
  6366. \end{exercise}
  6367. \section{The \LangCIf{} Intermediate Language}
  6368. \label{sec:Cif}
  6369. {\if\edition\pythonEd
  6370. The output of \key{explicate\_control} is a language similar to the
  6371. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6372. \code{goto} statements, so we name it \LangCIf{}. The abstract syntax
  6373. for \LangCIf{} is defined in Figure~\ref{fig:c1-syntax}.
  6374. \racket{(The concrete syntax for \LangCIf{} is in the Appendix,
  6375. Figure~\ref{fig:c1-concrete-syntax}.)}
  6376. %
  6377. The \LangCIf{} language supports the same operators as \LangIf{} but
  6378. the arguments of operators are restricted to atomic expressions. The
  6379. \LangCIf{} language does not include \code{if} expressions but it does
  6380. include a restricted form of \code{if} statment. The condition must be
  6381. a comparison and the two branches may only contain \code{goto}
  6382. statements. These restrictions make it easier to translate \code{if}
  6383. statements to x86.
  6384. %
  6385. Also, a \LangCIf{} program consists of a dictionary mapping labels to
  6386. lists of statements, instead of simply being a list of statements.
  6387. \fi}
  6388. \racket{
  6389. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  6390. \LangCIf{} intermediate language. (The concrete syntax is in the
  6391. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  6392. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  6393. operators to the \Exp{} non-terminal and the literals \TRUE{} and
  6394. \FALSE{} to the \Arg{} non-terminal.
  6395. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6396. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6397. statement is a comparison operation and the branches are \code{goto}
  6398. statements, making it straightforward to compile \code{if} statements
  6399. to x86.
  6400. }
  6401. \begin{figure}[tp]
  6402. \fbox{
  6403. \begin{minipage}{0.96\textwidth}
  6404. \small
  6405. {\if\edition\racketEd\color{olive}
  6406. \[
  6407. \begin{array}{lcl}
  6408. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6409. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  6410. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6411. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6412. &\MID& \UNIOP{\key{'not}}{\Atm}
  6413. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6414. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6415. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6416. \MID \GOTO{\itm{label}} \\
  6417. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6418. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6419. \end{array}
  6420. \]
  6421. \fi}
  6422. {\if\edition\pythonEd
  6423. \[
  6424. \begin{array}{lcl}
  6425. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6426. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  6427. \Exp &::= & \Atm \MID \READ{} \\
  6428. &\MID& \BINOP{\Atm}{\itm{binop}}{\Atm}
  6429. \MID \UNIOP{\itm{uniop}}{\Atm} \\
  6430. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6431. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6432. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6433. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6434. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6435. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6436. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{+}, \ldots \RC}
  6437. \end{array}
  6438. \]
  6439. \fi}
  6440. \end{minipage}
  6441. }
  6442. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6443. (Figure~\ref{fig:c0-syntax})}.}
  6444. \label{fig:c1-syntax}
  6445. \end{figure}
  6446. \section{The \LangXIf{} Language}
  6447. \label{sec:x86-if}
  6448. \index{subject}{x86} To implement the new logical operations, the comparison
  6449. operations, and the \key{if} expression, we need to delve further into
  6450. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6451. define the concrete and abstract syntax for the \LangXIf{} subset
  6452. of x86, which includes instructions for logical operations,
  6453. comparisons, and conditional jumps.
  6454. One challenge is that x86 does not provide an instruction that
  6455. directly implements logical negation (\code{not} in \LangIf{} and
  6456. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6457. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6458. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6459. bit of its arguments, and writes the results into its second argument.
  6460. Recall the truth table for exclusive-or:
  6461. \begin{center}
  6462. \begin{tabular}{l|cc}
  6463. & 0 & 1 \\ \hline
  6464. 0 & 0 & 1 \\
  6465. 1 & 1 & 0
  6466. \end{tabular}
  6467. \end{center}
  6468. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6469. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6470. for the bit $1$, the result is the opposite of the second bit. Thus,
  6471. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6472. the first argument:
  6473. \[
  6474. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Arg}}
  6475. \qquad\Rightarrow\qquad
  6476. \begin{array}{l}
  6477. \key{movq}~ \Arg\key{,} \Var\\
  6478. \key{xorq}~ \key{\$1,} \Var
  6479. \end{array}
  6480. \]
  6481. \begin{figure}[tp]
  6482. \fbox{
  6483. \begin{minipage}{0.96\textwidth}
  6484. \[
  6485. \begin{array}{lcl}
  6486. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6487. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6488. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6489. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6490. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6491. \key{subq} \; \Arg\key{,} \Arg \MID
  6492. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6493. && \gray{ \key{callq} \; \itm{label} \MID
  6494. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} } \\
  6495. && \gray{ \itm{label}\key{:}\; \Instr }
  6496. \MID \key{xorq}~\Arg\key{,}~\Arg
  6497. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6498. && \key{set}cc~\Arg
  6499. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6500. \MID \key{j}cc~\itm{label}
  6501. \\
  6502. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6503. & & \gray{ \key{main:} \; \Instr\ldots }
  6504. \end{array}
  6505. \]
  6506. \end{minipage}
  6507. }
  6508. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6509. \label{fig:x86-1-concrete}
  6510. \end{figure}
  6511. \begin{figure}[tp]
  6512. \fbox{
  6513. \begin{minipage}{0.98\textwidth}
  6514. \small
  6515. {\if\edition\racketEd\color{olive}
  6516. \[
  6517. \begin{array}{lcl}
  6518. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6519. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6520. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6521. \MID \BYTEREG{\itm{bytereg}} \\
  6522. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6523. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6524. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6525. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6526. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6527. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6528. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6529. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6530. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6531. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6532. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6533. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6534. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6535. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6536. \end{array}
  6537. \]
  6538. \fi}
  6539. %
  6540. {\if\edition\pythonEd
  6541. \[
  6542. \begin{array}{lcl}
  6543. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6544. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6545. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6546. \MID \BYTEREG{\itm{bytereg}} \\
  6547. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6548. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6549. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6550. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6551. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6552. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6553. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6554. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6555. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6556. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6557. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6558. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6559. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{+} \key{,} \ldots \RC }
  6560. \end{array}
  6561. \]
  6562. \fi}
  6563. \end{minipage}
  6564. }
  6565. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6566. \label{fig:x86-1}
  6567. \end{figure}
  6568. Next we consider the x86 instructions that are relevant for compiling
  6569. the comparison operations. The \key{cmpq} instruction compares its two
  6570. arguments to determine whether one argument is less than, equal, or
  6571. greater than the other argument. The \key{cmpq} instruction is unusual
  6572. regarding the order of its arguments and where the result is
  6573. placed. The argument order is backwards: if you want to test whether
  6574. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6575. \key{cmpq} is placed in the special EFLAGS register. This register
  6576. cannot be accessed directly but it can be queried by a number of
  6577. instructions, including the \key{set} instruction. The instruction
  6578. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6579. depending on whether the comparison comes out according to the
  6580. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6581. for less-or-equal, \key{g} for greater, \key{ge} for
  6582. greater-or-equal). The \key{set} instruction has an annoying quirk in
  6583. that its destination argument must be single byte register, such as
  6584. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6585. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6586. instruction can be used to move from a single byte register to a
  6587. normal 64-bit register. The abstract syntax for the \code{set}
  6588. instruction differs from the concrete syntax in that it separates the
  6589. instruction name from the condition code.
  6590. The x86 instruction for conditional jump is relevant to the
  6591. compilation of \key{if} expressions. The instruction
  6592. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  6593. the instruction after \itm{label} depending on whether the result in
  6594. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  6595. jump instruction falls through to the next instruction. Like the
  6596. abstract syntax for \code{set}, the abstract syntax for conditional
  6597. jump separates the instruction name from the condition code. For
  6598. example, \JMPIF{\key{'le'}}{\key{foo}} corresponds to \code{jle foo}.
  6599. Because the conditional jump instruction relies on the EFLAGS
  6600. register, it is common for it to be immediately preceded by a
  6601. \key{cmpq} instruction to set the EFLAGS register.
  6602. \section{Shrink the \LangIf{} Language}
  6603. \label{sec:shrink-Rif}
  6604. The \LangIf{} language includes several features that are easily
  6605. expressible with other features. For example, \code{and} and \code{or}
  6606. are expressible using \code{if} as follows.
  6607. \begin{align*}
  6608. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6609. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6610. \end{align*}
  6611. By performing these translations in the front-end of the compiler, the
  6612. later passes of the compiler do not need to deal with these features,
  6613. making the passes shorter.
  6614. %% For example, subtraction is
  6615. %% expressible using addition and negation.
  6616. %% \[
  6617. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6618. %% \]
  6619. %% Several of the comparison operations are expressible using less-than
  6620. %% and logical negation.
  6621. %% \[
  6622. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6623. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6624. %% \]
  6625. %% The \key{let} is needed in the above translation to ensure that
  6626. %% expression $e_1$ is evaluated before $e_2$.
  6627. On the other hand, sometimes translations reduce the efficiency of the
  6628. generated code by increasing the number of instructions. For example,
  6629. expressing subtraction in terms of negation
  6630. \[
  6631. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6632. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6633. \]
  6634. produces code with two x86 instructions (\code{negq} and \code{addq})
  6635. instead of just one (\code{subq}).
  6636. %% However,
  6637. %% these differences typically do not affect the number of accesses to
  6638. %% memory, which is the primary factor that determines execution time on
  6639. %% modern computer architectures.
  6640. \begin{exercise}\normalfont
  6641. %
  6642. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6643. the language by translating them to other constructs in \LangIf{}.
  6644. %
  6645. Create four test programs that involve these operators.
  6646. %
  6647. {\if\edition\racketEd\color{olive}
  6648. In the \code{run-tests.rkt} script, add the following entry for
  6649. \code{shrink} to the list of passes (it should be the only pass at
  6650. this point).
  6651. \begin{lstlisting}
  6652. (list "shrink" shrink interp_Rif type-check-Rif)
  6653. \end{lstlisting}
  6654. This instructs \code{interp-tests} to run the intepreter
  6655. \code{interp\_Rif} and the type checker \code{type-check-Rif} on the
  6656. output of \code{shrink}.
  6657. \fi}
  6658. %
  6659. Run the script to test your compiler on all the test programs.
  6660. \end{exercise}
  6661. {\if\edition\racketEd\color{olive}
  6662. \section{Uniquify Variables}
  6663. \label{sec:uniquify-Rif}
  6664. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6665. \code{if} expressions.
  6666. \begin{exercise}\normalfont
  6667. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6668. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6669. \begin{lstlisting}
  6670. (list "uniquify" uniquify interp_Rif type_check_Rif)
  6671. \end{lstlisting}
  6672. Run the script to test your compiler.
  6673. \end{exercise}
  6674. \fi}
  6675. \section{Remove Complex Operands}
  6676. \label{sec:remove-complex-opera-Rif}
  6677. The output language for this pass is \LangIfANF{}
  6678. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  6679. \LangIf{}. A Boolean constant is an atomic expressions but the
  6680. \code{if} expression is not.
  6681. All three sub-expressions of an
  6682. \code{if} are allowed to be complex expressions but the operands of
  6683. \code{not} and the comparisons must be atomic.
  6684. %
  6685. \python{We add a new language form, the \code{Let} expression, to aid
  6686. in the translation of \code{if} expressions. The
  6687. $\LET{x}{e_1}{e_2}$ form is like an assignment statement, but can be
  6688. used as an expression. It assigns the result of $e_1$ to the
  6689. variable $x$, an then evaluates $e_2$, which may reference $x$.}
  6690. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6691. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6692. according to whether the output needs to be \Exp{} or \Atm{} as
  6693. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6694. particularly important to \textbf{not} replace its condition with a
  6695. temporary variable because that would interfere with the generation of
  6696. high-quality output in the \code{explicate\_control} pass.
  6697. \begin{figure}[tp]
  6698. \centering
  6699. \fbox{
  6700. \begin{minipage}{0.96\textwidth}
  6701. {\if\edition\racketEd\color{olive}
  6702. \[
  6703. \begin{array}{rcl}
  6704. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6705. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6706. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6707. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6708. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6709. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6710. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6711. \end{array}
  6712. \]
  6713. \fi}
  6714. {\if\edition\pythonEd
  6715. \[
  6716. \begin{array}{rcl}
  6717. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  6718. \Exp &::=& \Atm \MID \READ{} \\
  6719. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  6720. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6721. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  6722. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6723. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  6724. P^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  6725. \end{array}
  6726. \]
  6727. \fi}
  6728. \end{minipage}
  6729. }
  6730. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  6731. \label{fig:Rif-anf-syntax}
  6732. \end{figure}
  6733. \begin{exercise}\normalfont
  6734. %
  6735. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6736. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6737. %
  6738. Create three new \LangInt{} programs that exercise the interesting
  6739. code in this pass.
  6740. %
  6741. {\if\edition\racketEd\color{olive}
  6742. In the \code{run-tests.rkt} script, add the following entry to the
  6743. list of \code{passes} and then run the script to test your compiler.
  6744. \begin{lstlisting}
  6745. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  6746. \end{lstlisting}
  6747. \fi}
  6748. \end{exercise}
  6749. \section{Explicate Control}
  6750. \label{sec:explicate-control-Rif}
  6751. \racket{Recall that the purpose of \code{explicate\_control} is to
  6752. make the order of evaluation explicit in the syntax of the program.
  6753. With the addition of \key{if} this get more interesting.}
  6754. %
  6755. The main challenge is that the condition of an \key{if} can be an
  6756. arbitrary expression in \LangIf{} whereas in \LangCIf{} the condition
  6757. must be a comparison.
  6758. As a motivating example, consider the following program that has an
  6759. \key{if} expression nested in the condition of another \key{if}.
  6760. % cond_test_41.rkt, if_lt_eq.py
  6761. \begin{center}
  6762. \begin{minipage}{0.96\textwidth}
  6763. {\if\edition\racketEd\color{olive}
  6764. \begin{lstlisting}
  6765. (let ([x (read)])
  6766. (let ([y (read)])
  6767. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6768. (+ y 2)
  6769. (+ y 10))))
  6770. \end{lstlisting}
  6771. \fi}
  6772. {\if\edition\pythonEd
  6773. \begin{lstlisting}
  6774. x = input_int()
  6775. y = input_int()
  6776. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  6777. \end{lstlisting}
  6778. \fi}
  6779. \end{minipage}
  6780. \end{center}
  6781. %
  6782. The naive way to compile \key{if} and the comparison operations would
  6783. be to handle each of them in isolation, regardless of their context.
  6784. Each comparison would be translated into a \key{cmpq} instruction
  6785. followed by a couple instructions to move the result from the EFLAGS
  6786. register into a general purpose register or stack location. Each
  6787. \key{if} would be translated into a \key{cmpq} instruction followed by
  6788. a conditional jump. The generated code for the inner \key{if} in the
  6789. above example would be as follows.
  6790. \begin{center}
  6791. \begin{minipage}{0.96\textwidth}
  6792. \begin{lstlisting}
  6793. cmpq $1, x
  6794. setl %al
  6795. movzbq %al, tmp
  6796. cmpq $1, tmp
  6797. je then_branch_1
  6798. jmp else_branch_1
  6799. \end{lstlisting}
  6800. \end{minipage}
  6801. \end{center}
  6802. However, if we take context into account we can do better and reduce
  6803. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6804. Our goal will be to compile \key{if} expressions so that the relevant
  6805. comparison instruction appears directly before the conditional jump.
  6806. For example, we want to generate the following code for the inner
  6807. \code{if}.
  6808. \begin{center}
  6809. \begin{minipage}{0.96\textwidth}
  6810. \begin{lstlisting}
  6811. cmpq $1, x
  6812. je then_branch_1
  6813. jmp else_branch_1
  6814. \end{lstlisting}
  6815. \end{minipage}
  6816. \end{center}
  6817. One way to achieve this is to reorganize the code at the level of
  6818. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  6819. the following code.
  6820. \begin{center}
  6821. \begin{minipage}{0.96\textwidth}
  6822. {\if\edition\racketEd\color{olive}
  6823. \begin{lstlisting}
  6824. (let ([x (read)])
  6825. (let ([y (read)])
  6826. (if (< x 1)
  6827. (if (eq? x 0)
  6828. (+ y 2)
  6829. (+ y 10))
  6830. (if (eq? x 2)
  6831. (+ y 2)
  6832. (+ y 10)))))
  6833. \end{lstlisting}
  6834. \fi}
  6835. {\if\edition\pythonEd
  6836. \begin{lstlisting}
  6837. x = input_int()
  6838. y = intput_int()
  6839. print(((y + 2) if x == 0 else (y + 10)) \
  6840. if (x < 1) \
  6841. else ((y + 2) if (x == 2) else (y + 10)))
  6842. \end{lstlisting}
  6843. \fi}
  6844. \end{minipage}
  6845. \end{center}
  6846. Unfortunately, this approach duplicates the two branches from the
  6847. outer \code{if} and a compiler must never duplicate code!
  6848. We need a way to perform the above transformation but without
  6849. duplicating code. That is, we need a way for different parts of a
  6850. program to refer to the same piece of code.
  6851. %
  6852. Put another way, we need to move away from abstract syntax
  6853. \emph{trees} and instead use \emph{graphs}.
  6854. %
  6855. At the level of x86 assembly this is straightforward because we can
  6856. label the code for each branch and insert jumps in all the places that
  6857. need to execute the branch.
  6858. %
  6859. Likewise, our language \LangCIf{} provides the ability to label a
  6860. sequence of code and to jump to a label via \code{goto}.
  6861. %
  6862. %% In particular, we use a standard program representation called a
  6863. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  6864. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  6865. %% is a labeled sequence of code, called a \emph{basic block}, and each
  6866. %% edge represents a jump to another block.
  6867. %
  6868. In particular, the \key{CProgram} construct contains \racket{an
  6869. alist}\python{a dictionary} mapping labels to \emph{basic blocks}. Each
  6870. basic block is \racket{represented by the $\Tail$ non-terminal}
  6871. \python{a list of statements}.
  6872. %% The nice thing about the output of \code{explicate\_control} is that
  6873. %% there are no unnecessary comparisons and every comparison is part of a
  6874. %% conditional jump.
  6875. %% The down-side of this output is that it includes
  6876. %% trivial blocks, such as the blocks labeled \code{block92} through
  6877. %% \code{block95}, that only jump to another block. We discuss a solution
  6878. %% to this problem in Section~\ref{sec:opt-jumps}.
  6879. {\if\edition\racketEd\color{olive}
  6880. %
  6881. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  6882. \code{explicate\_control} for \LangVar{} using two mutually recursive
  6883. functions, \code{explicate-tail} and \code{explicate-assign}. The
  6884. former function translates expressions in tail position whereas the
  6885. later function translates expressions on the right-hand-side of a
  6886. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  6887. have a new kind of position to deal with: the predicate position of
  6888. the \key{if}. We need another function, \code{explicate-pred}, that
  6889. takes an \LangIf{} expression and two blocks for the then-branch and
  6890. else-branch. The output of \code{explicate-pred} is a block. In the
  6891. following paragraphs we discuss specific cases in the
  6892. \code{explicate\_pred} function as well as additions to the
  6893. \code{explicate\_tail} and \code{explicate\_assign} functions.
  6894. %
  6895. \fi}
  6896. %
  6897. {\if\edition\pythonEd
  6898. %
  6899. We recommend implementing \code{explicate\_control} using four
  6900. auxiliary functions which we discuss in the following paragraphs.
  6901. \begin{description}
  6902. \item[\code{explicate\_effect}] generates code for expressions as
  6903. statements, so their result is ignored and only their side-effects
  6904. matter.
  6905. \item[\code{explicate\_assign}] generates code for expressions
  6906. on the right-hand side of an assignment.
  6907. \item[\code{explicate\_pred}] generates code for an \code{if}
  6908. expression or statement by analyzing the condition expression.
  6909. \item[\code{explicate\_stmt}] generates code for statements.
  6910. \end{description}
  6911. These four functions should incrementally build up the dictionary of
  6912. basic blocks. The following auxiliary function can be used to create a
  6913. new basic block from a list of statements. It returns a \code{goto}
  6914. statement that jumps to the new basic block.
  6915. \begin{center}
  6916. \begin{minipage}{\textwidth}
  6917. \begin{lstlisting}
  6918. def create_block(stmts, basic_blocks):
  6919. label = label_name(generate_name('block'))
  6920. basic_blocks[label] = stmts
  6921. return Goto(label)
  6922. \end{lstlisting}
  6923. \end{minipage}
  6924. \end{center}
  6925. Figure~\ref{fig:explicate-control-Rif} provides a skeleton for the
  6926. \code{explicate\_control} pass.
  6927. The \code{explicate\_effect} function has three parameters: 1) the
  6928. expression to be compiled, 2) the already-compiled code for this
  6929. expression's \emph{continuation}, that is, the list of statements that
  6930. should execute after this expression, and 3) the dictionary of
  6931. generated basic blocks. The output of \code{explicate\_effect} is a
  6932. list of \LangCIf{} statements.
  6933. %
  6934. Let's consider a few of the cases for the expression to be compiled.
  6935. If the expression to be compiled is a constant, then it can be
  6936. discarded because it has no side effects. If it's a \CREAD{}, then
  6937. that's a side-effect and should be preserved. So it should be
  6938. translated into a statment using the \code{Expr} AST class. If the
  6939. expression to be compiled is an \code{if} expression, we translate the
  6940. two branches using \code{explicate\_effect} and then translate the
  6941. condition expression using \code{explicate\_pred}, which generates
  6942. code for the entire \code{if}.
  6943. The \code{explicate\_assign} function has four parameters: 1) the
  6944. right-hand-side of the assignment, 2) the left-hand-side of the
  6945. assignment (the variable), 3) the continuation, and 4) the dictionary
  6946. of basic blocks. The output of \code{explicate\_assign} is a list of
  6947. \LangCIf{} statements.
  6948. When the right-hand-side is an \code{if} expression, there is some
  6949. work to do. In particular, the two branches should be translated using
  6950. \code{explicate\_assign} and the condition expression should be
  6951. translated using \code{explicate\_pred}. Otherwise we can simply
  6952. generate an assignment statement with the given left and right-hand
  6953. sides.
  6954. \begin{figure}[tbp]
  6955. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6956. def explicate_effect(e, cont, basic_blocks):
  6957. match e:
  6958. case IfExp(test, body, orelse):
  6959. ...
  6960. case Call(func, args):
  6961. ...
  6962. case Let(var, rhs, body):
  6963. ...
  6964. case _:
  6965. ...
  6966. def explicate_assign(rhs, lhs, cont, basic_blocks):
  6967. match rhs:
  6968. case IfExp(test, body, orelse):
  6969. ...
  6970. case Let(var, rhs, body):
  6971. ...
  6972. case _:
  6973. return [Assign([lhs], rhs)] + cont
  6974. def explicate_pred(cnd, thn, els, basic_blocks):
  6975. match cnd:
  6976. case Compare(left, [op], [right]):
  6977. goto_thn = create_block(thn, basic_blocks)
  6978. goto_els = create_block(els, basic_blocks)
  6979. return [If(cnd, [goto_thn], [goto_els])]
  6980. case Constant(True):
  6981. return thn;
  6982. case Constant(False):
  6983. return els;
  6984. case UnaryOp(Not(), operand):
  6985. ...
  6986. case IfExp(test, body, orelse):
  6987. ...
  6988. case Let(var, rhs, body):
  6989. ...
  6990. case _:
  6991. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  6992. [create_block(els, basic_blocks)],
  6993. [create_block(thn, basic_blocks)])]
  6994. def explicate_stmt(s, cont, basic_blocks):
  6995. match s:
  6996. case Assign([lhs], rhs):
  6997. return explicate_assign(rhs, lhs, cont, basic_blocks)
  6998. case Expr(value):
  6999. return explicate_effect(value, cont, basic_blocks)
  7000. case If(test, body, orelse):
  7001. ...
  7002. def explicate_control(p):
  7003. match p:
  7004. case Module(body):
  7005. new_body = [Return(Constant(0))]
  7006. basic_blocks = {}
  7007. for s in reversed(body):
  7008. new_body = explicate_stmt(s, new_body, basic_blocks)
  7009. basic_blocks[label_name('start')] = new_body
  7010. return CProgram(basic_blocks)
  7011. \end{lstlisting}
  7012. \caption{Skeleton for the \code{explicate\_control} pass.}
  7013. \label{fig:explicate-control-Rif}
  7014. \end{figure}
  7015. \fi}
  7016. {\if\edition\racketEd\color{olive}
  7017. \begin{figure}[tbp]
  7018. \begin{lstlisting}
  7019. (define (explicate-pred cnd thn els)
  7020. (match cnd
  7021. [(Var x) ___]
  7022. [(Let x rhs body) ___]
  7023. [(Prim 'not (list e)) ___]
  7024. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7025. (IfStmt (Prim op arg*) (force (block->goto thn))
  7026. (force (block->goto els)))]
  7027. [(Bool b) (if b thn els)]
  7028. [(If cnd^ thn^ els^) ___]
  7029. [else (error "explicate-pred unhandled case" cnd)]))
  7030. \end{lstlisting}
  7031. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  7032. \label{fig:explicate-pred}
  7033. \end{figure}
  7034. \fi}
  7035. \racket{The skeleton for the \code{explicate\_pred} function is given
  7036. in Figure~\ref{fig:explicate-pred}. It has a case for every
  7037. expression that can have type \code{Boolean}. We detail a few cases
  7038. here and leave the rest for the reader. The input to this function
  7039. is an expression and two blocks, \code{thn} and \code{els}, for the
  7040. two branches of the enclosing \key{if}.}
  7041. %
  7042. \python{The \code{explicate\_pred} function has four parameters: 1)
  7043. the condition expession, 2) the generated statements for the
  7044. ``then'' branch, 3) the generated statements for the ``else''
  7045. branch, and 4) the dictionary of basic blocks. The output of
  7046. \code{explicate\_pred} is a list of \LangCIf{} statements.}
  7047. %
  7048. Consider the case for comparison operators. We translate the
  7049. comparison to an \code{if} statement whose branches are \code{goto}
  7050. statements created by applying \code{create\_block} to the \code{thn}
  7051. and \code{els} branches.
  7052. %
  7053. Next consider the case for Boolean constants. We perform a kind of
  7054. partial evaluation\index{subject}{partial evaluation} and output
  7055. either the \code{thn} or \code{els} branch depending on whether the
  7056. constant is \TRUE{} or \FALSE{}. This case demonstrates that we
  7057. sometimes discard the \code{thn} or \code{els} blocks that are input
  7058. to \code{explicate\_pred}.
  7059. The case for \key{if} expressions in \code{explicate\_pred} is
  7060. particularly illuminating because it deals with the challenges we
  7061. discussed above regarding nested \key{if} expressions
  7062. (Figure~\ref{fig:explicate-control-s1-38}). The
  7063. \racket{\lstinline{thn^}}\python{\code{body}} and
  7064. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7065. \key{if} inherit their context from the current one, that is,
  7066. predicate context. So you should recursively apply
  7067. \code{explicate\_pred} to the
  7068. \racket{\lstinline{thn^}}\python{\code{body}} and
  7069. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7070. those recursive calls, pass \code{thn} and \code{els} as the extra
  7071. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7072. inside each recursive call. As discussed above, to avoid duplicating
  7073. code, we need to add them to the dictionary of basic blocks so that we
  7074. can instead refer to them by name and execute them with a \key{goto}.
  7075. {\if\edition\pythonEd
  7076. %
  7077. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7078. three parameters: 1) the statement to be compiled, 2) the code for its
  7079. continuation, and 3) the dictionary of basic blocks. The output is a
  7080. list of statements. The cases for assignment and an
  7081. expression-statement are given in full in the skeleton code: they
  7082. simply dispatch to \code{explicate\_assign} and
  7083. \code{explicate\_effect}, respectively. The case for \code{if}
  7084. statements is not given, and is similar to the case for \code{if}
  7085. expressions.
  7086. The \code{explicate\_control} function itself is given in
  7087. Figure~\ref{fig:explicate-control-Rif}. It applies
  7088. \code{explicate\_stmt} to each statement in the program, from back to
  7089. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7090. used as the continuation parameter in the next call to
  7091. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7092. \code{Return} statment. Once complete, we add the \code{new\_body} to
  7093. the dictionary of basic blocks, labeling it as the ``start'' block.
  7094. %
  7095. \fi}
  7096. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  7097. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  7098. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  7099. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7100. %% results from the two recursive calls. We complete the case for
  7101. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  7102. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7103. %% the result $B_5$.
  7104. %% \[
  7105. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7106. %% \quad\Rightarrow\quad
  7107. %% B_5
  7108. %% \]
  7109. \racket{The \code{explicate\_tail} and \code{explicate\_assign}
  7110. functions need additional cases for Boolean constants and \key{if}.
  7111. In the cases for \code{if}, the two branches inherit the current
  7112. context, so in \code{explicate\_tail} they are in tail position and
  7113. in \code{explicate\_assign} they are in assignment position. The
  7114. \code{cont} parameter of \code{explicate\_assign} is used in both
  7115. recursive calls, so make sure to use \code{block->goto} on it.}
  7116. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  7117. %% inherit the current context, so they are in tail position. Thus, the
  7118. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7119. %% \code{explicate-tail}.
  7120. %% %
  7121. %% We need to pass $B_0$ as the accumulator argument for both of these
  7122. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7123. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  7124. %% to the control-flow graph and obtain a promised goto $G_0$.
  7125. %% %
  7126. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  7127. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  7128. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7129. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  7130. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7131. %% \[
  7132. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7133. %% \]
  7134. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7135. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7136. %% should not be confused with the labels for the blocks that appear in
  7137. %% the generated code. We initially construct unlabeled blocks; we only
  7138. %% attach labels to blocks when we add them to the control-flow graph, as
  7139. %% we see in the next case.
  7140. %% Next consider the case for \key{if} in the \code{explicate-assign}
  7141. %% function. The context of the \key{if} is an assignment to some
  7142. %% variable $x$ and then the control continues to some promised block
  7143. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7144. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7145. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  7146. %% branches of the \key{if} inherit the current context, so they are in
  7147. %% assignment positions. Let $B_2$ be the result of applying
  7148. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  7149. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  7150. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7151. %% the result of applying \code{explicate-pred} to the predicate
  7152. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7153. %% translates to the promise $B_4$.
  7154. %% \[
  7155. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7156. %% \]
  7157. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7158. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7159. \code{remove\_complex\_operands} pass and then the
  7160. \code{explicate\_control} pass on the example program. We walk through
  7161. the output program and then discuss the algorithm.
  7162. %
  7163. Following the order of evaluation in the output of
  7164. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7165. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7166. in the predicate of the inner \key{if}. In the output of
  7167. \code{explicate\_control}, in the
  7168. block labeled \code{start}, is two assignment statements followed by a
  7169. \code{if} statement that branches to \code{block\_8} or
  7170. \code{block\_9}. The blocks associated with those labels contain the
  7171. translations of the code
  7172. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7173. and
  7174. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7175. respectively. In particular, we start \code{block\_8} with the
  7176. comparison
  7177. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7178. and then branch to \code{block\_4} or \code{block\_5}.
  7179. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7180. \code{block\_4} consists of just a \code{goto} to \code{block\_2}
  7181. and \code{block\_5} consists of just a \code{goto} to \code{block\_3}.
  7182. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7183. and go directly to \code{block\_2} and \code{block\_3},
  7184. which we investigate doing in Section~\ref{sec:opt-jumps}.
  7185. But getting back to the example, \code{block\_2} and \code{block\_3},
  7186. corresponds to the two branches of the outer \key{if}, i.e.,
  7187. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7188. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7189. %
  7190. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7191. %
  7192. \python{The \code{block\_1} corresponds to the \code{print} statment
  7193. at the end of the program.}
  7194. \begin{figure}[tbp]
  7195. {\if\edition\racketEd\color{olive}
  7196. \begin{tabular}{lll}
  7197. \begin{minipage}{0.4\textwidth}
  7198. % cond_test_41.rkt
  7199. \begin{lstlisting}
  7200. (let ([x (read)])
  7201. (let ([y (read)])
  7202. (if (if (< x 1)
  7203. (eq? x 0)
  7204. (eq? x 2))
  7205. (+ y 2)
  7206. (+ y 10))))
  7207. \end{lstlisting}
  7208. \end{minipage}
  7209. &
  7210. $\Rightarrow$
  7211. &
  7212. \begin{minipage}{0.55\textwidth}
  7213. TODO: replace with non-optimized version. -Jeremy
  7214. \begin{lstlisting}
  7215. start:
  7216. x = (read);
  7217. y = (read);
  7218. if (< x 1) goto block40;
  7219. else goto block41;
  7220. block40:
  7221. if (eq? x 0) goto block38;
  7222. else goto block39;
  7223. block41:
  7224. if (eq? x 2) goto block38;
  7225. else goto block39;
  7226. block38:
  7227. return (+ y 2);
  7228. block39:
  7229. return (+ y 10);
  7230. \end{lstlisting}
  7231. \end{minipage}
  7232. \end{tabular}
  7233. \fi}
  7234. {\if\edition\pythonEd
  7235. \begin{tabular}{lll}
  7236. \begin{minipage}{0.4\textwidth}
  7237. % cond_test_41.rkt
  7238. \begin{lstlisting}
  7239. x = input_int()
  7240. y = input_int()
  7241. print(y + 2 \
  7242. if (x == 0 \
  7243. if x < 1 \
  7244. else x == 2) \
  7245. else y + 10)
  7246. \end{lstlisting}
  7247. \end{minipage}
  7248. &
  7249. $\Rightarrow$
  7250. &
  7251. \begin{minipage}{0.55\textwidth}
  7252. \begin{lstlisting}
  7253. start:
  7254. x = input_int()
  7255. y = input_int()
  7256. if x < 1:
  7257. goto block_8
  7258. else:
  7259. goto block_9
  7260. block_8:
  7261. if x == 0:
  7262. goto block_4
  7263. else:
  7264. goto block_5
  7265. block_9:
  7266. if x == 2:
  7267. goto block_6
  7268. else:
  7269. goto block_7
  7270. block_4:
  7271. goto block_2
  7272. block_5:
  7273. goto block_3
  7274. block_6:
  7275. goto block_2
  7276. block_7:
  7277. goto block_3
  7278. block_2:
  7279. tmp_0 = y + 2
  7280. goto block_1
  7281. block_3:
  7282. tmp_0 = y + 10
  7283. goto block_1
  7284. block_1:
  7285. print(tmp_0)
  7286. return 0
  7287. \end{lstlisting}
  7288. \end{minipage}
  7289. \end{tabular}
  7290. \fi}
  7291. \caption{Translation from \LangIf{} to \LangCIf{}
  7292. via the \code{explicate\_control}.}
  7293. \label{fig:explicate-control-s1-38}
  7294. \end{figure}
  7295. {\if\edition\racketEd\color{olive}
  7296. The way in which the \code{shrink} pass transforms logical operations
  7297. such as \code{and} and \code{or} can impact the quality of code
  7298. generated by \code{explicate\_control}. For example, consider the
  7299. following program.
  7300. % cond_test_21.rkt, and_eq_input.py
  7301. \begin{lstlisting}
  7302. (if (and (eq? (read) 0) (eq? (read) 1))
  7303. 0
  7304. 42)
  7305. \end{lstlisting}
  7306. The \code{and} operation should transform into something that the
  7307. \code{explicate-pred} function can still analyze and descend through to
  7308. reach the underlying \code{eq?} conditions. Ideally, your
  7309. \code{explicate\_control} pass should generate code similar to the
  7310. following for the above program.
  7311. \begin{center}
  7312. \begin{lstlisting}
  7313. start:
  7314. tmp1 = (read);
  7315. if (eq? tmp1 0) goto block40;
  7316. else goto block39;
  7317. block40:
  7318. tmp2 = (read);
  7319. if (eq? tmp2 1) goto block38;
  7320. else goto block39;
  7321. block38:
  7322. return 0;
  7323. block39:
  7324. return 42;
  7325. \end{lstlisting}
  7326. \end{center}
  7327. \fi}
  7328. \begin{exercise}\normalfont
  7329. \racket{
  7330. Implement the pass \code{explicate\_control} by adding the cases for
  7331. Boolean constants and \key{if} to the \code{explicate-tail} and
  7332. \code{explicate-assign}. Implement the auxiliary function
  7333. \code{explicate-pred} for predicate contexts.}
  7334. \python{Implement \code{explicate\_control} pass with its
  7335. four auxiliary functions.}
  7336. %
  7337. Create test cases that exercise all of the new cases in the code for
  7338. this pass.
  7339. %
  7340. {\if\edition\racketEd\color{olive}
  7341. Add the following entry to the list of \code{passes} in
  7342. \code{run-tests.rkt} and then run this script to test your compiler.
  7343. \begin{lstlisting}
  7344. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  7345. \end{lstlisting}
  7346. \fi}
  7347. \end{exercise}
  7348. \clearpage
  7349. \section{Select Instructions}
  7350. \label{sec:select-Rif}
  7351. \index{subject}{instruction selection}
  7352. The \code{select\_instructions} pass translates \LangCIf{} to
  7353. \LangXIfVar{}.
  7354. %
  7355. \racket{Recall that we implement this pass using three auxiliary
  7356. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7357. $\Tail$.}
  7358. %
  7359. \racket{For $\Atm$, we have new cases for the Booleans.}
  7360. %
  7361. \python{We begin with the Boolean constants.}
  7362. We take the usual approach of encoding them as integers.
  7363. \[
  7364. \TRUE{} \quad\Rightarrow\quad \key{1}
  7365. \qquad
  7366. \FALSE{} \quad\Rightarrow\quad \key{0}
  7367. \]
  7368. For translating statements, we discuss a couple cases. The \code{not}
  7369. operation can be implemented in terms of \code{xorq} as we discussed
  7370. at the beginning of this section. Given an assignment, if the
  7371. left-hand side variable is the same as the argument of \code{not},
  7372. then just the \code{xorq} instruction suffices.
  7373. \[
  7374. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7375. \quad\Rightarrow\quad
  7376. \key{xorq}~\key{\$}1\key{,}~\Var
  7377. \]
  7378. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7379. semantics of x86. In the following translation, let $\Arg$ be the
  7380. result of translating $\Atm$ to x86.
  7381. \[
  7382. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7383. \quad\Rightarrow\quad
  7384. \begin{array}{l}
  7385. \key{movq}~\Arg\key{,}~\Var\\
  7386. \key{xorq}~\key{\$}1\key{,}~\Var
  7387. \end{array}
  7388. \]
  7389. Next consider the cases for equality. Translating this operation to
  7390. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7391. instruction discussed above. We recommend translating an assignment
  7392. with an equality on the right-hand side into the following sequence of
  7393. three instructions. \\
  7394. \begin{tabular}{lll}
  7395. \begin{minipage}{0.4\textwidth}
  7396. \begin{lstlisting}
  7397. |$\CASSIGN{\Var}{ \CEQ{\Atm_1}{\Atm_2} }$|
  7398. \end{lstlisting}
  7399. \end{minipage}
  7400. &
  7401. $\Rightarrow$
  7402. &
  7403. \begin{minipage}{0.4\textwidth}
  7404. \begin{lstlisting}
  7405. cmpq |$\Arg_2$|, |$\Arg_1$|
  7406. sete %al
  7407. movzbq %al, |$\Var$|
  7408. \end{lstlisting}
  7409. \end{minipage}
  7410. \end{tabular} \\
  7411. The translations for the other comparison operators is similar to the
  7412. above but use different suffixes for the \code{set} instruction.
  7413. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7414. \key{goto} and \key{if} statements. Both are straightforward to
  7415. translate to x86.}
  7416. %
  7417. A \key{goto} statement becomes a jump instruction.
  7418. \[
  7419. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7420. \]
  7421. %
  7422. An \key{if} statement becomes a compare instruction followed by a
  7423. conditional jump (for the ``then'' branch) and the fall-through is to
  7424. a regular jump (for the ``else'' branch).\\
  7425. \begin{tabular}{lll}
  7426. \begin{minipage}{0.4\textwidth}
  7427. \begin{lstlisting}
  7428. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7429. goto |$\ell_1$||$\racket{\key{;}}$|
  7430. else|$\python{\key{:}}$|
  7431. goto |$\ell_2$||$\racket{\key{;}}$|
  7432. \end{lstlisting}
  7433. \end{minipage}
  7434. &
  7435. $\Rightarrow$
  7436. &
  7437. \begin{minipage}{0.4\textwidth}
  7438. \begin{lstlisting}
  7439. cmpq |$\Arg_2$|, |$\Arg_1$|
  7440. je |$\ell_1$|
  7441. jmp |$\ell_2$|
  7442. \end{lstlisting}
  7443. \end{minipage}
  7444. \end{tabular} \\
  7445. Again, the translations for the other comparison operators is similar to the
  7446. above but use different suffixes for the conditional jump instruction.
  7447. \begin{exercise}\normalfont
  7448. Expand your \code{select\_instructions} pass to handle the new
  7449. features of the \LangIf{} language.
  7450. %
  7451. {\if\edition\racketEd\color{olive}
  7452. Add the following entry to the list of \code{passes} in
  7453. \code{run-tests.rkt}
  7454. \begin{lstlisting}
  7455. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  7456. \end{lstlisting}
  7457. \fi}
  7458. %
  7459. Run the script to test your compiler on all the test programs.
  7460. \end{exercise}
  7461. \section{Register Allocation}
  7462. \label{sec:register-allocation-Rif}
  7463. \index{subject}{register allocation}
  7464. The changes required for \LangIf{} affect liveness analysis, building the
  7465. interference graph, and assigning homes, but the graph coloring
  7466. algorithm itself does not change.
  7467. \subsection{Liveness Analysis}
  7468. \label{sec:liveness-analysis-Rif}
  7469. \index{subject}{liveness analysis}
  7470. Recall that for \LangVar{} we implemented liveness analysis for a
  7471. single basic block (Section~\ref{sec:liveness-analysis-Rvar}). With
  7472. the addition of \key{if} expressions to \LangIf{},
  7473. \code{explicate\_control} produces many basic blocks.
  7474. %% We recommend that you create a new auxiliary function named
  7475. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7476. %% control-flow graph.
  7477. The first question we is: what order should we process the basic
  7478. blocks? Recall that to perform liveness analysis on a basic block we
  7479. need to know the live-after set for the last instruction in the
  7480. block. If a basic block has no successors (i.e. contains no jumps to
  7481. other blocks), then it has an empty live-after set and we can
  7482. immediately apply liveness analysis to it. If a basic block has some
  7483. successors, then we need to complete liveness analysis on those blocks
  7484. first. These ordering contraints are the reverse of a
  7485. \emph{topological order}\index{subject}{topological order} on the
  7486. control-flow graph of the program~\citep{Allen:1970uq}. In a
  7487. \emph{control flow graph} (CFG), each node represents a \emph{basic
  7488. block} and each edge represents a jump from one block to another
  7489. \index{subject}{control-flow graph}. It is straightforward to
  7490. generate a CFG from the dictionary of basic blocks. One then needs to
  7491. transpose the CFG and apply the topological sort algorithm.
  7492. %
  7493. %
  7494. \racket{We recommend using the \code{tsort} and \code{transpose}
  7495. functions of the Racket \code{graph} package to accomplish this.}
  7496. %
  7497. \python{We provide implementations of \code{topological\_sort} and
  7498. \code{transpose} in the file \code{graph.py} of the support code.}
  7499. %
  7500. As an aside, a topological ordering is only guaranteed to exist if the
  7501. graph does not contain any cycles. That is indeed the case for the
  7502. control-flow graphs that we generate from \LangIf{} programs.
  7503. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  7504. learn how to handle cycles in the control-flow graph.
  7505. \racket{You'll need to construct a directed graph to represent the
  7506. control-flow graph. Do not use the \code{directed-graph} of the
  7507. \code{graph} package because that only allows at most one edge
  7508. between each pair of vertices, but a control-flow graph may have
  7509. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7510. file in the support code implements a graph representation that
  7511. allows multiple edges between a pair of vertices.}
  7512. {\if\edition\racketEd\color{olive}
  7513. The next question is how to analyze jump instructions. Recall that in
  7514. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  7515. \code{label->live} that maps each label to the set of live locations
  7516. at the beginning of its block. We use \code{label->live} to determine
  7517. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7518. that we have many basic blocks, \code{label->live} needs to be updated
  7519. as we process the blocks. In particular, after performing liveness
  7520. analysis on a block, we take the live-before set of its first
  7521. instruction and associate that with the block's label in the
  7522. \code{label->live}.
  7523. \fi}
  7524. %
  7525. {\if\edition\pythonEd
  7526. %
  7527. The next question is how to analyze jump instructions. The locations
  7528. that are live before a \code{jmp} should be the locations in
  7529. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7530. maintaining dictionary named \code{live\_before\_block} that maps each
  7531. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7532. block. After performing liveness analysis on each block, we take the
  7533. live-before set of its first instruction and associate that with the
  7534. block's label in the \code{live\_before\_block} dictionary.
  7535. %
  7536. \fi}
  7537. In \LangXIfVar{} we also have the conditional jump
  7538. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7539. this instruction is particularly interesting because during
  7540. compilation we do not know which way a conditional jump will go. So
  7541. we do not know whether to use the live-before set for the following
  7542. instruction or the live-before set for the block associated with the
  7543. $\itm{label}$. However, there is no harm to the correctness of the
  7544. generated code if we classify more locations as live than the ones
  7545. that are truly live during one particular execution of the
  7546. instruction. Thus, we can take the union of the live-before sets from
  7547. the following instruction and from the mapping for $\itm{label}$ in
  7548. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7549. The auxiliary functions for computing the variables in an
  7550. instruction's argument and for computing the variables read-from ($R$)
  7551. or written-to ($W$) by an instruction need to be updated to handle the
  7552. new kinds of arguments and instructions in \LangXIfVar{}.
  7553. \begin{exercise}\normalfont
  7554. {\if\edition\racketEd\color{olive}
  7555. %
  7556. Update the \code{uncover\_live} pass and implement the
  7557. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  7558. to the control-flow graph.
  7559. %
  7560. Add the following entry to the list of \code{passes} in the
  7561. \code{run-tests.rkt} script.
  7562. \begin{lstlisting}
  7563. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  7564. \end{lstlisting}
  7565. \fi}
  7566. {\if\edition\pythonEd
  7567. %
  7568. Update the \code{uncover\_live} function to perform liveness analysis,
  7569. in reverse topological order, on all of the basic blocks in the
  7570. program.
  7571. %
  7572. \fi}
  7573. % Check that the live-after sets that you generate for
  7574. % example X matches the following... -Jeremy
  7575. \end{exercise}
  7576. \subsection{Build the Interference Graph}
  7577. \label{sec:build-interference-Rif}
  7578. Many of the new instructions in \LangXIfVar{} can be handled in the
  7579. same way as the instructions in \LangXVar{}. Thus, if your code was
  7580. already quite general, it will not need to be changed to handle the
  7581. new instructions. If you code is not general enough, we recommend that
  7582. you change your code to be more general. For example, you can factor
  7583. out the computing of the the read and write sets for each kind of
  7584. instruction into auxiliary functions.
  7585. Note that the \key{movzbq} instruction requires some special care,
  7586. similar to the \key{movq} instruction. See rule number 1 in
  7587. Section~\ref{sec:build-interference}.
  7588. \begin{exercise}\normalfont
  7589. Update the \code{build\_interference} pass for \LangXIfVar{}.
  7590. {\if\edition\racketEd\color{olive}
  7591. Add the following entries to the list of \code{passes} in the
  7592. \code{run-tests.rkt} script.
  7593. \begin{lstlisting}
  7594. (list "build-interference" build-interference interp-pseudo-x86-1)
  7595. (list "allocate-registers" allocate-registers interp-x86-1)
  7596. \end{lstlisting}
  7597. \fi}
  7598. % Check that the interference graph that you generate for
  7599. % example X matches the following graph G... -Jeremy
  7600. \end{exercise}
  7601. \section{Patch Instructions}
  7602. The second argument of the \key{cmpq} instruction must not be an
  7603. immediate value (such as an integer). So if you are comparing two
  7604. immediates, we recommend inserting a \key{movq} instruction to put the
  7605. second argument in \key{rax}. Also, recall that instructions may have
  7606. at most one memory reference.
  7607. %
  7608. The second argument of the \key{movzbq} must be a register.
  7609. %
  7610. There are no special restrictions on the jump instructions.
  7611. \begin{exercise}\normalfont
  7612. %
  7613. Update \code{patch-instructions} pass for \LangXIfVar{}.
  7614. %
  7615. {\if\edition\racketEd\color{olive}
  7616. Add the following entry to the list of \code{passes} in
  7617. \code{run-tests.rkt} and then run this script to test your compiler.
  7618. \begin{lstlisting}
  7619. (list "patch-instructions" patch-instructions interp-x86-1)
  7620. \end{lstlisting}
  7621. \fi}
  7622. \end{exercise}
  7623. \begin{figure}[tbp]
  7624. {\if\edition\racketEd\color{olive}
  7625. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7626. \node (Rif) at (0,2) {\large \LangIf{}};
  7627. \node (Rif-2) at (3,2) {\large \LangIf{}};
  7628. \node (Rif-3) at (6,2) {\large \LangIf{}};
  7629. \node (Rif-4) at (9,2) {\large \LangIf{}};
  7630. \node (Rif-5) at (12,2) {\large \LangIf{}};
  7631. \node (C1-1) at (3,0) {\large \LangCIf{}};
  7632. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  7633. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  7634. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  7635. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  7636. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  7637. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  7638. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  7639. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  7640. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  7641. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  7642. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  7643. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  7644. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7645. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7646. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7647. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  7648. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  7649. \end{tikzpicture}
  7650. \fi}
  7651. {\if\edition\pythonEd
  7652. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7653. \node (Rif-1) at (0,2) {\large \LangIf{}};
  7654. \node (Rif-2) at (3,2) {\large \LangIf{}};
  7655. \node (Rif-3) at (6,2) {\large \LangIf{}};
  7656. \node (Rif-4) at (9,2) {\large \LangIf{}};
  7657. \node (C-1) at (3,0) {\large \LangCIf{}};
  7658. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  7659. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  7660. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  7661. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  7662. \path[->,bend left=15] (Rif-1) edge [above] node {\ttfamily\footnotesize type\_check} (Rif-2);
  7663. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  7664. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rif-4);
  7665. \path[->,bend left=15] (Rif-4) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  7666. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  7667. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  7668. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  7669. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86 } (x86-4);
  7670. \end{tikzpicture}
  7671. \fi}
  7672. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  7673. \label{fig:Rif-passes}
  7674. \end{figure}
  7675. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  7676. compilation of \LangIf{}.
  7677. \section{An Example Translation}
  7678. Figure~\ref{fig:if-example-x86} shows a simple example program in
  7679. \LangIf{} translated to x86, showing the results of
  7680. \code{explicate\_control}, \code{select\_instructions}, and the final
  7681. x86 assembly code.
  7682. \begin{figure}[tbp]
  7683. {\if\edition\racketEd\color{olive}
  7684. \begin{tabular}{lll}
  7685. \begin{minipage}{0.4\textwidth}
  7686. % cond_test_20.rkt, eq_input.py
  7687. \begin{lstlisting}
  7688. (if (eq? (read) 1) 42 0)
  7689. \end{lstlisting}
  7690. $\Downarrow$
  7691. \begin{lstlisting}
  7692. start:
  7693. tmp7951 = (read);
  7694. if (eq? tmp7951 1)
  7695. goto block7952;
  7696. else
  7697. goto block7953;
  7698. block7952:
  7699. return 42;
  7700. block7953:
  7701. return 0;
  7702. \end{lstlisting}
  7703. $\Downarrow$
  7704. \begin{lstlisting}
  7705. start:
  7706. callq read_int
  7707. movq %rax, tmp7951
  7708. cmpq $1, tmp7951
  7709. je block7952
  7710. jmp block7953
  7711. block7953:
  7712. movq $0, %rax
  7713. jmp conclusion
  7714. block7952:
  7715. movq $42, %rax
  7716. jmp conclusion
  7717. \end{lstlisting}
  7718. \end{minipage}
  7719. &
  7720. $\Rightarrow\qquad$
  7721. \begin{minipage}{0.4\textwidth}
  7722. \begin{lstlisting}
  7723. start:
  7724. callq read_int
  7725. movq %rax, %rcx
  7726. cmpq $1, %rcx
  7727. je block7952
  7728. jmp block7953
  7729. block7953:
  7730. movq $0, %rax
  7731. jmp conclusion
  7732. block7952:
  7733. movq $42, %rax
  7734. jmp conclusion
  7735. .globl main
  7736. main:
  7737. pushq %rbp
  7738. movq %rsp, %rbp
  7739. pushq %r13
  7740. pushq %r12
  7741. pushq %rbx
  7742. pushq %r14
  7743. subq $0, %rsp
  7744. jmp start
  7745. conclusion:
  7746. addq $0, %rsp
  7747. popq %r14
  7748. popq %rbx
  7749. popq %r12
  7750. popq %r13
  7751. popq %rbp
  7752. retq
  7753. \end{lstlisting}
  7754. \end{minipage}
  7755. \end{tabular}
  7756. \fi}
  7757. {\if\edition\pythonEd
  7758. \begin{tabular}{lll}
  7759. \begin{minipage}{0.4\textwidth}
  7760. % cond_test_20.rkt, eq_input.py
  7761. \begin{lstlisting}
  7762. print(42 if input_int() == 1 else 0)
  7763. \end{lstlisting}
  7764. $\Downarrow$
  7765. \begin{lstlisting}
  7766. start:
  7767. tmp_0 = input_int()
  7768. if tmp_0 == 1:
  7769. goto block_3
  7770. else:
  7771. goto block_4
  7772. block_3:
  7773. tmp_1 = 42
  7774. goto block_2
  7775. block_4:
  7776. tmp_1 = 0
  7777. goto block_2
  7778. block_2:
  7779. print(tmp_1)
  7780. return 0
  7781. \end{lstlisting}
  7782. $\Downarrow$
  7783. \begin{lstlisting}
  7784. start:
  7785. callq read_int
  7786. movq %rax, tmp_0
  7787. cmpq 1, tmp_0
  7788. je block_3
  7789. jmp block_4
  7790. block_3:
  7791. movq 42, tmp_1
  7792. jmp block_2
  7793. block_4:
  7794. movq 0, tmp_1
  7795. jmp block_2
  7796. block_2:
  7797. movq tmp_1, %rdi
  7798. callq print_int
  7799. movq 0, %rax
  7800. jmp conclusion
  7801. \end{lstlisting}
  7802. \end{minipage}
  7803. &
  7804. $\Rightarrow\qquad$
  7805. \begin{minipage}{0.4\textwidth}
  7806. \begin{lstlisting}
  7807. .globl main
  7808. main:
  7809. pushq %rbp
  7810. movq %rsp, %rbp
  7811. subq $0, %rsp
  7812. jmp start
  7813. start:
  7814. callq read_int
  7815. movq %rax, %rcx
  7816. cmpq $1, %rcx
  7817. je block_3
  7818. jmp block_4
  7819. block_3:
  7820. movq $42, %rcx
  7821. jmp block_2
  7822. block_4:
  7823. movq $0, %rcx
  7824. jmp block_2
  7825. block_2:
  7826. movq %rcx, %rdi
  7827. callq print_int
  7828. movq $0, %rax
  7829. jmp conclusion
  7830. conclusion:
  7831. addq $0, %rsp
  7832. popq %rbp
  7833. retq
  7834. \end{lstlisting}
  7835. \end{minipage}
  7836. \end{tabular}
  7837. \fi}
  7838. \caption{Example compilation of an \key{if} expression to x86, showing
  7839. the results of \code{explicate\_control},
  7840. \code{select\_instructions}, and the final x86 assembly code. }
  7841. \label{fig:if-example-x86}
  7842. \end{figure}
  7843. \section{Challenge: Optimize Blocks and Remove Jumps}
  7844. \label{sec:opt-jumps}
  7845. We discuss two challenges that involve optimizing the control-flow of
  7846. the program.
  7847. \subsection{Optimize Blocks}
  7848. The algorithm for \code{explicate\_control} that we sketched in
  7849. Section~\ref{sec:explicate-control-Rif} sometimes generates too many
  7850. blocks. It does so in two different ways.
  7851. %
  7852. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  7853. \code{block\_4} consists of just a jump to \code{block\_2}. What's
  7854. going on here is that we created a new basic block from a single
  7855. \code{goto} statement, whereas we could have simply returned the
  7856. \code{goto} statement. We can solve this problem by modifying the
  7857. \code{create\_block} function to recognize this situation.
  7858. %
  7859. Second, \code{explicate\_control} creates a basic block whenever a
  7860. continuation \emph{might} get used more than once (wheneven a
  7861. continuation is passed it into two or more recursive calls). However,
  7862. just because a continuation might get used more than once, doesn't
  7863. mean it will. In fact, some continuation parameters may not be used
  7864. at all because we sometimes ignore them. For example, consider the
  7865. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  7866. discard the \code{els} branch. So the question is how can we decide
  7867. whether to create a basic block?
  7868. The solution to this conundrum is to use \emph{lazy
  7869. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  7870. to delay creating a basic block until the point in time where we know
  7871. it will be used.
  7872. %
  7873. {\if\edition\racketEd\color{olive}
  7874. %
  7875. Racket provides support for
  7876. lazy evaluation with the
  7877. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  7878. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  7879. \index{subject}{delay} creates a
  7880. \emph{promise}\index{subject}{promise} in which the evaluation of the
  7881. expressions is postponed. When \key{(force}
  7882. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  7883. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  7884. result of $e_n$ is cached in the promise and returned. If \code{force}
  7885. is applied again to the same promise, then the cached result is
  7886. returned. If \code{force} is applied to an argument that is not a
  7887. promise, \code{force} simply returns the argument.
  7888. %
  7889. \fi}
  7890. %
  7891. {\if\edition\pythonEd
  7892. %
  7893. While Python does not provide direct support for lazy evaluation, it
  7894. is easy to mimic. We can \emph{delay} the evaluation of a computation
  7895. by wrapping it inside a function with no parameters. We can
  7896. \emph{force} its evaluation by calling the function. However, in some
  7897. cases of \code{explicate\_pred}, etc., we will return a list of
  7898. statements and in other cases we will return a function that computes
  7899. a list of statement. We use the term \emph{promise} to refer to either
  7900. a list of statements or a function. To uniformly deal with promises,
  7901. we define the following \code{force} function that checks whether its
  7902. input is a function and then either 1) calls the function, or 2)
  7903. returns the input.
  7904. \begin{lstlisting}
  7905. def force(promise):
  7906. if isinstance(promise, types.FunctionType):
  7907. return promise()
  7908. else:
  7909. return promise
  7910. \end{lstlisting}
  7911. %
  7912. \fi}
  7913. We use promises for the input and output of the functions
  7914. \code{explicate\_pred}, \code{explicate\_assign},
  7915. %
  7916. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  7917. %
  7918. So instead of taking and returning lists of statments, they take and
  7919. return promises. Furthermore, when we come to a situation in which a
  7920. continuation might be used more than once, as in the case for
  7921. \code{if} in \code{explicate\_pred}, we create a delayed computation
  7922. that creates a basic block for the continuations (if there is not
  7923. already one) and then returns a \code{goto} statement to that basic
  7924. block.
  7925. %
  7926. {\if\edition\racketEd\color{olive}
  7927. %
  7928. The following auxiliary function named \code{block->goto} accomplishes
  7929. this task. It begins with \code{delay} to create a promise. When
  7930. forced, this promise will force the original promise. If that returns
  7931. a \code{goto} (because the block was already added to the control-flow
  7932. graph), then we return the \code{goto}. Otherwise we add the block to
  7933. the control-flow graph with another auxiliary function named
  7934. \code{add-node}. That function returns the label for the new block,
  7935. which we use to create a \code{goto}.
  7936. \begin{lstlisting}
  7937. (define (block->goto block)
  7938. (delay
  7939. (define b (force block))
  7940. (match b
  7941. [(Goto label) (Goto label)]
  7942. [else (Goto (add-node b))])))
  7943. \end{lstlisting}
  7944. \fi}
  7945. {\if\edition\pythonEd
  7946. %
  7947. Here's the new version of the \code{create\_block} auxiliary function
  7948. that works on promises and that checks whether the block consists of a
  7949. solitary \code{goto} statement.\\
  7950. \begin{minipage}{\textwidth}
  7951. \begin{lstlisting}
  7952. def create_block(promise, basic_blocks):
  7953. stmts = force(promise)
  7954. match stmts:
  7955. case [Goto(l)]:
  7956. return Goto(l)
  7957. case _:
  7958. label = label_name(generate_name('block'))
  7959. basic_blocks[label] = stmts
  7960. return Goto(label)
  7961. \end{lstlisting}
  7962. \end{minipage}
  7963. \fi}
  7964. Figure~\ref{fig:explicate-control-challenge} shows the output of
  7965. \code{explicate\_control} on the example of the nested \code{if}
  7966. expressions with the two improvements discussed above. As you can
  7967. see, the number of basic blocks has been reduced from 10 blocks (see
  7968. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  7969. \begin{figure}[tbp]
  7970. {\if\edition\racketEd\color{olive}
  7971. \begin{tabular}{lll}
  7972. \begin{minipage}{0.4\textwidth}
  7973. % cond_test_41.rkt
  7974. \begin{lstlisting}
  7975. (let ([x (read)])
  7976. (let ([y (read)])
  7977. (if (if (< x 1)
  7978. (eq? x 0)
  7979. (eq? x 2))
  7980. (+ y 2)
  7981. (+ y 10))))
  7982. \end{lstlisting}
  7983. \end{minipage}
  7984. &
  7985. $\Rightarrow$
  7986. &
  7987. \begin{minipage}{0.55\textwidth}
  7988. \begin{lstlisting}
  7989. start:
  7990. x = (read);
  7991. y = (read);
  7992. if (< x 1) goto block40;
  7993. else goto block41;
  7994. block40:
  7995. if (eq? x 0) goto block38;
  7996. else goto block39;
  7997. block41:
  7998. if (eq? x 2) goto block38;
  7999. else goto block39;
  8000. block38:
  8001. return (+ y 2);
  8002. block39:
  8003. return (+ y 10);
  8004. \end{lstlisting}
  8005. \end{minipage}
  8006. \end{tabular}
  8007. \fi}
  8008. {\if\edition\pythonEd
  8009. \begin{tabular}{lll}
  8010. \begin{minipage}{0.4\textwidth}
  8011. % cond_test_41.rkt
  8012. \begin{lstlisting}
  8013. x = input_int()
  8014. y = input_int()
  8015. print(y + 2 \
  8016. if (x == 0 \
  8017. if x < 1 \
  8018. else x == 2) \
  8019. else y + 10)
  8020. \end{lstlisting}
  8021. \end{minipage}
  8022. &
  8023. $\Rightarrow$
  8024. &
  8025. \begin{minipage}{0.55\textwidth}
  8026. \begin{lstlisting}
  8027. start:
  8028. x = input_int()
  8029. y = input_int()
  8030. if x < 1:
  8031. goto block_4
  8032. else:
  8033. goto block_5
  8034. block_4:
  8035. if x == 0:
  8036. goto block_2
  8037. else:
  8038. goto block_3
  8039. block_5:
  8040. if x == 2:
  8041. goto block_2
  8042. else:
  8043. goto block_3
  8044. block_2:
  8045. tmp_0 = y + 2
  8046. goto block_1
  8047. block_3:
  8048. tmp_0 = y + 10
  8049. goto block_1
  8050. block_1:
  8051. print(tmp_0)
  8052. return 0
  8053. \end{lstlisting}
  8054. \end{minipage}
  8055. \end{tabular}
  8056. \fi}
  8057. \caption{Translation from \LangIf{} to \LangCIf{}
  8058. via the improved \code{explicate\_control}.}
  8059. \label{fig:explicate-control-challenge}
  8060. \end{figure}
  8061. %% Recall that in the example output of \code{explicate\_control} in
  8062. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8063. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8064. %% block. The first goal of this challenge assignment is to remove those
  8065. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8066. %% \code{explicate\_control} on the left and shows the result of bypassing
  8067. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8068. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8069. %% \code{block55}. The optimized code on the right of
  8070. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8071. %% \code{then} branch jumping directly to \code{block55}. The story is
  8072. %% similar for the \code{else} branch, as well as for the two branches in
  8073. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8074. %% have been optimized in this way, there are no longer any jumps to
  8075. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8076. %% \begin{figure}[tbp]
  8077. %% \begin{tabular}{lll}
  8078. %% \begin{minipage}{0.4\textwidth}
  8079. %% \begin{lstlisting}
  8080. %% block62:
  8081. %% tmp54 = (read);
  8082. %% if (eq? tmp54 2) then
  8083. %% goto block59;
  8084. %% else
  8085. %% goto block60;
  8086. %% block61:
  8087. %% tmp53 = (read);
  8088. %% if (eq? tmp53 0) then
  8089. %% goto block57;
  8090. %% else
  8091. %% goto block58;
  8092. %% block60:
  8093. %% goto block56;
  8094. %% block59:
  8095. %% goto block55;
  8096. %% block58:
  8097. %% goto block56;
  8098. %% block57:
  8099. %% goto block55;
  8100. %% block56:
  8101. %% return (+ 700 77);
  8102. %% block55:
  8103. %% return (+ 10 32);
  8104. %% start:
  8105. %% tmp52 = (read);
  8106. %% if (eq? tmp52 1) then
  8107. %% goto block61;
  8108. %% else
  8109. %% goto block62;
  8110. %% \end{lstlisting}
  8111. %% \end{minipage}
  8112. %% &
  8113. %% $\Rightarrow$
  8114. %% &
  8115. %% \begin{minipage}{0.55\textwidth}
  8116. %% \begin{lstlisting}
  8117. %% block62:
  8118. %% tmp54 = (read);
  8119. %% if (eq? tmp54 2) then
  8120. %% goto block55;
  8121. %% else
  8122. %% goto block56;
  8123. %% block61:
  8124. %% tmp53 = (read);
  8125. %% if (eq? tmp53 0) then
  8126. %% goto block55;
  8127. %% else
  8128. %% goto block56;
  8129. %% block56:
  8130. %% return (+ 700 77);
  8131. %% block55:
  8132. %% return (+ 10 32);
  8133. %% start:
  8134. %% tmp52 = (read);
  8135. %% if (eq? tmp52 1) then
  8136. %% goto block61;
  8137. %% else
  8138. %% goto block62;
  8139. %% \end{lstlisting}
  8140. %% \end{minipage}
  8141. %% \end{tabular}
  8142. %% \caption{Optimize jumps by removing trivial blocks.}
  8143. %% \label{fig:optimize-jumps}
  8144. %% \end{figure}
  8145. %% The name of this pass is \code{optimize-jumps}. We recommend
  8146. %% implementing this pass in two phases. The first phrase builds a hash
  8147. %% table that maps labels to possibly improved labels. The second phase
  8148. %% changes the target of each \code{goto} to use the improved label. If
  8149. %% the label is for a trivial block, then the hash table should map the
  8150. %% label to the first non-trivial block that can be reached from this
  8151. %% label by jumping through trivial blocks. If the label is for a
  8152. %% non-trivial block, then the hash table should map the label to itself;
  8153. %% we do not want to change jumps to non-trivial blocks.
  8154. %% The first phase can be accomplished by constructing an empty hash
  8155. %% table, call it \code{short-cut}, and then iterating over the control
  8156. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8157. %% then update the hash table, mapping the block's source to the target
  8158. %% of the \code{goto}. Also, the hash table may already have mapped some
  8159. %% labels to the block's source, to you must iterate through the hash
  8160. %% table and update all of those so that they instead map to the target
  8161. %% of the \code{goto}.
  8162. %% For the second phase, we recommend iterating through the $\Tail$ of
  8163. %% each block in the program, updating the target of every \code{goto}
  8164. %% according to the mapping in \code{short-cut}.
  8165. \begin{exercise}\normalfont
  8166. Implement the improvements to the \code{explicate\_control} pass.
  8167. Check that it removes trivial blocks in a few example programs. Then
  8168. check that your compiler still passes all of your tests.
  8169. \end{exercise}
  8170. \subsection{Remove Jumps}
  8171. There is an opportunity for removing jumps that is apparent in the
  8172. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8173. ends with a jump to \code{block\_4} and there are no other jumps to
  8174. \code{block\_4} in the rest of the program. In this situation we can
  8175. avoid the runtime overhead of this jump by merging \code{block\_4}
  8176. into the preceding block, in this case the \code{start} block.
  8177. Figure~\ref{fig:remove-jumps} shows the output of
  8178. \code{select\_instructions} on the left and the result of this
  8179. optimization on the right.
  8180. \begin{figure}[tbp]
  8181. {\if\edition\racketEd\color{olive}
  8182. \begin{tabular}{lll}
  8183. \begin{minipage}{0.5\textwidth}
  8184. % cond_test_20.rkt
  8185. \begin{lstlisting}
  8186. start:
  8187. callq read_int
  8188. movq %rax, tmp7951
  8189. cmpq $1, tmp7951
  8190. je block7952
  8191. jmp block7953
  8192. block7953:
  8193. movq $0, %rax
  8194. jmp conclusion
  8195. block7952:
  8196. movq $42, %rax
  8197. jmp conclusion
  8198. \end{lstlisting}
  8199. \end{minipage}
  8200. &
  8201. $\Rightarrow\qquad$
  8202. \begin{minipage}{0.4\textwidth}
  8203. \begin{lstlisting}
  8204. start:
  8205. callq read_int
  8206. movq %rax, tmp7951
  8207. cmpq $1, tmp7951
  8208. je block7952
  8209. movq $0, %rax
  8210. jmp conclusion
  8211. block7952:
  8212. movq $42, %rax
  8213. jmp conclusion
  8214. \end{lstlisting}
  8215. \end{minipage}
  8216. \end{tabular}
  8217. \fi}
  8218. {\if\edition\pythonEd
  8219. \begin{tabular}{lll}
  8220. \begin{minipage}{0.5\textwidth}
  8221. % cond_test_20.rkt
  8222. \begin{lstlisting}
  8223. start:
  8224. callq read_int
  8225. movq %rax, tmp_0
  8226. cmpq 1, tmp_0
  8227. je block_3
  8228. jmp block_4
  8229. block_3:
  8230. movq 42, tmp_1
  8231. jmp block_2
  8232. block_4:
  8233. movq 0, tmp_1
  8234. jmp block_2
  8235. block_2:
  8236. movq tmp_1, %rdi
  8237. callq print_int
  8238. movq 0, %rax
  8239. jmp conclusion
  8240. \end{lstlisting}
  8241. \end{minipage}
  8242. &
  8243. $\Rightarrow\qquad$
  8244. \begin{minipage}{0.4\textwidth}
  8245. \begin{lstlisting}
  8246. start:
  8247. callq read_int
  8248. movq %rax, tmp_0
  8249. cmpq 1, tmp_0
  8250. je block_3
  8251. movq 0, tmp_1
  8252. jmp block_2
  8253. block_3:
  8254. movq 42, tmp_1
  8255. jmp block_2
  8256. block_2:
  8257. movq tmp_1, %rdi
  8258. callq print_int
  8259. movq 0, %rax
  8260. jmp conclusion
  8261. \end{lstlisting}
  8262. \end{minipage}
  8263. \end{tabular}
  8264. \fi}
  8265. \caption{Merging basic blocks by removing unnecessary jumps.}
  8266. \label{fig:remove-jumps}
  8267. \end{figure}
  8268. \begin{exercise}\normalfont
  8269. %
  8270. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8271. into their preceding basic block, when there is only one preceding
  8272. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8273. %
  8274. {\if\edition\racketEd\color{olive}
  8275. In the \code{run-tests.rkt} script, add the following entry to the
  8276. list of \code{passes} between \code{allocate-registers}
  8277. and \code{patch-instructions}.
  8278. \begin{lstlisting}
  8279. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8280. \end{lstlisting}
  8281. \fi}
  8282. %
  8283. Run the script to test your compiler.
  8284. %
  8285. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8286. blocks on several test programs.
  8287. \end{exercise}
  8288. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8289. \chapter{Loops and Dataflow Analysis}
  8290. \label{ch:Rwhile}
  8291. % TODO: define R'_8
  8292. % TODO: multi-graph
  8293. \if\edition\racketEd
  8294. In this chapter we study two features that are the hallmarks of
  8295. imperative programming languages: loops and assignments to local
  8296. variables. The following example demonstrates these new features by
  8297. computing the sum of the first five positive integers.
  8298. % similar to loop_test_1.rkt
  8299. \begin{lstlisting}
  8300. (let ([sum 0])
  8301. (let ([i 5])
  8302. (begin
  8303. (while (> i 0)
  8304. (begin
  8305. (set! sum (+ sum i))
  8306. (set! i (- i 1))))
  8307. sum)))
  8308. \end{lstlisting}
  8309. The \code{while} loop consists of a condition and a body.
  8310. %
  8311. The \code{set!} consists of a variable and a right-hand-side expression.
  8312. %
  8313. The primary purpose of both the \code{while} loop and \code{set!} is
  8314. to cause side effects, so it is convenient to also include in a
  8315. language feature for sequencing side effects: the \code{begin}
  8316. expression. It consists of one or more subexpressions that are
  8317. evaluated left-to-right.
  8318. \section{The \LangLoop{} Language}
  8319. \begin{figure}[tp]
  8320. \centering
  8321. \fbox{
  8322. \begin{minipage}{0.96\textwidth}
  8323. \small
  8324. \[
  8325. \begin{array}{lcl}
  8326. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  8327. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8328. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8329. &\MID& \gray{\key{\#t} \MID \key{\#f}
  8330. \MID (\key{and}\;\Exp\;\Exp)
  8331. \MID (\key{or}\;\Exp\;\Exp)
  8332. \MID (\key{not}\;\Exp) } \\
  8333. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8334. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  8335. (\key{vector-ref}\;\Exp\;\Int)} \\
  8336. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  8337. \MID (\Exp \; \Exp\ldots) } \\
  8338. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  8339. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  8340. &\MID& \CSETBANG{\Var}{\Exp}
  8341. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8342. \MID \CWHILE{\Exp}{\Exp} \\
  8343. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8344. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  8345. \end{array}
  8346. \]
  8347. \end{minipage}
  8348. }
  8349. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  8350. \label{fig:Rwhile-concrete-syntax}
  8351. \end{figure}
  8352. \begin{figure}[tp]
  8353. \centering
  8354. \fbox{
  8355. \begin{minipage}{0.96\textwidth}
  8356. \small
  8357. \[
  8358. \begin{array}{lcl}
  8359. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8360. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8361. &\MID& \gray{ \BOOL{\itm{bool}}
  8362. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8363. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  8364. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  8365. &\MID& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  8366. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8367. \MID \WHILE{\Exp}{\Exp} \\
  8368. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8369. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8370. \end{array}
  8371. \]
  8372. \end{minipage}
  8373. }
  8374. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  8375. \label{fig:Rwhile-syntax}
  8376. \end{figure}
  8377. The concrete syntax of \LangLoop{} is defined in
  8378. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  8379. in Figure~\ref{fig:Rwhile-syntax}.
  8380. %
  8381. The definitional interpreter for \LangLoop{} is shown in
  8382. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  8383. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  8384. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  8385. support assignment to variables and to make their lifetimes indefinite
  8386. (see the second example in Section~\ref{sec:assignment-scoping}), we
  8387. box the value that is bound to each variable (in \code{Let}) and
  8388. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  8389. the value.
  8390. %
  8391. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8392. variable in the environment to obtain a boxed value and then we change
  8393. it using \code{set-box!} to the result of evaluating the right-hand
  8394. side. The result value of a \code{SetBang} is \code{void}.
  8395. %
  8396. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8397. if the result is true, 2) evaluate the body.
  8398. The result value of a \code{while} loop is also \code{void}.
  8399. %
  8400. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8401. subexpressions \itm{es} for their effects and then evaluates
  8402. and returns the result from \itm{body}.
  8403. \begin{figure}[tbp]
  8404. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8405. (define interp-Rwhile_class
  8406. (class interp-Rany_class
  8407. (super-new)
  8408. (define/override ((interp-exp env) e)
  8409. (define recur (interp-exp env))
  8410. (match e
  8411. [(SetBang x rhs)
  8412. (set-box! (lookup x env) (recur rhs))]
  8413. [(WhileLoop cnd body)
  8414. (define (loop)
  8415. (cond [(recur cnd) (recur body) (loop)]
  8416. [else (void)]))
  8417. (loop)]
  8418. [(Begin es body)
  8419. (for ([e es]) (recur e))
  8420. (recur body)]
  8421. [else ((super interp-exp env) e)]))
  8422. ))
  8423. (define (interp-Rwhile p)
  8424. (send (new interp-Rwhile_class) interp-program p))
  8425. \end{lstlisting}
  8426. \caption{Interpreter for \LangLoop{}.}
  8427. \label{fig:interp-Rwhile}
  8428. \end{figure}
  8429. The type checker for \LangLoop{} is define in
  8430. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  8431. variable and the right-hand-side must agree. The result type is
  8432. \code{Void}. For the \code{WhileLoop}, the condition must be a
  8433. \code{Boolean}. The result type is also \code{Void}. For
  8434. \code{Begin}, the result type is the type of its last subexpression.
  8435. \begin{figure}[tbp]
  8436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8437. (define type-check-Rwhile_class
  8438. (class type-check-Rany_class
  8439. (super-new)
  8440. (inherit check-type-equal?)
  8441. (define/override (type-check-exp env)
  8442. (lambda (e)
  8443. (define recur (type-check-exp env))
  8444. (match e
  8445. [(SetBang x rhs)
  8446. (define-values (rhs^ rhsT) (recur rhs))
  8447. (define varT (dict-ref env x))
  8448. (check-type-equal? rhsT varT e)
  8449. (values (SetBang x rhs^) 'Void)]
  8450. [(WhileLoop cnd body)
  8451. (define-values (cnd^ Tc) (recur cnd))
  8452. (check-type-equal? Tc 'Boolean e)
  8453. (define-values (body^ Tbody) ((type-check-exp env) body))
  8454. (values (WhileLoop cnd^ body^) 'Void)]
  8455. [(Begin es body)
  8456. (define-values (es^ ts)
  8457. (for/lists (l1 l2) ([e es]) (recur e)))
  8458. (define-values (body^ Tbody) (recur body))
  8459. (values (Begin es^ body^) Tbody)]
  8460. [else ((super type-check-exp env) e)])))
  8461. ))
  8462. (define (type-check-Rwhile p)
  8463. (send (new type-check-Rwhile_class) type-check-program p))
  8464. \end{lstlisting}
  8465. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  8466. and \code{Begin} in \LangLoop{}.}
  8467. \label{fig:type-check-Rwhile}
  8468. \end{figure}
  8469. At first glance, the translation of these language features to x86
  8470. seems straightforward because the \LangCFun{} intermediate language already
  8471. supports all of the ingredients that we need: assignment, \code{goto},
  8472. conditional branching, and sequencing. However, there are two
  8473. complications that arise which we discuss in the next two
  8474. sections. After that we introduce one new compiler pass and the
  8475. changes necessary to the existing passes.
  8476. \section{Assignment and Lexically Scoped Functions}
  8477. \label{sec:assignment-scoping}
  8478. The addition of assignment raises a problem with our approach to
  8479. implementing lexically-scoped functions. Consider the following
  8480. example in which function \code{f} has a free variable \code{x} that
  8481. is changed after \code{f} is created but before the call to \code{f}.
  8482. % loop_test_11.rkt
  8483. \begin{lstlisting}
  8484. (let ([x 0])
  8485. (let ([y 0])
  8486. (let ([z 20])
  8487. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  8488. (begin
  8489. (set! x 10)
  8490. (set! y 12)
  8491. (f y))))))
  8492. \end{lstlisting}
  8493. The correct output for this example is \code{42} because the call to
  8494. \code{f} is required to use the current value of \code{x} (which is
  8495. \code{10}). Unfortunately, the closure conversion pass
  8496. (Section~\ref{sec:closure-conversion}) generates code for the
  8497. \code{lambda} that copies the old value of \code{x} into a
  8498. closure. Thus, if we naively add support for assignment to our current
  8499. compiler, the output of this program would be \code{32}.
  8500. A first attempt at solving this problem would be to save a pointer to
  8501. \code{x} in the closure and change the occurrences of \code{x} inside
  8502. the lambda to dereference the pointer. Of course, this would require
  8503. assigning \code{x} to the stack and not to a register. However, the
  8504. problem goes a bit deeper. Consider the following example in which we
  8505. create a counter abstraction by creating a pair of functions that
  8506. share the free variable \code{x}.
  8507. % similar to loop_test_10.rkt
  8508. \begin{lstlisting}
  8509. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  8510. (vector
  8511. (lambda: () : Integer x)
  8512. (lambda: () : Void (set! x (+ 1 x)))))
  8513. (let ([counter (f 0)])
  8514. (let ([get (vector-ref counter 0)])
  8515. (let ([inc (vector-ref counter 1)])
  8516. (begin
  8517. (inc)
  8518. (get)))))
  8519. \end{lstlisting}
  8520. In this example, the lifetime of \code{x} extends beyond the lifetime
  8521. of the call to \code{f}. Thus, if we were to store \code{x} on the
  8522. stack frame for the call to \code{f}, it would be gone by the time we
  8523. call \code{inc} and \code{get}, leaving us with dangling pointers for
  8524. \code{x}. This example demonstrates that when a variable occurs free
  8525. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  8526. value of the variable needs to live on the heap. The verb ``box'' is
  8527. often used for allocating a single value on the heap, producing a
  8528. pointer, and ``unbox'' for dereferencing the pointer.
  8529. We recommend solving these problems by ``boxing'' the local variables
  8530. that are in the intersection of 1) variables that appear on the
  8531. left-hand-side of a \code{set!} and 2) variables that occur free
  8532. inside a \code{lambda}. We shall introduce a new pass named
  8533. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  8534. perform this translation. But before diving into the compiler passes,
  8535. we one more problem to discuss.
  8536. \section{Cyclic Control Flow and Dataflow Analysis}
  8537. \label{sec:dataflow-analysis}
  8538. Up until this point the control-flow graphs generated in
  8539. \code{explicate\_control} were guaranteed to be acyclic. However, each
  8540. \code{while} loop introduces a cycle in the control-flow graph.
  8541. But does that matter?
  8542. %
  8543. Indeed it does. Recall that for register allocation, the compiler
  8544. performs liveness analysis to determine which variables can share the
  8545. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  8546. the control-flow graph in reverse topological order, but topological
  8547. order is only well-defined for acyclic graphs.
  8548. Let us return to the example of computing the sum of the first five
  8549. positive integers. Here is the program after instruction selection but
  8550. before register allocation.
  8551. \begin{center}
  8552. \begin{minipage}{0.45\textwidth}
  8553. \begin{lstlisting}
  8554. (define (main) : Integer
  8555. mainstart:
  8556. movq $0, sum1
  8557. movq $5, i2
  8558. jmp block5
  8559. block5:
  8560. movq i2, tmp3
  8561. cmpq tmp3, $0
  8562. jl block7
  8563. jmp block8
  8564. \end{lstlisting}
  8565. \end{minipage}
  8566. \begin{minipage}{0.45\textwidth}
  8567. \begin{lstlisting}
  8568. block7:
  8569. addq i2, sum1
  8570. movq $1, tmp4
  8571. negq tmp4
  8572. addq tmp4, i2
  8573. jmp block5
  8574. block8:
  8575. movq $27, %rax
  8576. addq sum1, %rax
  8577. jmp mainconclusion
  8578. )
  8579. \end{lstlisting}
  8580. \end{minipage}
  8581. \end{center}
  8582. Recall that liveness analysis works backwards, starting at the end
  8583. of each function. For this example we could start with \code{block8}
  8584. because we know what is live at the beginning of the conclusion,
  8585. just \code{rax} and \code{rsp}. So the live-before set
  8586. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  8587. %
  8588. Next we might try to analyze \code{block5} or \code{block7}, but
  8589. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  8590. we are stuck.
  8591. The way out of this impasse comes from the realization that one can
  8592. perform liveness analysis starting with an empty live-after set to
  8593. compute an under-approximation of the live-before set. By
  8594. \emph{under-approximation}, we mean that the set only contains
  8595. variables that are really live, but it may be missing some. Next, the
  8596. under-approximations for each block can be improved by 1) updating the
  8597. live-after set for each block using the approximate live-before sets
  8598. from the other blocks and 2) perform liveness analysis again on each
  8599. block. In fact, by iterating this process, the under-approximations
  8600. eventually become the correct solutions!
  8601. %
  8602. This approach of iteratively analyzing a control-flow graph is
  8603. applicable to many static analysis problems and goes by the name
  8604. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  8605. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  8606. Washington.
  8607. Let us apply this approach to the above example. We use the empty set
  8608. for the initial live-before set for each block. Let $m_0$ be the
  8609. following mapping from label names to sets of locations (variables and
  8610. registers).
  8611. \begin{center}
  8612. \begin{lstlisting}
  8613. mainstart: {}
  8614. block5: {}
  8615. block7: {}
  8616. block8: {}
  8617. \end{lstlisting}
  8618. \end{center}
  8619. Using the above live-before approximations, we determine the
  8620. live-after for each block and then apply liveness analysis to each
  8621. block. This produces our next approximation $m_1$ of the live-before
  8622. sets.
  8623. \begin{center}
  8624. \begin{lstlisting}
  8625. mainstart: {}
  8626. block5: {i2}
  8627. block7: {i2, sum1}
  8628. block8: {rsp, sum1}
  8629. \end{lstlisting}
  8630. \end{center}
  8631. For the second round, the live-after for \code{mainstart} is the
  8632. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  8633. liveness analysis for \code{mainstart} computes the empty set. The
  8634. live-after for \code{block5} is the union of the live-before sets for
  8635. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  8636. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  8637. sum1\}}. The live-after for \code{block7} is the live-before for
  8638. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  8639. So the liveness analysis for \code{block7} remains \code{\{i2,
  8640. sum1\}}. Together these yield the following approximation $m_2$ of
  8641. the live-before sets.
  8642. \begin{center}
  8643. \begin{lstlisting}
  8644. mainstart: {}
  8645. block5: {i2, rsp, sum1}
  8646. block7: {i2, sum1}
  8647. block8: {rsp, sum1}
  8648. \end{lstlisting}
  8649. \end{center}
  8650. In the preceding iteration, only \code{block5} changed, so we can
  8651. limit our attention to \code{mainstart} and \code{block7}, the two
  8652. blocks that jump to \code{block5}. As a result, the live-before sets
  8653. for \code{mainstart} and \code{block7} are updated to include
  8654. \code{rsp}, yielding the following approximation $m_3$.
  8655. \begin{center}
  8656. \begin{lstlisting}
  8657. mainstart: {rsp}
  8658. block5: {i2, rsp, sum1}
  8659. block7: {i2, rsp, sum1}
  8660. block8: {rsp, sum1}
  8661. \end{lstlisting}
  8662. \end{center}
  8663. Because \code{block7} changed, we analyze \code{block5} once more, but
  8664. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  8665. our approximations have converged, so $m_3$ is the solution.
  8666. This iteration process is guaranteed to converge to a solution by the
  8667. Kleene Fixed-Point Theorem, a general theorem about functions on
  8668. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  8669. any collection that comes with a partial ordering $\sqsubseteq$ on its
  8670. elements, a least element $\bot$ (pronounced bottom), and a join
  8671. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  8672. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  8673. working with join semi-lattices.} When two elements are ordered $m_i
  8674. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  8675. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  8676. approximation than $m_i$. The bottom element $\bot$ represents the
  8677. complete lack of information, i.e., the worst approximation. The join
  8678. operator takes two lattice elements and combines their information,
  8679. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  8680. bound}
  8681. A dataflow analysis typically involves two lattices: one lattice to
  8682. represent abstract states and another lattice that aggregates the
  8683. abstract states of all the blocks in the control-flow graph. For
  8684. liveness analysis, an abstract state is a set of locations. We form
  8685. the lattice $L$ by taking its elements to be sets of locations, the
  8686. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  8687. set, and the join operator to be set union.
  8688. %
  8689. We form a second lattice $M$ by taking its elements to be mappings
  8690. from the block labels to sets of locations (elements of $L$). We
  8691. order the mappings point-wise, using the ordering of $L$. So given any
  8692. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  8693. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  8694. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  8695. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  8696. We can think of one iteration of liveness analysis as being a function
  8697. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  8698. mapping.
  8699. \[
  8700. f(m_i) = m_{i+1}
  8701. \]
  8702. Next let us think for a moment about what a final solution $m_s$
  8703. should look like. If we perform liveness analysis using the solution
  8704. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  8705. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  8706. \[
  8707. f(m_s) = m_s
  8708. \]
  8709. Furthermore, the solution should only include locations that are
  8710. forced to be there by performing liveness analysis on the program, so
  8711. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  8712. The Kleene Fixed-Point Theorem states that if a function $f$ is
  8713. monotone (better inputs produce better outputs), then the least fixed
  8714. point of $f$ is the least upper bound of the \emph{ascending Kleene
  8715. chain} obtained by starting at $\bot$ and iterating $f$ as
  8716. follows.\index{subject}{Kleene Fixed-Point Theorem}
  8717. \[
  8718. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8719. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  8720. \]
  8721. When a lattice contains only finitely-long ascending chains, then
  8722. every Kleene chain tops out at some fixed point after a number of
  8723. iterations of $f$. So that fixed point is also a least upper
  8724. bound of the chain.
  8725. \[
  8726. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8727. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  8728. \]
  8729. The liveness analysis is indeed a monotone function and the lattice
  8730. $M$ only has finitely-long ascending chains because there are only a
  8731. finite number of variables and blocks in the program. Thus we are
  8732. guaranteed that iteratively applying liveness analysis to all blocks
  8733. in the program will eventually produce the least fixed point solution.
  8734. Next let us consider dataflow analysis in general and discuss the
  8735. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  8736. %
  8737. The algorithm has four parameters: the control-flow graph \code{G}, a
  8738. function \code{transfer} that applies the analysis to one block, the
  8739. \code{bottom} and \code{join} operator for the lattice of abstract
  8740. states. The algorithm begins by creating the bottom mapping,
  8741. represented by a hash table. It then pushes all of the nodes in the
  8742. control-flow graph onto the work list (a queue). The algorithm repeats
  8743. the \code{while} loop as long as there are items in the work list. In
  8744. each iteration, a node is popped from the work list and processed. The
  8745. \code{input} for the node is computed by taking the join of the
  8746. abstract states of all the predecessor nodes. The \code{transfer}
  8747. function is then applied to obtain the \code{output} abstract
  8748. state. If the output differs from the previous state for this block,
  8749. the mapping for this block is updated and its successor nodes are
  8750. pushed onto the work list.
  8751. \begin{figure}[tb]
  8752. \begin{lstlisting}
  8753. (define (analyze-dataflow G transfer bottom join)
  8754. (define mapping (make-hash))
  8755. (for ([v (in-vertices G)])
  8756. (dict-set! mapping v bottom))
  8757. (define worklist (make-queue))
  8758. (for ([v (in-vertices G)])
  8759. (enqueue! worklist v))
  8760. (define trans-G (transpose G))
  8761. (while (not (queue-empty? worklist))
  8762. (define node (dequeue! worklist))
  8763. (define input (for/fold ([state bottom])
  8764. ([pred (in-neighbors trans-G node)])
  8765. (join state (dict-ref mapping pred))))
  8766. (define output (transfer node input))
  8767. (cond [(not (equal? output (dict-ref mapping node)))
  8768. (dict-set! mapping node output)
  8769. (for ([v (in-neighbors G node)])
  8770. (enqueue! worklist v))]))
  8771. mapping)
  8772. \end{lstlisting}
  8773. \caption{Generic work list algorithm for dataflow analysis}
  8774. \label{fig:generic-dataflow}
  8775. \end{figure}
  8776. Having discussed the two complications that arise from adding support
  8777. for assignment and loops, we turn to discussing the one new compiler
  8778. pass and the significant changes to existing passes.
  8779. \section{Convert Assignments}
  8780. \label{sec:convert-assignments}
  8781. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  8782. the combination of assignments and lexically-scoped functions requires
  8783. that we box those variables that are both assigned-to and that appear
  8784. free inside a \code{lambda}. The purpose of the
  8785. \code{convert-assignments} pass is to carry out that transformation.
  8786. We recommend placing this pass after \code{uniquify} but before
  8787. \code{reveal-functions}.
  8788. Consider again the first example from
  8789. Section~\ref{sec:assignment-scoping}:
  8790. \begin{lstlisting}
  8791. (let ([x 0])
  8792. (let ([y 0])
  8793. (let ([z 20])
  8794. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  8795. (begin
  8796. (set! x 10)
  8797. (set! y 12)
  8798. (f y))))))
  8799. \end{lstlisting}
  8800. The variables \code{x} and \code{y} are assigned-to. The variables
  8801. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  8802. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  8803. The boxing of \code{x} consists of three transformations: initialize
  8804. \code{x} with a vector, replace reads from \code{x} with
  8805. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  8806. \code{vector-set!}. The output of \code{convert-assignments} for this
  8807. example is as follows.
  8808. \begin{lstlisting}
  8809. (define (main) : Integer
  8810. (let ([x0 (vector 0)])
  8811. (let ([y1 0])
  8812. (let ([z2 20])
  8813. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  8814. (+ a3 (+ (vector-ref x0 0) z2)))])
  8815. (begin
  8816. (vector-set! x0 0 10)
  8817. (set! y1 12)
  8818. (f4 y1)))))))
  8819. \end{lstlisting}
  8820. \paragraph{Assigned \& Free}
  8821. We recommend defining an auxiliary function named
  8822. \code{assigned\&free} that takes an expression and simultaneously
  8823. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  8824. that occur free within lambda's, and 3) a new version of the
  8825. expression that records which bound variables occurred in the
  8826. intersection of $A$ and $F$. You can use the struct
  8827. \code{AssignedFree} to do this. Consider the case for
  8828. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  8829. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  8830. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  8831. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  8832. \begin{lstlisting}
  8833. (Let |$x$| |$rhs$| |$body$|)
  8834. |$\Rightarrow$|
  8835. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  8836. \end{lstlisting}
  8837. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  8838. The set of assigned variables for this \code{Let} is
  8839. $A_r \cup (A_b - \{x\})$
  8840. and the set of variables free in lambda's is
  8841. $F_r \cup (F_b - \{x\})$.
  8842. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  8843. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  8844. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  8845. and $F_r$.
  8846. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  8847. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  8848. recursively processing \itm{body}. Wrap each of parameter that occurs
  8849. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  8850. Let $P$ be the set of parameter names in \itm{params}. The result is
  8851. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  8852. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  8853. variables of an expression (see Chapter~\ref{ch:Rlam}).
  8854. \paragraph{Convert Assignments}
  8855. Next we discuss the \code{convert-assignment} pass with its auxiliary
  8856. functions for expressions and definitions. The function for
  8857. expressions, \code{cnvt-assign-exp}, should take an expression and a
  8858. set of assigned-and-free variables (obtained from the result of
  8859. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  8860. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  8861. \code{vector-ref}.
  8862. \begin{lstlisting}
  8863. (Var |$x$|)
  8864. |$\Rightarrow$|
  8865. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  8866. \end{lstlisting}
  8867. %
  8868. In the case for $\LET{\LP\code{AssignedFree}\,
  8869. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  8870. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  8871. \itm{body'} but with $x$ added to the set of assigned-and-free
  8872. variables. Translate the let-expression as follows to bind $x$ to a
  8873. boxed value.
  8874. \begin{lstlisting}
  8875. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  8876. |$\Rightarrow$|
  8877. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  8878. \end{lstlisting}
  8879. %
  8880. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  8881. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  8882. variables, translate the \code{set!} into a \code{vector-set!}
  8883. as follows.
  8884. \begin{lstlisting}
  8885. (SetBang |$x$| |$\itm{rhs}$|)
  8886. |$\Rightarrow$|
  8887. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  8888. \end{lstlisting}
  8889. %
  8890. The case for \code{Lambda} is non-trivial, but it is similar to the
  8891. case for function definitions, which we discuss next.
  8892. The auxiliary function for definitions, \code{cnvt-assign-def},
  8893. applies assignment conversion to function definitions.
  8894. We translate a function definition as follows.
  8895. \begin{lstlisting}
  8896. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  8897. |$\Rightarrow$|
  8898. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  8899. \end{lstlisting}
  8900. So it remains to explain \itm{params'} and $\itm{body}_4$.
  8901. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  8902. \code{assigned\&free} on $\itm{body_1}$.
  8903. Let $P$ be the parameter names in \itm{params}.
  8904. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  8905. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  8906. as the set of assigned-and-free variables.
  8907. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  8908. in a sequence of let-expressions that box the parameters
  8909. that are in $A_b \cap F_b$.
  8910. %
  8911. Regarding \itm{params'}, change the names of the parameters that are
  8912. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  8913. variables can retain the original names). Recall the second example in
  8914. Section~\ref{sec:assignment-scoping} involving a counter
  8915. abstraction. The following is the output of assignment version for
  8916. function \code{f}.
  8917. \begin{lstlisting}
  8918. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  8919. (vector
  8920. (lambda: () : Integer x1)
  8921. (lambda: () : Void (set! x1 (+ 1 x1)))))
  8922. |$\Rightarrow$|
  8923. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  8924. (let ([x1 (vector param_x1)])
  8925. (vector (lambda: () : Integer (vector-ref x1 0))
  8926. (lambda: () : Void
  8927. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  8928. \end{lstlisting}
  8929. \section{Remove Complex Operands}
  8930. \label{sec:rco-loop}
  8931. The three new language forms, \code{while}, \code{set!}, and
  8932. \code{begin} are all complex expressions and their subexpressions are
  8933. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  8934. output language \LangFunANF{} of this pass.
  8935. \begin{figure}[tp]
  8936. \centering
  8937. \fbox{
  8938. \begin{minipage}{0.96\textwidth}
  8939. \small
  8940. \[
  8941. \begin{array}{rcl}
  8942. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  8943. \MID \VOID{} } \\
  8944. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8945. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  8946. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  8947. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8948. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8949. \end{array}
  8950. \]
  8951. \end{minipage}
  8952. }
  8953. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  8954. \label{fig:Rwhile-anf-syntax}
  8955. \end{figure}
  8956. As usual, when a complex expression appears in a grammar position that
  8957. needs to be atomic, such as the argument of a primitive operator, we
  8958. must introduce a temporary variable and bind it to the complex
  8959. expression. This approach applies, unchanged, to handle the new
  8960. language forms. For example, in the following code there are two
  8961. \code{begin} expressions appearing as arguments to \code{+}. The
  8962. output of \code{rco-exp} is shown below, in which the \code{begin}
  8963. expressions have been bound to temporary variables. Recall that
  8964. \code{let} expressions in \LangLoopANF{} are allowed to have
  8965. arbitrary expressions in their right-hand-side expression, so it is
  8966. fine to place \code{begin} there.
  8967. \begin{lstlisting}
  8968. (let ([x0 10])
  8969. (let ([y1 0])
  8970. (+ (+ (begin (set! y1 (read)) x0)
  8971. (begin (set! x0 (read)) y1))
  8972. x0)))
  8973. |$\Rightarrow$|
  8974. (let ([x0 10])
  8975. (let ([y1 0])
  8976. (let ([tmp2 (begin (set! y1 (read)) x0)])
  8977. (let ([tmp3 (begin (set! x0 (read)) y1)])
  8978. (let ([tmp4 (+ tmp2 tmp3)])
  8979. (+ tmp4 x0))))))
  8980. \end{lstlisting}
  8981. \section{Explicate Control and \LangCLoop{}}
  8982. \label{sec:explicate-loop}
  8983. Recall that in the \code{explicate\_control} pass we define one helper
  8984. function for each kind of position in the program. For the \LangVar{}
  8985. language of integers and variables we needed kinds of positions:
  8986. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  8987. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  8988. yet another kind of position: effect position. Except for the last
  8989. subexpression, the subexpressions inside a \code{begin} are evaluated
  8990. only for their effect. Their result values are discarded. We can
  8991. generate better code by taking this fact into account.
  8992. The output language of \code{explicate\_control} is \LangCLoop{}
  8993. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  8994. \LangCLam{}. The only syntactic difference is that \code{Call},
  8995. \code{vector-set!}, and \code{read} may also appear as statements.
  8996. The most significant difference between \LangCLam{} and \LangCLoop{}
  8997. is that the control-flow graphs of the later may contain cycles.
  8998. \begin{figure}[tp]
  8999. \fbox{
  9000. \begin{minipage}{0.96\textwidth}
  9001. \small
  9002. \[
  9003. \begin{array}{lcl}
  9004. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9005. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9006. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  9007. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9008. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9009. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9010. \end{array}
  9011. \]
  9012. \end{minipage}
  9013. }
  9014. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9015. \label{fig:c7-syntax}
  9016. \end{figure}
  9017. The new auxiliary function \code{explicate-effect} takes an expression
  9018. (in an effect position) and a promise of a continuation block. The
  9019. function returns a promise for a $\Tail$ that includes the generated
  9020. code for the input expression followed by the continuation block. If
  9021. the expression is obviously pure, that is, never causes side effects,
  9022. then the expression can be removed, so the result is just the
  9023. continuation block.
  9024. %
  9025. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9026. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9027. the loop. Recursively process the \itm{body} (in effect position)
  9028. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9029. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9030. \itm{body'} as the then-branch and the continuation block as the
  9031. else-branch. The result should be added to the control-flow graph with
  9032. the label \itm{loop}. The result for the whole \code{while} loop is a
  9033. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9034. added to the control-flow graph if the loop is indeed used, which can
  9035. be accomplished using \code{delay}.
  9036. The auxiliary functions for tail, assignment, and predicate positions
  9037. need to be updated. The three new language forms, \code{while},
  9038. \code{set!}, and \code{begin}, can appear in assignment and tail
  9039. positions. Only \code{begin} may appear in predicate positions; the
  9040. other two have result type \code{Void}.
  9041. \section{Select Instructions}
  9042. \label{sec:select-instructions-loop}
  9043. Only three small additions are needed in the
  9044. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  9045. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9046. stand-alone statements instead of only appearing on the right-hand
  9047. side of an assignment statement. The code generation is nearly
  9048. identical; just leave off the instruction for moving the result into
  9049. the left-hand side.
  9050. \section{Register Allocation}
  9051. \label{sec:register-allocation-loop}
  9052. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9053. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9054. which complicates the liveness analysis needed for register
  9055. allocation.
  9056. \subsection{Liveness Analysis}
  9057. \label{sec:liveness-analysis-r8}
  9058. We recommend using the generic \code{analyze-dataflow} function that
  9059. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9060. perform liveness analysis, replacing the code in
  9061. \code{uncover-live-CFG} that processed the basic blocks in topological
  9062. order (Section~\ref{sec:liveness-analysis-Rif}).
  9063. The \code{analyze-dataflow} function has four parameters.
  9064. \begin{enumerate}
  9065. \item The first parameter \code{G} should be a directed graph from the
  9066. \code{racket/graph} package (see the sidebar in
  9067. Section~\ref{sec:build-interference}) that represents the
  9068. control-flow graph.
  9069. \item The second parameter \code{transfer} is a function that applies
  9070. liveness analysis to a basic block. It takes two parameters: the
  9071. label for the block to analyze and the live-after set for that
  9072. block. The transfer function should return the live-before set for
  9073. the block. Also, as a side-effect, it should update the block's
  9074. $\itm{info}$ with the liveness information for each instruction. To
  9075. implement the \code{transfer} function, you should be able to reuse
  9076. the code you already have for analyzing basic blocks.
  9077. \item The third and fourth parameters of \code{analyze-dataflow} are
  9078. \code{bottom} and \code{join} for the lattice of abstract states,
  9079. i.e. sets of locations. The bottom of the lattice is the empty set
  9080. \code{(set)} and the join operator is \code{set-union}.
  9081. \end{enumerate}
  9082. \begin{figure}[p]
  9083. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9084. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9085. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9086. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9087. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9088. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9089. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9090. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9091. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  9092. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  9093. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  9094. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9095. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9096. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9097. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9098. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9099. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9100. %% \path[->,bend left=15] (Rfun) edge [above] node
  9101. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9102. \path[->,bend left=15] (Rfun) edge [above] node
  9103. {\ttfamily\footnotesize shrink} (Rfun-2);
  9104. \path[->,bend left=15] (Rfun-2) edge [above] node
  9105. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9106. \path[->,bend left=15] (Rfun-3) edge [above] node
  9107. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9108. \path[->,bend left=15] (Rfun-4) edge [right] node
  9109. {\ttfamily\footnotesize convert-assignments} (F1-1);
  9110. \path[->,bend left=15] (F1-1) edge [below] node
  9111. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9112. \path[->,bend right=15] (F1-2) edge [above] node
  9113. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9114. \path[->,bend right=15] (F1-3) edge [above] node
  9115. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9116. \path[->,bend right=15] (F1-4) edge [above] node
  9117. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9118. \path[->,bend right=15] (F1-5) edge [right] node
  9119. {\ttfamily\footnotesize explicate-control} (C3-2);
  9120. \path[->,bend left=15] (C3-2) edge [left] node
  9121. {\ttfamily\footnotesize select-instr.} (x86-2);
  9122. \path[->,bend right=15] (x86-2) edge [left] node
  9123. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9124. \path[->,bend right=15] (x86-2-1) edge [below] node
  9125. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9126. \path[->,bend right=15] (x86-2-2) edge [left] node
  9127. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9128. \path[->,bend left=15] (x86-3) edge [above] node
  9129. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9130. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  9131. \end{tikzpicture}
  9132. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  9133. \label{fig:Rwhile-passes}
  9134. \end{figure}
  9135. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9136. for the compilation of \LangLoop{}.
  9137. \section{Challenge: Arrays}
  9138. \label{sec:arrays}
  9139. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  9140. elements whose length is determined at compile-time and where each
  9141. element of a tuple may have a different type (they are
  9142. heterogeous). This challenge is also about sequences, but this time
  9143. the length is determined at run-time and all the elements have the same
  9144. type (they are homogeneous). We use the term ``array'' for this later
  9145. kind of sequence.
  9146. The Racket language does not distinguish between tuples and arrays,
  9147. they are both represented by vectors. However, Typed Racket
  9148. distinguishes between tuples and arrays: the \code{Vector} type is for
  9149. tuples and the \code{Vectorof} type is for arrays.
  9150. %
  9151. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  9152. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  9153. and the \code{make-vector} primitive operator for creating an array,
  9154. whose arguments are the length of the array and an initial value for
  9155. all the elements in the array. The \code{vector-length},
  9156. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  9157. for tuples become overloaded for use with arrays.
  9158. %
  9159. We also include integer multiplication in \LangArray{}, as it is
  9160. useful in many examples involving arrays such as computing the
  9161. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  9162. \begin{figure}[tp]
  9163. \centering
  9164. \fbox{
  9165. \begin{minipage}{0.96\textwidth}
  9166. \small
  9167. \[
  9168. \begin{array}{lcl}
  9169. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  9170. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  9171. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  9172. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9173. &\MID& \gray{\key{\#t} \MID \key{\#f}
  9174. \MID \LP\key{and}\;\Exp\;\Exp\RP
  9175. \MID \LP\key{or}\;\Exp\;\Exp\RP
  9176. \MID \LP\key{not}\;\Exp\RP } \\
  9177. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9178. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  9179. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  9180. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  9181. \MID \LP\Exp \; \Exp\ldots\RP } \\
  9182. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9183. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9184. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  9185. \MID \CBEGIN{\Exp\ldots}{\Exp}
  9186. \MID \CWHILE{\Exp}{\Exp} } \\
  9187. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  9188. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9189. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  9190. \end{array}
  9191. \]
  9192. \end{minipage}
  9193. }
  9194. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  9195. \label{fig:Rvecof-concrete-syntax}
  9196. \end{figure}
  9197. \begin{figure}[tp]
  9198. \begin{lstlisting}
  9199. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  9200. [n : Integer]) : Integer
  9201. (let ([i 0])
  9202. (let ([prod 0])
  9203. (begin
  9204. (while (< i n)
  9205. (begin
  9206. (set! prod (+ prod (* (vector-ref A i)
  9207. (vector-ref B i))))
  9208. (set! i (+ i 1))
  9209. ))
  9210. prod))))
  9211. (let ([A (make-vector 2 2)])
  9212. (let ([B (make-vector 2 3)])
  9213. (+ (inner-product A B 2)
  9214. 30)))
  9215. \end{lstlisting}
  9216. \caption{Example program that computes the inner-product.}
  9217. \label{fig:inner-product}
  9218. \end{figure}
  9219. The type checker for \LangArray{} is define in
  9220. Figure~\ref{fig:type-check-Rvecof}. The result type of
  9221. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  9222. of the intializing expression. The length expression is required to
  9223. have type \code{Integer}. The type checking of the operators
  9224. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  9225. updated to handle the situation where the vector has type
  9226. \code{Vectorof}. In these cases we translate the operators to their
  9227. \code{vectorof} form so that later passes can easily distinguish
  9228. between operations on tuples versus arrays. We override the
  9229. \code{operator-types} method to provide the type signature for
  9230. multiplication: it takes two integers and returns an integer. To
  9231. support injection and projection of arrays to the \code{Any} type
  9232. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  9233. predicate.
  9234. \begin{figure}[tbp]
  9235. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9236. (define type-check-Rvecof_class
  9237. (class type-check-Rwhile_class
  9238. (super-new)
  9239. (inherit check-type-equal?)
  9240. (define/override (flat-ty? ty)
  9241. (match ty
  9242. ['(Vectorof Any) #t]
  9243. [else (super flat-ty? ty)]))
  9244. (define/override (operator-types)
  9245. (append '((* . ((Integer Integer) . Integer)))
  9246. (super operator-types)))
  9247. (define/override (type-check-exp env)
  9248. (lambda (e)
  9249. (define recur (type-check-exp env))
  9250. (match e
  9251. [(Prim 'make-vector (list e1 e2))
  9252. (define-values (e1^ t1) (recur e1))
  9253. (define-values (e2^ elt-type) (recur e2))
  9254. (define vec-type `(Vectorof ,elt-type))
  9255. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  9256. vec-type)]
  9257. [(Prim 'vector-ref (list e1 e2))
  9258. (define-values (e1^ t1) (recur e1))
  9259. (define-values (e2^ t2) (recur e2))
  9260. (match* (t1 t2)
  9261. [(`(Vectorof ,elt-type) 'Integer)
  9262. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  9263. [(other wise) ((super type-check-exp env) e)])]
  9264. [(Prim 'vector-set! (list e1 e2 e3) )
  9265. (define-values (e-vec t-vec) (recur e1))
  9266. (define-values (e2^ t2) (recur e2))
  9267. (define-values (e-arg^ t-arg) (recur e3))
  9268. (match t-vec
  9269. [`(Vectorof ,elt-type)
  9270. (check-type-equal? elt-type t-arg e)
  9271. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  9272. [else ((super type-check-exp env) e)])]
  9273. [(Prim 'vector-length (list e1))
  9274. (define-values (e1^ t1) (recur e1))
  9275. (match t1
  9276. [`(Vectorof ,t)
  9277. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  9278. [else ((super type-check-exp env) e)])]
  9279. [else ((super type-check-exp env) e)])))
  9280. ))
  9281. (define (type-check-Rvecof p)
  9282. (send (new type-check-Rvecof_class) type-check-program p))
  9283. \end{lstlisting}
  9284. \caption{Type checker for the \LangArray{} language.}
  9285. \label{fig:type-check-Rvecof}
  9286. \end{figure}
  9287. The interpreter for \LangArray{} is defined in
  9288. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  9289. implemented with Racket's \code{make-vector} function and
  9290. multiplication is \code{fx*}, multiplication for \code{fixnum}
  9291. integers.
  9292. \begin{figure}[tbp]
  9293. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9294. (define interp-Rvecof_class
  9295. (class interp-Rwhile_class
  9296. (super-new)
  9297. (define/override (interp-op op)
  9298. (verbose "Rvecof/interp-op" op)
  9299. (match op
  9300. ['make-vector make-vector]
  9301. ['* fx*]
  9302. [else (super interp-op op)]))
  9303. ))
  9304. (define (interp-Rvecof p)
  9305. (send (new interp-Rvecof_class) interp-program p))
  9306. \end{lstlisting}
  9307. \caption{Interpreter for \LangArray{}.}
  9308. \label{fig:interp-Rvecof}
  9309. \end{figure}
  9310. \subsection{Data Representation}
  9311. \label{sec:array-rep}
  9312. Just like tuples, we store arrays on the heap which means that the
  9313. garbage collector will need to inspect arrays. An immediate thought is
  9314. to use the same representation for arrays that we use for tuples.
  9315. However, we limit tuples to a length of $50$ so that their length and
  9316. pointer mask can fit into the 64-bit tag at the beginning of each
  9317. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  9318. millions of elements, so we need more bits to store the length.
  9319. However, because arrays are homogeneous, we only need $1$ bit for the
  9320. pointer mask instead of one bit per array elements. Finally, the
  9321. garbage collector will need to be able to distinguish between tuples
  9322. and arrays, so we need to reserve $1$ bit for that purpose. So we
  9323. arrive at the following layout for the 64-bit tag at the beginning of
  9324. an array:
  9325. \begin{itemize}
  9326. \item The right-most bit is the forwarding bit, just like in a tuple.
  9327. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  9328. it is not.
  9329. \item The next bit to the left is the pointer mask. A $0$ indicates
  9330. that none of the elements are pointers to the heap and a $1$
  9331. indicates that all of the elements are pointers.
  9332. \item The next $61$ bits store the length of the array.
  9333. \item The left-most bit distinguishes between a tuple ($0$) versus an
  9334. array ($1$).
  9335. \end{itemize}
  9336. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  9337. differentiate the kinds of values that have been injected into the
  9338. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  9339. to indicate that the value is an array.
  9340. In the following subsections we provide hints regarding how to update
  9341. the passes to handle arrays.
  9342. \subsection{Reveal Casts}
  9343. The array-access operators \code{vectorof-ref} and
  9344. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  9345. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  9346. that the type checker cannot tell whether the index will be in bounds,
  9347. so the bounds check must be performed at run time. Recall that the
  9348. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  9349. an \code{If} arround a vector reference for update to check whether
  9350. the index is less than the length. You should do the same for
  9351. \code{vectorof-ref} and \code{vectorof-set!} .
  9352. In addition, the handling of the \code{any-vector} operators in
  9353. \code{reveal-casts} needs to be updated to account for arrays that are
  9354. injected to \code{Any}. For the \code{any-vector-length} operator, the
  9355. generated code should test whether the tag is for tuples (\code{010})
  9356. or arrays (\code{110}) and then dispatch to either
  9357. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  9358. we add a case in \code{select-instructions} to generate the
  9359. appropriate instructions for accessing the array length from the
  9360. header of an array.
  9361. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  9362. the generated code needs to check that the index is less than the
  9363. vector length, so like the code for \code{any-vector-length}, check
  9364. the tag to determine whether to use \code{any-vector-length} or
  9365. \code{any-vectorof-length} for this purpose. Once the bounds checking
  9366. is complete, the generated code can use \code{any-vector-ref} and
  9367. \code{any-vector-set!} for both tuples and arrays because the
  9368. instructions used for those operators do not look at the tag at the
  9369. front of the tuple or array.
  9370. \subsection{Expose Allocation}
  9371. This pass should translate the \code{make-vector} operator into
  9372. lower-level operations. In particular, the new AST node
  9373. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  9374. length specified by the $\Exp$, but does not initialize the elements
  9375. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  9376. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  9377. element type for the array. Regarding the initialization of the array,
  9378. we recommend generated a \code{while} loop that uses
  9379. \code{vector-set!} to put the initializing value into every element of
  9380. the array.
  9381. \subsection{Remove Complex Operands}
  9382. Add cases in the \code{rco-atom} and \code{rco-exp} for
  9383. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  9384. complex and its subexpression must be atomic.
  9385. \subsection{Explicate Control}
  9386. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  9387. \code{explicate-assign}.
  9388. \subsection{Select Instructions}
  9389. Generate instructions for \code{AllocateArray} similar to those for
  9390. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  9391. that the tag at the front of the array should instead use the
  9392. representation discussed in Section~\ref{sec:array-rep}.
  9393. Regarding \code{vectorof-length}, extract the length from the tag
  9394. according to the representation discussed in
  9395. Section~\ref{sec:array-rep}.
  9396. The instructions generated for \code{vectorof-ref} differ from those
  9397. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  9398. that the index is not a constant so the offset must be computed at
  9399. runtime, similar to the instructions generated for
  9400. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  9401. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  9402. appear in an assignment and as a stand-alone statement, so make sure
  9403. to handle both situations in this pass.
  9404. Finally, the instructions for \code{any-vectorof-length} should be
  9405. similar to those for \code{vectorof-length}, except that one must
  9406. first project the array by writing zeroes into the $3$-bit tag
  9407. \begin{exercise}\normalfont
  9408. Implement a compiler for the \LangArray{} language by extending your
  9409. compiler for \LangLoop{}. Test your compiler on a half dozen new
  9410. programs, including the one in Figure~\ref{fig:inner-product} and also
  9411. a program that multiplies two matrices. Note that matrices are
  9412. 2-dimensional arrays, but those can be encoded into 1-dimensional
  9413. arrays by laying out each row in the array, one after the next.
  9414. \end{exercise}
  9415. % Further Reading: dataflow analysis
  9416. \fi
  9417. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9418. \chapter{Tuples and Garbage Collection}
  9419. \label{ch:Rvec}
  9420. \index{subject}{tuple}
  9421. \index{subject}{vector}
  9422. \if\edition\racketEd
  9423. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9424. %% all the IR grammars are spelled out! \\ --Jeremy}
  9425. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9426. %% the root stack. \\ --Jeremy}
  9427. In this chapter we study the implementation of mutable tuples, called
  9428. vectors in Racket. This language feature is the first to use the
  9429. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  9430. tuple is indefinite, that is, a tuple lives forever from the
  9431. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  9432. is important to reclaim the space associated with a tuple when it is
  9433. no longer needed, which is why we also study \emph{garbage collection}
  9434. \emph{garbage collection} techniques in this chapter.
  9435. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9436. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  9437. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  9438. \code{void} value. The reason for including the later is that the
  9439. \code{vector-set!} operation returns a value of type
  9440. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  9441. called the \code{Unit} type in the programming languages
  9442. literature. Racket's \code{Void} type is inhabited by a single value
  9443. \code{void} which corresponds to \code{unit} or \code{()} in the
  9444. literature~\citep{Pierce:2002hj}.}.
  9445. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9446. copying live objects back and forth between two halves of the
  9447. heap. The garbage collector requires coordination with the compiler so
  9448. that it can see all of the \emph{root} pointers, that is, pointers in
  9449. registers or on the procedure call stack.
  9450. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9451. discuss all the necessary changes and additions to the compiler
  9452. passes, including a new compiler pass named \code{expose-allocation}.
  9453. \section{The \LangVec{} Language}
  9454. \label{sec:r3}
  9455. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  9456. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  9457. \LangVec{} language includes three new forms: \code{vector} for creating a
  9458. tuple, \code{vector-ref} for reading an element of a tuple, and
  9459. \code{vector-set!} for writing to an element of a tuple. The program
  9460. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  9461. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  9462. the 3-tuple, demonstrating that tuples are first-class values. The
  9463. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  9464. of the \key{if} is taken. The element at index $0$ of \code{t} is
  9465. \code{40}, to which we add \code{2}, the element at index $0$ of the
  9466. 1-tuple. So the result of the program is \code{42}.
  9467. \begin{figure}[tbp]
  9468. \centering
  9469. \fbox{
  9470. \begin{minipage}{0.96\textwidth}
  9471. \[
  9472. \begin{array}{lcl}
  9473. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  9474. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  9475. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9476. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9477. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  9478. \MID \LP\key{and}\;\Exp\;\Exp\RP
  9479. \MID \LP\key{or}\;\Exp\;\Exp\RP
  9480. \MID \LP\key{not}\;\Exp\RP } \\
  9481. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  9482. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9483. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  9484. \MID \LP\key{vector-length}\;\Exp\RP \\
  9485. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9486. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  9487. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  9488. \LangVecM{} &::=& \Exp
  9489. \end{array}
  9490. \]
  9491. \end{minipage}
  9492. }
  9493. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  9494. (Figure~\ref{fig:Rif-concrete-syntax}).}
  9495. \label{fig:Rvec-concrete-syntax}
  9496. \end{figure}
  9497. \begin{figure}[tbp]
  9498. \begin{lstlisting}
  9499. (let ([t (vector 40 #t (vector 2))])
  9500. (if (vector-ref t 1)
  9501. (+ (vector-ref t 0)
  9502. (vector-ref (vector-ref t 2) 0))
  9503. 44))
  9504. \end{lstlisting}
  9505. \caption{Example program that creates tuples and reads from them.}
  9506. \label{fig:vector-eg}
  9507. \end{figure}
  9508. \begin{figure}[tp]
  9509. \centering
  9510. \fbox{
  9511. \begin{minipage}{0.96\textwidth}
  9512. \[
  9513. \begin{array}{lcl}
  9514. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  9515. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9516. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  9517. \MID \BOOL{\itm{bool}}
  9518. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9519. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  9520. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9521. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  9522. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9523. \end{array}
  9524. \]
  9525. \end{minipage}
  9526. }
  9527. \caption{The abstract syntax of \LangVec{}.}
  9528. \label{fig:Rvec-syntax}
  9529. \end{figure}
  9530. \index{subject}{allocate}
  9531. \index{subject}{heap allocate}
  9532. Tuples are our first encounter with heap-allocated data, which raises
  9533. several interesting issues. First, variable binding performs a
  9534. shallow-copy when dealing with tuples, which means that different
  9535. variables can refer to the same tuple, that is, different variables
  9536. can be \emph{aliases} for the same entity. Consider the following
  9537. example in which both \code{t1} and \code{t2} refer to the same tuple.
  9538. Thus, the mutation through \code{t2} is visible when referencing the
  9539. tuple from \code{t1}, so the result of this program is \code{42}.
  9540. \index{subject}{alias}\index{subject}{mutation}
  9541. \begin{center}
  9542. \begin{minipage}{0.96\textwidth}
  9543. \begin{lstlisting}
  9544. (let ([t1 (vector 3 7)])
  9545. (let ([t2 t1])
  9546. (let ([_ (vector-set! t2 0 42)])
  9547. (vector-ref t1 0))))
  9548. \end{lstlisting}
  9549. \end{minipage}
  9550. \end{center}
  9551. The next issue concerns the lifetime of tuples. Of course, they are
  9552. created by the \code{vector} form, but when does their lifetime end?
  9553. Notice that \LangVec{} does not include an operation for deleting
  9554. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  9555. of static scoping. For example, the following program returns
  9556. \code{42} even though the variable \code{w} goes out of scope prior to
  9557. the \code{vector-ref} that reads from the vector it was bound to.
  9558. \begin{center}
  9559. \begin{minipage}{0.96\textwidth}
  9560. \begin{lstlisting}
  9561. (let ([v (vector (vector 44))])
  9562. (let ([x (let ([w (vector 42)])
  9563. (let ([_ (vector-set! v 0 w)])
  9564. 0))])
  9565. (+ x (vector-ref (vector-ref v 0) 0))))
  9566. \end{lstlisting}
  9567. \end{minipage}
  9568. \end{center}
  9569. From the perspective of programmer-observable behavior, tuples live
  9570. forever. Of course, if they really lived forever, then many programs
  9571. would run out of memory.\footnote{The \LangVec{} language does not have
  9572. looping or recursive functions, so it is nigh impossible to write a
  9573. program in \LangVec{} that will run out of memory. However, we add
  9574. recursive functions in the next Chapter!} A Racket implementation
  9575. must therefore perform automatic garbage collection.
  9576. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  9577. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  9578. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  9579. terms of the corresponding operations in Racket. One subtle point is
  9580. that the \code{vector-set!} operation returns the \code{\#<void>}
  9581. value. The \code{\#<void>} value can be passed around just like other
  9582. values inside an \LangVec{} program and a \code{\#<void>} value can be
  9583. compared for equality with another \code{\#<void>} value. However,
  9584. there are no other operations specific to the the \code{\#<void>}
  9585. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  9586. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  9587. otherwise.
  9588. \begin{figure}[tbp]
  9589. \begin{lstlisting}
  9590. (define interp-Rvec_class
  9591. (class interp-Rif_class
  9592. (super-new)
  9593. (define/override (interp-op op)
  9594. (match op
  9595. ['eq? (lambda (v1 v2)
  9596. (cond [(or (and (fixnum? v1) (fixnum? v2))
  9597. (and (boolean? v1) (boolean? v2))
  9598. (and (vector? v1) (vector? v2))
  9599. (and (void? v1) (void? v2)))
  9600. (eq? v1 v2)]))]
  9601. ['vector vector]
  9602. ['vector-length vector-length]
  9603. ['vector-ref vector-ref]
  9604. ['vector-set! vector-set!]
  9605. [else (super interp-op op)]
  9606. ))
  9607. (define/override ((interp-exp env) e)
  9608. (define recur (interp-exp env))
  9609. (match e
  9610. [(HasType e t) (recur e)]
  9611. [(Void) (void)]
  9612. [else ((super interp-exp env) e)]
  9613. ))
  9614. ))
  9615. (define (interp-Rvec p)
  9616. (send (new interp-Rvec_class) interp-program p))
  9617. \end{lstlisting}
  9618. \caption{Interpreter for the \LangVec{} language.}
  9619. \label{fig:interp-Rvec}
  9620. \end{figure}
  9621. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  9622. deserves some explanation. When allocating a vector, we need to know
  9623. which elements of the vector are pointers (i.e. are also vectors). We
  9624. can obtain this information during type checking. The type checker in
  9625. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  9626. expression, it also wraps every \key{vector} creation with the form
  9627. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  9628. %
  9629. To create the s-expression for the \code{Vector} type in
  9630. Figure~\ref{fig:type-check-Rvec}, we use the
  9631. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  9632. operator} \code{,@} to insert the list \code{t*} without its usual
  9633. start and end parentheses. \index{subject}{unquote-slicing}
  9634. \begin{figure}[tp]
  9635. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9636. (define type-check-Rvec_class
  9637. (class type-check-Rif_class
  9638. (super-new)
  9639. (inherit check-type-equal?)
  9640. (define/override (type-check-exp env)
  9641. (lambda (e)
  9642. (define recur (type-check-exp env))
  9643. (match e
  9644. [(Void) (values (Void) 'Void)]
  9645. [(Prim 'vector es)
  9646. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  9647. (define t `(Vector ,@t*))
  9648. (values (HasType (Prim 'vector e*) t) t)]
  9649. [(Prim 'vector-ref (list e1 (Int i)))
  9650. (define-values (e1^ t) (recur e1))
  9651. (match t
  9652. [`(Vector ,ts ...)
  9653. (unless (and (0 . <= . i) (i . < . (length ts)))
  9654. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  9655. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  9656. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  9657. [(Prim 'vector-set! (list e1 (Int i) arg) )
  9658. (define-values (e-vec t-vec) (recur e1))
  9659. (define-values (e-arg^ t-arg) (recur arg))
  9660. (match t-vec
  9661. [`(Vector ,ts ...)
  9662. (unless (and (0 . <= . i) (i . < . (length ts)))
  9663. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  9664. (check-type-equal? (list-ref ts i) t-arg e)
  9665. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  9666. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  9667. [(Prim 'vector-length (list e))
  9668. (define-values (e^ t) (recur e))
  9669. (match t
  9670. [`(Vector ,ts ...)
  9671. (values (Prim 'vector-length (list e^)) 'Integer)]
  9672. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  9673. [(Prim 'eq? (list arg1 arg2))
  9674. (define-values (e1 t1) (recur arg1))
  9675. (define-values (e2 t2) (recur arg2))
  9676. (match* (t1 t2)
  9677. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9678. [(other wise) (check-type-equal? t1 t2 e)])
  9679. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9680. [(HasType (Prim 'vector es) t)
  9681. ((type-check-exp env) (Prim 'vector es))]
  9682. [(HasType e1 t)
  9683. (define-values (e1^ t^) (recur e1))
  9684. (check-type-equal? t t^ e)
  9685. (values (HasType e1^ t) t)]
  9686. [else ((super type-check-exp env) e)]
  9687. )))
  9688. ))
  9689. (define (type-check-Rvec p)
  9690. (send (new type-check-Rvec_class) type-check-program p))
  9691. \end{lstlisting}
  9692. \caption{Type checker for the \LangVec{} language.}
  9693. \label{fig:type-check-Rvec}
  9694. \end{figure}
  9695. \section{Garbage Collection}
  9696. \label{sec:GC}
  9697. Here we study a relatively simple algorithm for garbage collection
  9698. that is the basis of state-of-the-art garbage
  9699. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  9700. particular, we describe a two-space copying
  9701. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  9702. perform the
  9703. copy~\citep{Cheney:1970aa}.
  9704. \index{subject}{copying collector}
  9705. \index{subject}{two-space copying collector}
  9706. Figure~\ref{fig:copying-collector} gives a
  9707. coarse-grained depiction of what happens in a two-space collector,
  9708. showing two time steps, prior to garbage collection (on the top) and
  9709. after garbage collection (on the bottom). In a two-space collector,
  9710. the heap is divided into two parts named the FromSpace and the
  9711. ToSpace. Initially, all allocations go to the FromSpace until there is
  9712. not enough room for the next allocation request. At that point, the
  9713. garbage collector goes to work to make more room.
  9714. \index{subject}{ToSpace}
  9715. \index{subject}{FromSpace}
  9716. The garbage collector must be careful not to reclaim tuples that will
  9717. be used by the program in the future. Of course, it is impossible in
  9718. general to predict what a program will do, but we can over approximate
  9719. the will-be-used tuples by preserving all tuples that could be
  9720. accessed by \emph{any} program given the current computer state. A
  9721. program could access any tuple whose address is in a register or on
  9722. the procedure call stack. These addresses are called the \emph{root
  9723. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  9724. transitively reachable from the root set. Thus, it is safe for the
  9725. garbage collector to reclaim the tuples that are not reachable in this
  9726. way.
  9727. So the goal of the garbage collector is twofold:
  9728. \begin{enumerate}
  9729. \item preserve all tuple that are reachable from the root set via a
  9730. path of pointers, that is, the \emph{live} tuples, and
  9731. \item reclaim the memory of everything else, that is, the
  9732. \emph{garbage}.
  9733. \end{enumerate}
  9734. A copying collector accomplishes this by copying all of the live
  9735. objects from the FromSpace into the ToSpace and then performs a sleight
  9736. of hand, treating the ToSpace as the new FromSpace and the old
  9737. FromSpace as the new ToSpace. In the example of
  9738. Figure~\ref{fig:copying-collector}, there are three pointers in the
  9739. root set, one in a register and two on the stack. All of the live
  9740. objects have been copied to the ToSpace (the right-hand side of
  9741. Figure~\ref{fig:copying-collector}) in a way that preserves the
  9742. pointer relationships. For example, the pointer in the register still
  9743. points to a 2-tuple whose first element is a 3-tuple and whose second
  9744. element is a 2-tuple. There are four tuples that are not reachable
  9745. from the root set and therefore do not get copied into the ToSpace.
  9746. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  9747. created by a well-typed program in \LangVec{} because it contains a
  9748. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  9749. We design the garbage collector to deal with cycles to begin with so
  9750. we will not need to revisit this issue.
  9751. \begin{figure}[tbp]
  9752. \centering
  9753. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  9754. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  9755. \caption{A copying collector in action.}
  9756. \label{fig:copying-collector}
  9757. \end{figure}
  9758. There are many alternatives to copying collectors (and their bigger
  9759. siblings, the generational collectors) when its comes to garbage
  9760. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  9761. reference counting~\citep{Collins:1960aa}. The strengths of copying
  9762. collectors are that allocation is fast (just a comparison and pointer
  9763. increment), there is no fragmentation, cyclic garbage is collected,
  9764. and the time complexity of collection only depends on the amount of
  9765. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  9766. main disadvantages of a two-space copying collector is that it uses a
  9767. lot of space and takes a long time to perform the copy, though these
  9768. problems are ameliorated in generational collectors. Racket and
  9769. Scheme programs tend to allocate many small objects and generate a lot
  9770. of garbage, so copying and generational collectors are a good fit.
  9771. Garbage collection is an active research topic, especially concurrent
  9772. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  9773. developing new techniques and revisiting old
  9774. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  9775. meet every year at the International Symposium on Memory Management to
  9776. present these findings.
  9777. \subsection{Graph Copying via Cheney's Algorithm}
  9778. \label{sec:cheney}
  9779. \index{subject}{Cheney's algorithm}
  9780. Let us take a closer look at the copying of the live objects. The
  9781. allocated objects and pointers can be viewed as a graph and we need to
  9782. copy the part of the graph that is reachable from the root set. To
  9783. make sure we copy all of the reachable vertices in the graph, we need
  9784. an exhaustive graph traversal algorithm, such as depth-first search or
  9785. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  9786. such algorithms take into account the possibility of cycles by marking
  9787. which vertices have already been visited, so as to ensure termination
  9788. of the algorithm. These search algorithms also use a data structure
  9789. such as a stack or queue as a to-do list to keep track of the vertices
  9790. that need to be visited. We use breadth-first search and a trick
  9791. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  9792. and copying tuples into the ToSpace.
  9793. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  9794. copy progresses. The queue is represented by a chunk of contiguous
  9795. memory at the beginning of the ToSpace, using two pointers to track
  9796. the front and the back of the queue. The algorithm starts by copying
  9797. all tuples that are immediately reachable from the root set into the
  9798. ToSpace to form the initial queue. When we copy a tuple, we mark the
  9799. old tuple to indicate that it has been visited. We discuss how this
  9800. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  9801. pointers inside the copied tuples in the queue still point back to the
  9802. FromSpace. Once the initial queue has been created, the algorithm
  9803. enters a loop in which it repeatedly processes the tuple at the front
  9804. of the queue and pops it off the queue. To process a tuple, the
  9805. algorithm copies all the tuple that are directly reachable from it to
  9806. the ToSpace, placing them at the back of the queue. The algorithm then
  9807. updates the pointers in the popped tuple so they point to the newly
  9808. copied tuples.
  9809. \begin{figure}[tbp]
  9810. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  9811. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  9812. \label{fig:cheney}
  9813. \end{figure}
  9814. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  9815. tuple whose second element is $42$ to the back of the queue. The other
  9816. pointer goes to a tuple that has already been copied, so we do not
  9817. need to copy it again, but we do need to update the pointer to the new
  9818. location. This can be accomplished by storing a \emph{forwarding
  9819. pointer} to the new location in the old tuple, back when we initially
  9820. copied the tuple into the ToSpace. This completes one step of the
  9821. algorithm. The algorithm continues in this way until the front of the
  9822. queue is empty, that is, until the front catches up with the back.
  9823. \subsection{Data Representation}
  9824. \label{sec:data-rep-gc}
  9825. The garbage collector places some requirements on the data
  9826. representations used by our compiler. First, the garbage collector
  9827. needs to distinguish between pointers and other kinds of data. There
  9828. are several ways to accomplish this.
  9829. \begin{enumerate}
  9830. \item Attached a tag to each object that identifies what type of
  9831. object it is~\citep{McCarthy:1960dz}.
  9832. \item Store different types of objects in different
  9833. regions~\citep{Steele:1977ab}.
  9834. \item Use type information from the program to either generate
  9835. type-specific code for collecting or to generate tables that can
  9836. guide the
  9837. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  9838. \end{enumerate}
  9839. Dynamically typed languages, such as Lisp, need to tag objects
  9840. anyways, so option 1 is a natural choice for those languages.
  9841. However, \LangVec{} is a statically typed language, so it would be
  9842. unfortunate to require tags on every object, especially small and
  9843. pervasive objects like integers and Booleans. Option 3 is the
  9844. best-performing choice for statically typed languages, but comes with
  9845. a relatively high implementation complexity. To keep this chapter
  9846. within a 2-week time budget, we recommend a combination of options 1
  9847. and 2, using separate strategies for the stack and the heap.
  9848. Regarding the stack, we recommend using a separate stack for pointers,
  9849. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  9850. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  9851. is, when a local variable needs to be spilled and is of type
  9852. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  9853. stack instead of the normal procedure call stack. Furthermore, we
  9854. always spill vector-typed variables if they are live during a call to
  9855. the collector, thereby ensuring that no pointers are in registers
  9856. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  9857. example from Figure~\ref{fig:copying-collector} and contrasts it with
  9858. the data layout using a root stack. The root stack contains the two
  9859. pointers from the regular stack and also the pointer in the second
  9860. register.
  9861. \begin{figure}[tbp]
  9862. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  9863. \caption{Maintaining a root stack to facilitate garbage collection.}
  9864. \label{fig:shadow-stack}
  9865. \end{figure}
  9866. The problem of distinguishing between pointers and other kinds of data
  9867. also arises inside of each tuple on the heap. We solve this problem by
  9868. attaching a tag, an extra 64-bits, to each
  9869. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  9870. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  9871. that we have drawn the bits in a big-endian way, from right-to-left,
  9872. with bit location 0 (the least significant bit) on the far right,
  9873. which corresponds to the direction of the x86 shifting instructions
  9874. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  9875. is dedicated to specifying which elements of the tuple are pointers,
  9876. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  9877. indicates there is a pointer and a 0 bit indicates some other kind of
  9878. data. The pointer mask starts at bit location 7. We have limited
  9879. tuples to a maximum size of 50 elements, so we just need 50 bits for
  9880. the pointer mask. The tag also contains two other pieces of
  9881. information. The length of the tuple (number of elements) is stored in
  9882. bits location 1 through 6. Finally, the bit at location 0 indicates
  9883. whether the tuple has yet to be copied to the ToSpace. If the bit has
  9884. value 1, then this tuple has not yet been copied. If the bit has
  9885. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  9886. of a pointer are always zero anyways because our tuples are 8-byte
  9887. aligned.)
  9888. \begin{figure}[tbp]
  9889. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  9890. \caption{Representation of tuples in the heap.}
  9891. \label{fig:tuple-rep}
  9892. \end{figure}
  9893. \subsection{Implementation of the Garbage Collector}
  9894. \label{sec:organize-gz}
  9895. \index{subject}{prelude}
  9896. An implementation of the copying collector is provided in the
  9897. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  9898. interface to the garbage collector that is used by the compiler. The
  9899. \code{initialize} function creates the FromSpace, ToSpace, and root
  9900. stack and should be called in the prelude of the \code{main}
  9901. function. The arguments of \code{initialize} are the root stack size
  9902. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  9903. good choice for both. The \code{initialize} function puts the address
  9904. of the beginning of the FromSpace into the global variable
  9905. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  9906. the address that is 1-past the last element of the FromSpace. (We use
  9907. half-open intervals to represent chunks of
  9908. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  9909. points to the first element of the root stack.
  9910. As long as there is room left in the FromSpace, your generated code
  9911. can allocate tuples simply by moving the \code{free\_ptr} forward.
  9912. %
  9913. The amount of room left in FromSpace is the difference between the
  9914. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  9915. function should be called when there is not enough room left in the
  9916. FromSpace for the next allocation. The \code{collect} function takes
  9917. a pointer to the current top of the root stack (one past the last item
  9918. that was pushed) and the number of bytes that need to be
  9919. allocated. The \code{collect} function performs the copying collection
  9920. and leaves the heap in a state such that the next allocation will
  9921. succeed.
  9922. \begin{figure}[tbp]
  9923. \begin{lstlisting}
  9924. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  9925. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  9926. int64_t* free_ptr;
  9927. int64_t* fromspace_begin;
  9928. int64_t* fromspace_end;
  9929. int64_t** rootstack_begin;
  9930. \end{lstlisting}
  9931. \caption{The compiler's interface to the garbage collector.}
  9932. \label{fig:gc-header}
  9933. \end{figure}
  9934. %% \begin{exercise}
  9935. %% In the file \code{runtime.c} you will find the implementation of
  9936. %% \code{initialize} and a partial implementation of \code{collect}.
  9937. %% The \code{collect} function calls another function, \code{cheney},
  9938. %% to perform the actual copy, and that function is left to the reader
  9939. %% to implement. The following is the prototype for \code{cheney}.
  9940. %% \begin{lstlisting}
  9941. %% static void cheney(int64_t** rootstack_ptr);
  9942. %% \end{lstlisting}
  9943. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  9944. %% rootstack (which is an array of pointers). The \code{cheney} function
  9945. %% also communicates with \code{collect} through the global
  9946. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  9947. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  9948. %% the ToSpace:
  9949. %% \begin{lstlisting}
  9950. %% static int64_t* tospace_begin;
  9951. %% static int64_t* tospace_end;
  9952. %% \end{lstlisting}
  9953. %% The job of the \code{cheney} function is to copy all the live
  9954. %% objects (reachable from the root stack) into the ToSpace, update
  9955. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  9956. %% update the root stack so that it points to the objects in the
  9957. %% ToSpace, and finally to swap the global pointers for the FromSpace
  9958. %% and ToSpace.
  9959. %% \end{exercise}
  9960. %% \section{Compiler Passes}
  9961. %% \label{sec:code-generation-gc}
  9962. The introduction of garbage collection has a non-trivial impact on our
  9963. compiler passes. We introduce a new compiler pass named
  9964. \code{expose-allocation}. We make
  9965. significant changes to \code{select-instructions},
  9966. \code{build-interference}, \code{allocate-registers}, and
  9967. \code{print\_x86} and make minor changes in several more passes. The
  9968. following program will serve as our running example. It creates two
  9969. tuples, one nested inside the other. Both tuples have length one. The
  9970. program accesses the element in the inner tuple tuple via two vector
  9971. references.
  9972. % tests/s2_17.rkt
  9973. \begin{lstlisting}
  9974. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  9975. \end{lstlisting}
  9976. \section{Shrink}
  9977. \label{sec:shrink-Rvec}
  9978. Recall that the \code{shrink} pass translates the primitives operators
  9979. into a smaller set of primitives. Because this pass comes after type
  9980. checking, but before the passes that require the type information in
  9981. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  9982. to wrap \code{HasType} around each AST node that it generates.
  9983. \section{Expose Allocation}
  9984. \label{sec:expose-allocation}
  9985. The pass \code{expose-allocation} lowers the \code{vector} creation
  9986. form into a conditional call to the collector followed by the
  9987. allocation. We choose to place the \code{expose-allocation} pass
  9988. before \code{remove\_complex\_operands} because the code generated by
  9989. \code{expose-allocation} contains complex operands. We also place
  9990. \code{expose-allocation} before \code{explicate\_control} because
  9991. \code{expose-allocation} introduces new variables using \code{let},
  9992. but \code{let} is gone after \code{explicate\_control}.
  9993. The output of \code{expose-allocation} is a language \LangAlloc{} that
  9994. extends \LangVec{} with the three new forms that we use in the translation
  9995. of the \code{vector} form.
  9996. \[
  9997. \begin{array}{lcl}
  9998. \Exp &::=& \cdots
  9999. \MID (\key{collect} \,\itm{int})
  10000. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10001. \MID (\key{global-value} \,\itm{name})
  10002. \end{array}
  10003. \]
  10004. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  10005. $n$ bytes. It will become a call to the \code{collect} function in
  10006. \code{runtime.c} in \code{select-instructions}. The
  10007. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  10008. \index{subject}{allocate}
  10009. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  10010. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  10011. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  10012. a global variable, such as \code{free\_ptr}.
  10013. In the following, we show the transformation for the \code{vector}
  10014. form into 1) a sequence of let-bindings for the initializing
  10015. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10016. \code{allocate}, and 4) the initialization of the vector. In the
  10017. following, \itm{len} refers to the length of the vector and
  10018. \itm{bytes} is how many total bytes need to be allocated for the
  10019. vector, which is 8 for the tag plus \itm{len} times 8.
  10020. \begin{lstlisting}
  10021. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10022. |$\Longrightarrow$|
  10023. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10024. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10025. (global-value fromspace_end))
  10026. (void)
  10027. (collect |\itm{bytes}|))])
  10028. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10029. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10030. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10031. |$v$|) ... )))) ...)
  10032. \end{lstlisting}
  10033. In the above, we suppressed all of the \code{has-type} forms in the
  10034. output for the sake of readability. The placement of the initializing
  10035. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  10036. sequence of \code{vector-set!} is important, as those expressions may
  10037. trigger garbage collection and we cannot have an allocated but
  10038. uninitialized tuple on the heap during a collection.
  10039. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10040. \code{expose-allocation} pass on our running example.
  10041. \begin{figure}[tbp]
  10042. % tests/s2_17.rkt
  10043. \begin{lstlisting}
  10044. (vector-ref
  10045. (vector-ref
  10046. (let ([vecinit7976
  10047. (let ([vecinit7972 42])
  10048. (let ([collectret7974
  10049. (if (< (+ (global-value free_ptr) 16)
  10050. (global-value fromspace_end))
  10051. (void)
  10052. (collect 16)
  10053. )])
  10054. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10055. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10056. alloc7971)
  10057. )
  10058. )
  10059. )
  10060. ])
  10061. (let ([collectret7978
  10062. (if (< (+ (global-value free_ptr) 16)
  10063. (global-value fromspace_end))
  10064. (void)
  10065. (collect 16)
  10066. )])
  10067. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10068. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10069. alloc7975)
  10070. )
  10071. )
  10072. )
  10073. 0)
  10074. 0)
  10075. \end{lstlisting}
  10076. \caption{Output of the \code{expose-allocation} pass, minus
  10077. all of the \code{has-type} forms.}
  10078. \label{fig:expose-alloc-output}
  10079. \end{figure}
  10080. \section{Remove Complex Operands}
  10081. \label{sec:remove-complex-opera-Rvec}
  10082. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  10083. should all be treated as complex operands.
  10084. %% A new case for
  10085. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10086. %% handled carefully to prevent the \code{Prim} node from being separated
  10087. %% from its enclosing \code{HasType}.
  10088. Figure~\ref{fig:Rvec-anf-syntax}
  10089. shows the grammar for the output language \LangVecANF{} of this
  10090. pass, which is \LangVec{} in administrative normal form.
  10091. \begin{figure}[tp]
  10092. \centering
  10093. \fbox{
  10094. \begin{minipage}{0.96\textwidth}
  10095. \small
  10096. \[
  10097. \begin{array}{rcl}
  10098. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  10099. \MID \VOID{} \\
  10100. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10101. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10102. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10103. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10104. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10105. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  10106. \MID \LP\key{GlobalValue}~\Var\RP\\
  10107. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10108. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10109. \end{array}
  10110. \]
  10111. \end{minipage}
  10112. }
  10113. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  10114. \label{fig:Rvec-anf-syntax}
  10115. \end{figure}
  10116. \section{Explicate Control and the \LangCVec{} language}
  10117. \label{sec:explicate-control-r3}
  10118. \begin{figure}[tp]
  10119. \fbox{
  10120. \begin{minipage}{0.96\textwidth}
  10121. \small
  10122. \[
  10123. \begin{array}{lcl}
  10124. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  10125. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  10126. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  10127. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  10128. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  10129. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10130. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  10131. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  10132. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  10133. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  10134. \MID \LP\key{Collect} \,\itm{int}\RP \\
  10135. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10136. \MID \GOTO{\itm{label}} } \\
  10137. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10138. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  10139. \end{array}
  10140. \]
  10141. \end{minipage}
  10142. }
  10143. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  10144. (Figure~\ref{fig:c1-syntax}).}
  10145. \label{fig:c2-syntax}
  10146. \end{figure}
  10147. The output of \code{explicate\_control} is a program in the
  10148. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10149. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  10150. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  10151. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  10152. \key{vector-set!}, and \key{global-value} expressions and the
  10153. \code{collect} statement. The \code{explicate\_control} pass can treat
  10154. these new forms much like the other expression forms that we've
  10155. already encoutered.
  10156. \section{Select Instructions and the \LangXGlobal{} Language}
  10157. \label{sec:select-instructions-gc}
  10158. \index{subject}{instruction selection}
  10159. %% void (rep as zero)
  10160. %% allocate
  10161. %% collect (callq collect)
  10162. %% vector-ref
  10163. %% vector-set!
  10164. %% global (postpone)
  10165. In this pass we generate x86 code for most of the new operations that
  10166. were needed to compile tuples, including \code{Allocate},
  10167. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  10168. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  10169. the later has a different concrete syntax (see
  10170. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  10171. \index{subject}{x86}
  10172. The \code{vector-ref} and \code{vector-set!} forms translate into
  10173. \code{movq} instructions. (The plus one in the offset is to get past
  10174. the tag at the beginning of the tuple representation.)
  10175. \begin{lstlisting}
  10176. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  10177. |$\Longrightarrow$|
  10178. movq |$\itm{vec}'$|, %r11
  10179. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10180. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  10181. |$\Longrightarrow$|
  10182. movq |$\itm{vec}'$|, %r11
  10183. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  10184. movq $0, |$\itm{lhs'}$|
  10185. \end{lstlisting}
  10186. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  10187. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  10188. register \code{r11} ensures that offset expression
  10189. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10190. removing \code{r11} from consideration by the register allocating.
  10191. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10192. \code{rax}. Then the generated code for \code{vector-set!} would be
  10193. \begin{lstlisting}
  10194. movq |$\itm{vec}'$|, %rax
  10195. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  10196. movq $0, |$\itm{lhs}'$|
  10197. \end{lstlisting}
  10198. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  10199. \code{patch-instructions} would insert a move through \code{rax}
  10200. as follows.
  10201. \begin{lstlisting}
  10202. movq |$\itm{vec}'$|, %rax
  10203. movq |$\itm{arg}'$|, %rax
  10204. movq %rax, |$8(n+1)$|(%rax)
  10205. movq $0, |$\itm{lhs}'$|
  10206. \end{lstlisting}
  10207. But the above sequence of instructions does not work because we're
  10208. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  10209. $\itm{arg}'$) at the same time!
  10210. We compile the \code{allocate} form to operations on the
  10211. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10212. is the next free address in the FromSpace, so we copy it into
  10213. \code{r11} and then move it forward by enough space for the tuple
  10214. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10215. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10216. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10217. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10218. tag is organized. We recommend using the Racket operations
  10219. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  10220. during compilation. The type annotation in the \code{vector} form is
  10221. used to determine the pointer mask region of the tag.
  10222. \begin{lstlisting}
  10223. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  10224. |$\Longrightarrow$|
  10225. movq free_ptr(%rip), %r11
  10226. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10227. movq $|$\itm{tag}$|, 0(%r11)
  10228. movq %r11, |$\itm{lhs}'$|
  10229. \end{lstlisting}
  10230. The \code{collect} form is compiled to a call to the \code{collect}
  10231. function in the runtime. The arguments to \code{collect} are 1) the
  10232. top of the root stack and 2) the number of bytes that need to be
  10233. allocated. We use another dedicated register, \code{r15}, to
  10234. store the pointer to the top of the root stack. So \code{r15} is not
  10235. available for use by the register allocator.
  10236. \begin{lstlisting}
  10237. (collect |$\itm{bytes}$|)
  10238. |$\Longrightarrow$|
  10239. movq %r15, %rdi
  10240. movq $|\itm{bytes}|, %rsi
  10241. callq collect
  10242. \end{lstlisting}
  10243. \begin{figure}[tp]
  10244. \fbox{
  10245. \begin{minipage}{0.96\textwidth}
  10246. \[
  10247. \begin{array}{lcl}
  10248. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  10249. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  10250. & & \gray{ \key{main:} \; \Instr\ldots }
  10251. \end{array}
  10252. \]
  10253. \end{minipage}
  10254. }
  10255. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  10256. \label{fig:x86-2-concrete}
  10257. \end{figure}
  10258. \begin{figure}[tp]
  10259. \fbox{
  10260. \begin{minipage}{0.96\textwidth}
  10261. \small
  10262. \[
  10263. \begin{array}{lcl}
  10264. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  10265. \MID \BYTEREG{\Reg}} \\
  10266. &\MID& (\key{Global}~\Var) \\
  10267. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  10268. \end{array}
  10269. \]
  10270. \end{minipage}
  10271. }
  10272. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  10273. \label{fig:x86-2}
  10274. \end{figure}
  10275. The concrete and abstract syntax of the \LangXGlobal{} language is
  10276. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  10277. differs from \LangXIf{} just in the addition of the form for global
  10278. variables.
  10279. %
  10280. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  10281. \code{select-instructions} pass on the running example.
  10282. \begin{figure}[tbp]
  10283. \centering
  10284. % tests/s2_17.rkt
  10285. \begin{minipage}[t]{0.5\textwidth}
  10286. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10287. block35:
  10288. movq free_ptr(%rip), alloc9024
  10289. addq $16, free_ptr(%rip)
  10290. movq alloc9024, %r11
  10291. movq $131, 0(%r11)
  10292. movq alloc9024, %r11
  10293. movq vecinit9025, 8(%r11)
  10294. movq $0, initret9026
  10295. movq alloc9024, %r11
  10296. movq 8(%r11), tmp9034
  10297. movq tmp9034, %r11
  10298. movq 8(%r11), %rax
  10299. jmp conclusion
  10300. block36:
  10301. movq $0, collectret9027
  10302. jmp block35
  10303. block38:
  10304. movq free_ptr(%rip), alloc9020
  10305. addq $16, free_ptr(%rip)
  10306. movq alloc9020, %r11
  10307. movq $3, 0(%r11)
  10308. movq alloc9020, %r11
  10309. movq vecinit9021, 8(%r11)
  10310. movq $0, initret9022
  10311. movq alloc9020, vecinit9025
  10312. movq free_ptr(%rip), tmp9031
  10313. movq tmp9031, tmp9032
  10314. addq $16, tmp9032
  10315. movq fromspace_end(%rip), tmp9033
  10316. cmpq tmp9033, tmp9032
  10317. jl block36
  10318. jmp block37
  10319. block37:
  10320. movq %r15, %rdi
  10321. movq $16, %rsi
  10322. callq 'collect
  10323. jmp block35
  10324. block39:
  10325. movq $0, collectret9023
  10326. jmp block38
  10327. \end{lstlisting}
  10328. \end{minipage}
  10329. \begin{minipage}[t]{0.45\textwidth}
  10330. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10331. start:
  10332. movq $42, vecinit9021
  10333. movq free_ptr(%rip), tmp9028
  10334. movq tmp9028, tmp9029
  10335. addq $16, tmp9029
  10336. movq fromspace_end(%rip), tmp9030
  10337. cmpq tmp9030, tmp9029
  10338. jl block39
  10339. jmp block40
  10340. block40:
  10341. movq %r15, %rdi
  10342. movq $16, %rsi
  10343. callq 'collect
  10344. jmp block38
  10345. \end{lstlisting}
  10346. \end{minipage}
  10347. \caption{Output of the \code{select-instructions} pass.}
  10348. \label{fig:select-instr-output-gc}
  10349. \end{figure}
  10350. \clearpage
  10351. \section{Register Allocation}
  10352. \label{sec:reg-alloc-gc}
  10353. \index{subject}{register allocation}
  10354. As discussed earlier in this chapter, the garbage collector needs to
  10355. access all the pointers in the root set, that is, all variables that
  10356. are vectors. It will be the responsibility of the register allocator
  10357. to make sure that:
  10358. \begin{enumerate}
  10359. \item the root stack is used for spilling vector-typed variables, and
  10360. \item if a vector-typed variable is live during a call to the
  10361. collector, it must be spilled to ensure it is visible to the
  10362. collector.
  10363. \end{enumerate}
  10364. The later responsibility can be handled during construction of the
  10365. interference graph, by adding interference edges between the call-live
  10366. vector-typed variables and all the callee-saved registers. (They
  10367. already interfere with the caller-saved registers.) The type
  10368. information for variables is in the \code{Program} form, so we
  10369. recommend adding another parameter to the \code{build-interference}
  10370. function to communicate this alist.
  10371. The spilling of vector-typed variables to the root stack can be
  10372. handled after graph coloring, when choosing how to assign the colors
  10373. (integers) to registers and stack locations. The \code{Program} output
  10374. of this pass changes to also record the number of spills to the root
  10375. stack.
  10376. % build-interference
  10377. %
  10378. % callq
  10379. % extra parameter for var->type assoc. list
  10380. % update 'program' and 'if'
  10381. % allocate-registers
  10382. % allocate spilled vectors to the rootstack
  10383. % don't change color-graph
  10384. \section{Print x86}
  10385. \label{sec:print-x86-gc}
  10386. \index{subject}{prelude}\index{subject}{conclusion}
  10387. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  10388. \code{print\_x86} pass on the running example. In the prelude and
  10389. conclusion of the \code{main} function, we treat the root stack very
  10390. much like the regular stack in that we move the root stack pointer
  10391. (\code{r15}) to make room for the spills to the root stack, except
  10392. that the root stack grows up instead of down. For the running
  10393. example, there was just one spill so we increment \code{r15} by 8
  10394. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  10395. One issue that deserves special care is that there may be a call to
  10396. \code{collect} prior to the initializing assignments for all the
  10397. variables in the root stack. We do not want the garbage collector to
  10398. accidentally think that some uninitialized variable is a pointer that
  10399. needs to be followed. Thus, we zero-out all locations on the root
  10400. stack in the prelude of \code{main}. In
  10401. Figure~\ref{fig:print-x86-output-gc}, the instruction
  10402. %
  10403. \lstinline{movq $0, (%r15)}
  10404. %
  10405. accomplishes this task. The garbage collector tests each root to see
  10406. if it is null prior to dereferencing it.
  10407. \begin{figure}[htbp]
  10408. \begin{minipage}[t]{0.5\textwidth}
  10409. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10410. block35:
  10411. movq free_ptr(%rip), %rcx
  10412. addq $16, free_ptr(%rip)
  10413. movq %rcx, %r11
  10414. movq $131, 0(%r11)
  10415. movq %rcx, %r11
  10416. movq -8(%r15), %rax
  10417. movq %rax, 8(%r11)
  10418. movq $0, %rdx
  10419. movq %rcx, %r11
  10420. movq 8(%r11), %rcx
  10421. movq %rcx, %r11
  10422. movq 8(%r11), %rax
  10423. jmp conclusion
  10424. block36:
  10425. movq $0, %rcx
  10426. jmp block35
  10427. block38:
  10428. movq free_ptr(%rip), %rcx
  10429. addq $16, free_ptr(%rip)
  10430. movq %rcx, %r11
  10431. movq $3, 0(%r11)
  10432. movq %rcx, %r11
  10433. movq %rbx, 8(%r11)
  10434. movq $0, %rdx
  10435. movq %rcx, -8(%r15)
  10436. movq free_ptr(%rip), %rcx
  10437. addq $16, %rcx
  10438. movq fromspace_end(%rip), %rdx
  10439. cmpq %rdx, %rcx
  10440. jl block36
  10441. movq %r15, %rdi
  10442. movq $16, %rsi
  10443. callq collect
  10444. jmp block35
  10445. block39:
  10446. movq $0, %rcx
  10447. jmp block38
  10448. \end{lstlisting}
  10449. \end{minipage}
  10450. \begin{minipage}[t]{0.45\textwidth}
  10451. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10452. start:
  10453. movq $42, %rbx
  10454. movq free_ptr(%rip), %rdx
  10455. addq $16, %rdx
  10456. movq fromspace_end(%rip), %rcx
  10457. cmpq %rcx, %rdx
  10458. jl block39
  10459. movq %r15, %rdi
  10460. movq $16, %rsi
  10461. callq collect
  10462. jmp block38
  10463. .globl main
  10464. main:
  10465. pushq %rbp
  10466. movq %rsp, %rbp
  10467. pushq %r13
  10468. pushq %r12
  10469. pushq %rbx
  10470. pushq %r14
  10471. subq $0, %rsp
  10472. movq $16384, %rdi
  10473. movq $16384, %rsi
  10474. callq initialize
  10475. movq rootstack_begin(%rip), %r15
  10476. movq $0, (%r15)
  10477. addq $8, %r15
  10478. jmp start
  10479. conclusion:
  10480. subq $8, %r15
  10481. addq $0, %rsp
  10482. popq %r14
  10483. popq %rbx
  10484. popq %r12
  10485. popq %r13
  10486. popq %rbp
  10487. retq
  10488. \end{lstlisting}
  10489. \end{minipage}
  10490. \caption{Output of the \code{print\_x86} pass.}
  10491. \label{fig:print-x86-output-gc}
  10492. \end{figure}
  10493. \begin{figure}[p]
  10494. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10495. \node (Rvec) at (0,2) {\large \LangVec{}};
  10496. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  10497. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  10498. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  10499. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  10500. \node (C2-4) at (3,0) {\large \LangCVec{}};
  10501. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  10502. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  10503. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  10504. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  10505. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  10506. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  10507. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  10508. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  10509. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  10510. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  10511. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  10512. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  10513. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  10514. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10515. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10516. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10517. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  10518. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10519. \end{tikzpicture}
  10520. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  10521. \label{fig:Rvec-passes}
  10522. \end{figure}
  10523. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  10524. for the compilation of \LangVec{}.
  10525. \section{Challenge: Simple Structures}
  10526. \label{sec:simple-structures}
  10527. \index{subject}{struct}
  10528. \index{subject}{structure}
  10529. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  10530. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  10531. Recall that a \code{struct} in Typed Racket is a user-defined data
  10532. type that contains named fields and that is heap allocated, similar to
  10533. a vector. The following is an example of a structure definition, in
  10534. this case the definition of a \code{point} type.
  10535. \begin{lstlisting}
  10536. (struct point ([x : Integer] [y : Integer]) #:mutable)
  10537. \end{lstlisting}
  10538. \begin{figure}[tbp]
  10539. \centering
  10540. \fbox{
  10541. \begin{minipage}{0.96\textwidth}
  10542. \[
  10543. \begin{array}{lcl}
  10544. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  10545. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  10546. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  10547. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  10548. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  10549. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  10550. \MID (\key{and}\;\Exp\;\Exp)
  10551. \MID (\key{or}\;\Exp\;\Exp)
  10552. \MID (\key{not}\;\Exp) } \\
  10553. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  10554. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  10555. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  10556. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  10557. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  10558. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  10559. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  10560. \LangStruct{} &::=& \Def \ldots \; \Exp
  10561. \end{array}
  10562. \]
  10563. \end{minipage}
  10564. }
  10565. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  10566. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  10567. \label{fig:r3s-concrete-syntax}
  10568. \end{figure}
  10569. An instance of a structure is created using function call syntax, with
  10570. the name of the structure in the function position:
  10571. \begin{lstlisting}
  10572. (point 7 12)
  10573. \end{lstlisting}
  10574. Function-call syntax is also used to read the value in a field of a
  10575. structure. The function name is formed by the structure name, a dash,
  10576. and the field name. The following example uses \code{point-x} and
  10577. \code{point-y} to access the \code{x} and \code{y} fields of two point
  10578. instances.
  10579. \begin{center}
  10580. \begin{lstlisting}
  10581. (let ([pt1 (point 7 12)])
  10582. (let ([pt2 (point 4 3)])
  10583. (+ (- (point-x pt1) (point-x pt2))
  10584. (- (point-y pt1) (point-y pt2)))))
  10585. \end{lstlisting}
  10586. \end{center}
  10587. Similarly, to write to a field of a structure, use its set function,
  10588. whose name starts with \code{set-}, followed by the structure name,
  10589. then a dash, then the field name, and concluded with an exclamation
  10590. mark. The following example uses \code{set-point-x!} to change the
  10591. \code{x} field from \code{7} to \code{42}.
  10592. \begin{center}
  10593. \begin{lstlisting}
  10594. (let ([pt (point 7 12)])
  10595. (let ([_ (set-point-x! pt 42)])
  10596. (point-x pt)))
  10597. \end{lstlisting}
  10598. \end{center}
  10599. \begin{exercise}\normalfont
  10600. Extend your compiler with support for simple structures, compiling
  10601. \LangStruct{} to x86 assembly code. Create five new test cases that use
  10602. structures and test your compiler.
  10603. \end{exercise}
  10604. \section{Challenge: Generational Collection}
  10605. The copying collector described in Section~\ref{sec:GC} can incur
  10606. significant runtime overhead because the call to \code{collect} takes
  10607. time proportional to all of the live data. One way to reduce this
  10608. overhead is to reduce how much data is inspected in each call to
  10609. \code{collect}. In particular, researchers have observed that recently
  10610. allocated data is more likely to become garbage then data that has
  10611. survived one or more previous calls to \code{collect}. This insight
  10612. motivated the creation of \emph{generational garbage collectors}
  10613. \index{subject}{generational garbage collector} that
  10614. 1) segregates data according to its age into two or more generations,
  10615. 2) allocates less space for younger generations, so collecting them is
  10616. faster, and more space for the older generations, and 3) performs
  10617. collection on the younger generations more frequently then for older
  10618. generations~\citep{Wilson:1992fk}.
  10619. For this challenge assignment, the goal is to adapt the copying
  10620. collector implemented in \code{runtime.c} to use two generations, one
  10621. for young data and one for old data. Each generation consists of a
  10622. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  10623. \code{collect} function to use the two generations.
  10624. \begin{enumerate}
  10625. \item Copy the young generation's FromSpace to its ToSpace then switch
  10626. the role of the ToSpace and FromSpace
  10627. \item If there is enough space for the requested number of bytes in
  10628. the young FromSpace, then return from \code{collect}.
  10629. \item If there is not enough space in the young FromSpace for the
  10630. requested bytes, then move the data from the young generation to the
  10631. old one with the following steps:
  10632. \begin{enumerate}
  10633. \item If there is enough room in the old FromSpace, copy the young
  10634. FromSpace to the old FromSpace and then return.
  10635. \item If there is not enough room in the old FromSpace, then collect
  10636. the old generation by copying the old FromSpace to the old ToSpace
  10637. and swap the roles of the old FromSpace and ToSpace.
  10638. \item If there is enough room now, copy the young FromSpace to the
  10639. old FromSpace and return. Otherwise, allocate a larger FromSpace
  10640. and ToSpace for the old generation. Copy the young FromSpace and
  10641. the old FromSpace into the larger FromSpace for the old
  10642. generation and then return.
  10643. \end{enumerate}
  10644. \end{enumerate}
  10645. We recommend that you generalize the \code{cheney} function so that it
  10646. can be used for all the copies mentioned above: between the young
  10647. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  10648. between the young FromSpace and old FromSpace. This can be
  10649. accomplished by adding parameters to \code{cheney} that replace its
  10650. use of the global variables \code{fromspace\_begin},
  10651. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  10652. Note that the collection of the young generation does not traverse the
  10653. old generation. This introduces a potential problem: there may be
  10654. young data that is only reachable through pointers in the old
  10655. generation. If these pointers are not taken into account, the
  10656. collector could throw away young data that is live! One solution,
  10657. called \emph{pointer recording}, is to maintain a set of all the
  10658. pointers from the old generation into the new generation and consider
  10659. this set as part of the root set. To maintain this set, the compiler
  10660. must insert extra instructions around every \code{vector-set!}. If the
  10661. vector being modified is in the old generation, and if the value being
  10662. written is a pointer into the new generation, than that pointer must
  10663. be added to the set. Also, if the value being overwritten was a
  10664. pointer into the new generation, then that pointer should be removed
  10665. from the set.
  10666. \begin{exercise}\normalfont
  10667. Adapt the \code{collect} function in \code{runtime.c} to implement
  10668. generational garbage collection, as outlined in this section.
  10669. Update the code generation for \code{vector-set!} to implement
  10670. pointer recording. Make sure that your new compiler and runtime
  10671. passes your test suite.
  10672. \end{exercise}
  10673. % Further Reading
  10674. \fi % racketEd
  10675. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10676. \chapter{Functions}
  10677. \label{ch:Rfun}
  10678. \index{subject}{function}
  10679. \if\edition\racketEd
  10680. This chapter studies the compilation of functions similar to those
  10681. found in the C language. This corresponds to a subset of Typed Racket
  10682. in which only top-level function definitions are allowed. This kind of
  10683. function is an important stepping stone to implementing
  10684. lexically-scoped functions, that is, \key{lambda} abstractions, which
  10685. is the topic of Chapter~\ref{ch:Rlam}.
  10686. \section{The \LangFun{} Language}
  10687. The concrete and abstract syntax for function definitions and function
  10688. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  10689. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  10690. \LangFun{} begin with zero or more function definitions. The function
  10691. names from these definitions are in-scope for the entire program,
  10692. including all other function definitions (so the ordering of function
  10693. definitions does not matter). The concrete syntax for function
  10694. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  10695. where the first expression must
  10696. evaluate to a function and the rest are the arguments.
  10697. The abstract syntax for function application is
  10698. $\APPLY{\Exp}{\Exp\ldots}$.
  10699. %% The syntax for function application does not include an explicit
  10700. %% keyword, which is error prone when using \code{match}. To alleviate
  10701. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  10702. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  10703. Functions are first-class in the sense that a function pointer
  10704. \index{subject}{function pointer} is data and can be stored in memory or passed
  10705. as a parameter to another function. Thus, we introduce a function
  10706. type, written
  10707. \begin{lstlisting}
  10708. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  10709. \end{lstlisting}
  10710. for a function whose $n$ parameters have the types $\Type_1$ through
  10711. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  10712. these functions (with respect to Racket functions) is that they are
  10713. not lexically scoped. That is, the only external entities that can be
  10714. referenced from inside a function body are other globally-defined
  10715. functions. The syntax of \LangFun{} prevents functions from being nested
  10716. inside each other.
  10717. \begin{figure}[tp]
  10718. \centering
  10719. \fbox{
  10720. \begin{minipage}{0.96\textwidth}
  10721. \small
  10722. \[
  10723. \begin{array}{lcl}
  10724. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  10725. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  10726. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  10727. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  10728. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  10729. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  10730. \MID (\key{and}\;\Exp\;\Exp)
  10731. \MID (\key{or}\;\Exp\;\Exp)
  10732. \MID (\key{not}\;\Exp)} \\
  10733. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  10734. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  10735. (\key{vector-ref}\;\Exp\;\Int)} \\
  10736. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  10737. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  10738. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  10739. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  10740. \LangFunM{} &::=& \Def \ldots \; \Exp
  10741. \end{array}
  10742. \]
  10743. \end{minipage}
  10744. }
  10745. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  10746. \label{fig:Rfun-concrete-syntax}
  10747. \end{figure}
  10748. \begin{figure}[tp]
  10749. \centering
  10750. \fbox{
  10751. \begin{minipage}{0.96\textwidth}
  10752. \small
  10753. \[
  10754. \begin{array}{lcl}
  10755. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  10756. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10757. &\MID& \gray{ \BOOL{\itm{bool}}
  10758. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  10759. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  10760. \MID \APPLY{\Exp}{\Exp\ldots}\\
  10761. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  10762. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  10763. \end{array}
  10764. \]
  10765. \end{minipage}
  10766. }
  10767. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  10768. \label{fig:Rfun-syntax}
  10769. \end{figure}
  10770. The program in Figure~\ref{fig:Rfun-function-example} is a
  10771. representative example of defining and using functions in \LangFun{}. We
  10772. define a function \code{map-vec} that applies some other function
  10773. \code{f} to both elements of a vector and returns a new
  10774. vector containing the results. We also define a function \code{add1}.
  10775. The program applies
  10776. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  10777. \code{(vector 1 42)}, from which we return the \code{42}.
  10778. \begin{figure}[tbp]
  10779. \begin{lstlisting}
  10780. (define (map-vec [f : (Integer -> Integer)]
  10781. [v : (Vector Integer Integer)])
  10782. : (Vector Integer Integer)
  10783. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10784. (define (add1 [x : Integer]) : Integer
  10785. (+ x 1))
  10786. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10787. \end{lstlisting}
  10788. \caption{Example of using functions in \LangFun{}.}
  10789. \label{fig:Rfun-function-example}
  10790. \end{figure}
  10791. The definitional interpreter for \LangFun{} is in
  10792. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  10793. responsible for setting up the mutual recursion between the top-level
  10794. function definitions. We use the classic back-patching \index{subject}{back-patching}
  10795. approach that uses mutable variables and makes two passes over the function
  10796. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  10797. top-level environment using a mutable cons cell for each function
  10798. definition. Note that the \code{lambda} value for each function is
  10799. incomplete; it does not yet include the environment. Once the
  10800. top-level environment is constructed, we then iterate over it and
  10801. update the \code{lambda} values to use the top-level environment.
  10802. \begin{figure}[tp]
  10803. \begin{lstlisting}
  10804. (define interp-Rfun_class
  10805. (class interp-Rvec_class
  10806. (super-new)
  10807. (define/override ((interp-exp env) e)
  10808. (define recur (interp-exp env))
  10809. (match e
  10810. [(Var x) (unbox (dict-ref env x))]
  10811. [(Let x e body)
  10812. (define new-env (dict-set env x (box (recur e))))
  10813. ((interp-exp new-env) body)]
  10814. [(Apply fun args)
  10815. (define fun-val (recur fun))
  10816. (define arg-vals (for/list ([e args]) (recur e)))
  10817. (match fun-val
  10818. [`(function (,xs ...) ,body ,fun-env)
  10819. (define params-args (for/list ([x xs] [arg arg-vals])
  10820. (cons x (box arg))))
  10821. (define new-env (append params-args fun-env))
  10822. ((interp-exp new-env) body)]
  10823. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  10824. [else ((super interp-exp env) e)]
  10825. ))
  10826. (define/public (interp-def d)
  10827. (match d
  10828. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  10829. (cons f (box `(function ,xs ,body ())))]))
  10830. (define/override (interp-program p)
  10831. (match p
  10832. [(ProgramDefsExp info ds body)
  10833. (let ([top-level (for/list ([d ds]) (interp-def d))])
  10834. (for/list ([f (in-dict-values top-level)])
  10835. (set-box! f (match (unbox f)
  10836. [`(function ,xs ,body ())
  10837. `(function ,xs ,body ,top-level)])))
  10838. ((interp-exp top-level) body))]))
  10839. ))
  10840. (define (interp-Rfun p)
  10841. (send (new interp-Rfun_class) interp-program p))
  10842. \end{lstlisting}
  10843. \caption{Interpreter for the \LangFun{} language.}
  10844. \label{fig:interp-Rfun}
  10845. \end{figure}
  10846. %\margincomment{TODO: explain type checker}
  10847. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  10848. \begin{figure}[tp]
  10849. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10850. (define type-check-Rfun_class
  10851. (class type-check-Rvec_class
  10852. (super-new)
  10853. (inherit check-type-equal?)
  10854. (define/public (type-check-apply env e es)
  10855. (define-values (e^ ty) ((type-check-exp env) e))
  10856. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  10857. ((type-check-exp env) e)))
  10858. (match ty
  10859. [`(,ty^* ... -> ,rt)
  10860. (for ([arg-ty ty*] [param-ty ty^*])
  10861. (check-type-equal? arg-ty param-ty (Apply e es)))
  10862. (values e^ e* rt)]))
  10863. (define/override (type-check-exp env)
  10864. (lambda (e)
  10865. (match e
  10866. [(FunRef f)
  10867. (values (FunRef f) (dict-ref env f))]
  10868. [(Apply e es)
  10869. (define-values (e^ es^ rt) (type-check-apply env e es))
  10870. (values (Apply e^ es^) rt)]
  10871. [(Call e es)
  10872. (define-values (e^ es^ rt) (type-check-apply env e es))
  10873. (values (Call e^ es^) rt)]
  10874. [else ((super type-check-exp env) e)])))
  10875. (define/public (type-check-def env)
  10876. (lambda (e)
  10877. (match e
  10878. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  10879. (define new-env (append (map cons xs ps) env))
  10880. (define-values (body^ ty^) ((type-check-exp new-env) body))
  10881. (check-type-equal? ty^ rt body)
  10882. (Def f p:t* rt info body^)])))
  10883. (define/public (fun-def-type d)
  10884. (match d
  10885. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  10886. (define/override (type-check-program e)
  10887. (match e
  10888. [(ProgramDefsExp info ds body)
  10889. (define new-env (for/list ([d ds])
  10890. (cons (Def-name d) (fun-def-type d))))
  10891. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  10892. (define-values (body^ ty) ((type-check-exp new-env) body))
  10893. (check-type-equal? ty 'Integer body)
  10894. (ProgramDefsExp info ds^ body^)]))))
  10895. (define (type-check-Rfun p)
  10896. (send (new type-check-Rfun_class) type-check-program p))
  10897. \end{lstlisting}
  10898. \caption{Type checker for the \LangFun{} language.}
  10899. \label{fig:type-check-Rfun}
  10900. \end{figure}
  10901. \section{Functions in x86}
  10902. \label{sec:fun-x86}
  10903. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  10904. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  10905. %% \margincomment{\tiny Talk about the return address on the
  10906. %% stack and what callq and retq does.\\ --Jeremy }
  10907. The x86 architecture provides a few features to support the
  10908. implementation of functions. We have already seen that x86 provides
  10909. labels so that one can refer to the location of an instruction, as is
  10910. needed for jump instructions. Labels can also be used to mark the
  10911. beginning of the instructions for a function. Going further, we can
  10912. obtain the address of a label by using the \key{leaq} instruction and
  10913. PC-relative addressing. For example, the following puts the
  10914. address of the \code{add1} label into the \code{rbx} register.
  10915. \begin{lstlisting}
  10916. leaq add1(%rip), %rbx
  10917. \end{lstlisting}
  10918. The instruction pointer register \key{rip} (aka. the program counter
  10919. \index{subject}{program counter}) always points to the next instruction to be
  10920. executed. When combined with an label, as in \code{add1(\%rip)}, the
  10921. linker computes the distance $d$ between the address of \code{add1}
  10922. and where the \code{rip} would be at that moment and then changes
  10923. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  10924. the address of \code{add1}.
  10925. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  10926. jump to a function whose location is given by a label. To support
  10927. function calls in this chapter we instead will be jumping to a
  10928. function whose location is given by an address in a register, that is,
  10929. we need to make an \emph{indirect function call}. The x86 syntax for
  10930. this is a \code{callq} instruction but with an asterisk before the
  10931. register name.\index{subject}{indirect function call}
  10932. \begin{lstlisting}
  10933. callq *%rbx
  10934. \end{lstlisting}
  10935. \subsection{Calling Conventions}
  10936. \index{subject}{calling conventions}
  10937. The \code{callq} instruction provides partial support for implementing
  10938. functions: it pushes the return address on the stack and it jumps to
  10939. the target. However, \code{callq} does not handle
  10940. \begin{enumerate}
  10941. \item parameter passing,
  10942. \item pushing frames on the procedure call stack and popping them off,
  10943. or
  10944. \item determining how registers are shared by different functions.
  10945. \end{enumerate}
  10946. Regarding (1) parameter passing, recall that the following six
  10947. registers are used to pass arguments to a function, in this order.
  10948. \begin{lstlisting}
  10949. rdi rsi rdx rcx r8 r9
  10950. \end{lstlisting}
  10951. If there are
  10952. more than six arguments, then the convention is to use space on the
  10953. frame of the caller for the rest of the arguments. However, to ease
  10954. the implementation of efficient tail calls
  10955. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  10956. arguments.
  10957. %
  10958. Also recall that the register \code{rax} is for the return value of
  10959. the function.
  10960. \index{subject}{prelude}\index{subject}{conclusion}
  10961. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  10962. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  10963. the stack grows down, with each function call using a chunk of space
  10964. called a frame. The caller sets the stack pointer, register
  10965. \code{rsp}, to the last data item in its frame. The callee must not
  10966. change anything in the caller's frame, that is, anything that is at or
  10967. above the stack pointer. The callee is free to use locations that are
  10968. below the stack pointer.
  10969. Recall that we are storing variables of vector type on the root stack.
  10970. So the prelude needs to move the root stack pointer \code{r15} up and
  10971. the conclusion needs to move the root stack pointer back down. Also,
  10972. the prelude must initialize to \code{0} this frame's slots in the root
  10973. stack to signal to the garbage collector that those slots do not yet
  10974. contain a pointer to a vector. Otherwise the garbage collector will
  10975. interpret the garbage bits in those slots as memory addresses and try
  10976. to traverse them, causing serious mayhem!
  10977. Regarding (3) the sharing of registers between different functions,
  10978. recall from Section~\ref{sec:calling-conventions} that the registers
  10979. are divided into two groups, the caller-saved registers and the
  10980. callee-saved registers. The caller should assume that all the
  10981. caller-saved registers get overwritten with arbitrary values by the
  10982. callee. That is why we recommend in
  10983. Section~\ref{sec:calling-conventions} that variables that are live
  10984. during a function call should not be assigned to caller-saved
  10985. registers.
  10986. On the flip side, if the callee wants to use a callee-saved register,
  10987. the callee must save the contents of those registers on their stack
  10988. frame and then put them back prior to returning to the caller. That
  10989. is why we recommended in Section~\ref{sec:calling-conventions} that if
  10990. the register allocator assigns a variable to a callee-saved register,
  10991. then the prelude of the \code{main} function must save that register
  10992. to the stack and the conclusion of \code{main} must restore it. This
  10993. recommendation now generalizes to all functions.
  10994. Also recall that the base pointer, register \code{rbp}, is used as a
  10995. point-of-reference within a frame, so that each local variable can be
  10996. accessed at a fixed offset from the base pointer
  10997. (Section~\ref{sec:x86}).
  10998. %
  10999. Figure~\ref{fig:call-frames} shows the general layout of the caller
  11000. and callee frames.
  11001. \begin{figure}[tbp]
  11002. \centering
  11003. \begin{tabular}{r|r|l|l} \hline
  11004. Caller View & Callee View & Contents & Frame \\ \hline
  11005. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  11006. 0(\key{\%rbp}) & & old \key{rbp} \\
  11007. -8(\key{\%rbp}) & & callee-saved $1$ \\
  11008. \ldots & & \ldots \\
  11009. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  11010. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  11011. \ldots & & \ldots \\
  11012. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  11013. %% & & \\
  11014. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  11015. %% & \ldots & \ldots \\
  11016. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  11017. \hline
  11018. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  11019. & 0(\key{\%rbp}) & old \key{rbp} \\
  11020. & -8(\key{\%rbp}) & callee-saved $1$ \\
  11021. & \ldots & \ldots \\
  11022. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  11023. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  11024. & \ldots & \ldots \\
  11025. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  11026. \end{tabular}
  11027. \caption{Memory layout of caller and callee frames.}
  11028. \label{fig:call-frames}
  11029. \end{figure}
  11030. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  11031. %% local variables and for storing the values of callee-saved registers
  11032. %% (we shall refer to all of these collectively as ``locals''), and that
  11033. %% at the beginning of a function we move the stack pointer \code{rsp}
  11034. %% down to make room for them.
  11035. %% We recommend storing the local variables
  11036. %% first and then the callee-saved registers, so that the local variables
  11037. %% can be accessed using \code{rbp} the same as before the addition of
  11038. %% functions.
  11039. %% To make additional room for passing arguments, we shall
  11040. %% move the stack pointer even further down. We count how many stack
  11041. %% arguments are needed for each function call that occurs inside the
  11042. %% body of the function and find their maximum. Adding this number to the
  11043. %% number of locals gives us how much the \code{rsp} should be moved at
  11044. %% the beginning of the function. In preparation for a function call, we
  11045. %% offset from \code{rsp} to set up the stack arguments. We put the first
  11046. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  11047. %% so on.
  11048. %% Upon calling the function, the stack arguments are retrieved by the
  11049. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  11050. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  11051. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  11052. %% the layout of the caller and callee frames. Notice how important it is
  11053. %% that we correctly compute the maximum number of arguments needed for
  11054. %% function calls; if that number is too small then the arguments and
  11055. %% local variables will smash into each other!
  11056. \subsection{Efficient Tail Calls}
  11057. \label{sec:tail-call}
  11058. In general, the amount of stack space used by a program is determined
  11059. by the longest chain of nested function calls. That is, if function
  11060. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  11061. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  11062. $n$ can grow quite large in the case of recursive or mutually
  11063. recursive functions. However, in some cases we can arrange to use only
  11064. constant space, i.e. $O(1)$, instead of $O(n)$.
  11065. If a function call is the last action in a function body, then that
  11066. call is said to be a \emph{tail call}\index{subject}{tail call}.
  11067. For example, in the following
  11068. program, the recursive call to \code{tail-sum} is a tail call.
  11069. \begin{center}
  11070. \begin{lstlisting}
  11071. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  11072. (if (eq? n 0)
  11073. r
  11074. (tail-sum (- n 1) (+ n r))))
  11075. (+ (tail-sum 5 0) 27)
  11076. \end{lstlisting}
  11077. \end{center}
  11078. At a tail call, the frame of the caller is no longer needed, so we
  11079. can pop the caller's frame before making the tail call. With this
  11080. approach, a recursive function that only makes tail calls will only
  11081. use $O(1)$ stack space. Functional languages like Racket typically
  11082. rely heavily on recursive functions, so they typically guarantee that
  11083. all tail calls will be optimized in this way.
  11084. \index{subject}{frame}
  11085. However, some care is needed with regards to argument passing in tail
  11086. calls. As mentioned above, for arguments beyond the sixth, the
  11087. convention is to use space in the caller's frame for passing
  11088. arguments. But for a tail call we pop the caller's frame and can no
  11089. longer use it. Another alternative is to use space in the callee's
  11090. frame for passing arguments. However, this option is also problematic
  11091. because the caller and callee's frame overlap in memory. As we begin
  11092. to copy the arguments from their sources in the caller's frame, the
  11093. target locations in the callee's frame might overlap with the sources
  11094. for later arguments! We solve this problem by using the heap instead
  11095. of the stack for passing more than six arguments, as we describe in
  11096. the Section~\ref{sec:limit-functions-r4}.
  11097. As mentioned above, for a tail call we pop the caller's frame prior to
  11098. making the tail call. The instructions for popping a frame are the
  11099. instructions that we usually place in the conclusion of a
  11100. function. Thus, we also need to place such code immediately before
  11101. each tail call. These instructions include restoring the callee-saved
  11102. registers, so it is good that the argument passing registers are all
  11103. caller-saved registers.
  11104. One last note regarding which instruction to use to make the tail
  11105. call. When the callee is finished, it should not return to the current
  11106. function, but it should return to the function that called the current
  11107. one. Thus, the return address that is already on the stack is the
  11108. right one, and we should not use \key{callq} to make the tail call, as
  11109. that would unnecessarily overwrite the return address. Instead we can
  11110. simply use the \key{jmp} instruction. Like the indirect function call,
  11111. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  11112. prefixed with an asterisk. We recommend using \code{rax} to hold the
  11113. jump target because the preceding conclusion overwrites just about
  11114. everything else.
  11115. \begin{lstlisting}
  11116. jmp *%rax
  11117. \end{lstlisting}
  11118. \section{Shrink \LangFun{}}
  11119. \label{sec:shrink-r4}
  11120. The \code{shrink} pass performs a minor modification to ease the
  11121. later passes. This pass introduces an explicit \code{main} function
  11122. and changes the top \code{ProgramDefsExp} form to
  11123. \code{ProgramDefs} as follows.
  11124. \begin{lstlisting}
  11125. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  11126. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  11127. \end{lstlisting}
  11128. where $\itm{mainDef}$ is
  11129. \begin{lstlisting}
  11130. (Def 'main '() 'Integer '() |$\Exp'$|)
  11131. \end{lstlisting}
  11132. \section{Reveal Functions and the \LangFunRef{} language}
  11133. \label{sec:reveal-functions-r4}
  11134. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  11135. respect: it conflates the use of function names and local
  11136. variables. This is a problem because we need to compile the use of a
  11137. function name differently than the use of a local variable; we need to
  11138. use \code{leaq} to convert the function name (a label in x86) to an
  11139. address in a register. Thus, it is a good idea to create a new pass
  11140. that changes function references from just a symbol $f$ to
  11141. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  11142. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  11143. The concrete syntax for a function reference is $\CFUNREF{f}$.
  11144. \begin{figure}[tp]
  11145. \centering
  11146. \fbox{
  11147. \begin{minipage}{0.96\textwidth}
  11148. \[
  11149. \begin{array}{lcl}
  11150. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  11151. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11152. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  11153. \end{array}
  11154. \]
  11155. \end{minipage}
  11156. }
  11157. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  11158. (Figure~\ref{fig:Rfun-syntax}).}
  11159. \label{fig:f1-syntax}
  11160. \end{figure}
  11161. %% Distinguishing between calls in tail position and non-tail position
  11162. %% requires the pass to have some notion of context. We recommend using
  11163. %% two mutually recursive functions, one for processing expressions in
  11164. %% tail position and another for the rest.
  11165. Placing this pass after \code{uniquify} will make sure that there are
  11166. no local variables and functions that share the same name. On the
  11167. other hand, \code{reveal-functions} needs to come before the
  11168. \code{explicate\_control} pass because that pass helps us compile
  11169. \code{FunRef} forms into assignment statements.
  11170. \section{Limit Functions}
  11171. \label{sec:limit-functions-r4}
  11172. Recall that we wish to limit the number of function parameters to six
  11173. so that we do not need to use the stack for argument passing, which
  11174. makes it easier to implement efficient tail calls. However, because
  11175. the input language \LangFun{} supports arbitrary numbers of function
  11176. arguments, we have some work to do!
  11177. This pass transforms functions and function calls that involve more
  11178. than six arguments to pass the first five arguments as usual, but it
  11179. packs the rest of the arguments into a vector and passes it as the
  11180. sixth argument.
  11181. Each function definition with too many parameters is transformed as
  11182. follows.
  11183. \begin{lstlisting}
  11184. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  11185. |$\Rightarrow$|
  11186. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  11187. \end{lstlisting}
  11188. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  11189. the occurrences of the later parameters with vector references.
  11190. \begin{lstlisting}
  11191. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  11192. \end{lstlisting}
  11193. For function calls with too many arguments, the \code{limit-functions}
  11194. pass transforms them in the following way.
  11195. \begin{tabular}{lll}
  11196. \begin{minipage}{0.2\textwidth}
  11197. \begin{lstlisting}
  11198. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  11199. \end{lstlisting}
  11200. \end{minipage}
  11201. &
  11202. $\Rightarrow$
  11203. &
  11204. \begin{minipage}{0.4\textwidth}
  11205. \begin{lstlisting}
  11206. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  11207. \end{lstlisting}
  11208. \end{minipage}
  11209. \end{tabular}
  11210. \section{Remove Complex Operands}
  11211. \label{sec:rco-r4}
  11212. The primary decisions to make for this pass is whether to classify
  11213. \code{FunRef} and \code{Apply} as either atomic or complex
  11214. expressions. Recall that a simple expression will eventually end up as
  11215. just an immediate argument of an x86 instruction. Function
  11216. application will be translated to a sequence of instructions, so
  11217. \code{Apply} must be classified as complex expression.
  11218. On the other hand, the arguments of \code{Apply} should be
  11219. atomic expressions.
  11220. %
  11221. Regarding \code{FunRef}, as discussed above, the function label needs
  11222. to be converted to an address using the \code{leaq} instruction. Thus,
  11223. even though \code{FunRef} seems rather simple, it needs to be
  11224. classified as a complex expression so that we generate an assignment
  11225. statement with a left-hand side that can serve as the target of the
  11226. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  11227. output language \LangFunANF{} of this pass.
  11228. \begin{figure}[tp]
  11229. \centering
  11230. \fbox{
  11231. \begin{minipage}{0.96\textwidth}
  11232. \small
  11233. \[
  11234. \begin{array}{rcl}
  11235. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  11236. \MID \VOID{} } \\
  11237. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  11238. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  11239. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  11240. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  11241. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  11242. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  11243. \MID \LP\key{GlobalValue}~\Var\RP }\\
  11244. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  11245. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11246. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  11247. \end{array}
  11248. \]
  11249. \end{minipage}
  11250. }
  11251. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  11252. \label{fig:Rfun-anf-syntax}
  11253. \end{figure}
  11254. \section{Explicate Control and the \LangCFun{} language}
  11255. \label{sec:explicate-control-r4}
  11256. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  11257. output of \code{explicate\_control}. (The concrete syntax is given in
  11258. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  11259. functions for assignment and tail contexts should be updated with
  11260. cases for \code{Apply} and \code{FunRef} and the function for
  11261. predicate context should be updated for \code{Apply} but not
  11262. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  11263. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  11264. tail position \code{Apply} becomes \code{TailCall}. We recommend
  11265. defining a new auxiliary function for processing function definitions.
  11266. This code is similar to the case for \code{Program} in \LangVec{}. The
  11267. top-level \code{explicate\_control} function that handles the
  11268. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  11269. all the function definitions.
  11270. \begin{figure}[tp]
  11271. \fbox{
  11272. \begin{minipage}{0.96\textwidth}
  11273. \small
  11274. \[
  11275. \begin{array}{lcl}
  11276. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  11277. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  11278. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  11279. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  11280. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  11281. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  11282. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  11283. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  11284. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  11285. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  11286. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  11287. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  11288. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  11289. \MID \GOTO{\itm{label}} } \\
  11290. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  11291. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  11292. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  11293. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11294. \end{array}
  11295. \]
  11296. \end{minipage}
  11297. }
  11298. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  11299. \label{fig:c3-syntax}
  11300. \end{figure}
  11301. \section{Select Instructions and the \LangXIndCall{} Language}
  11302. \label{sec:select-r4}
  11303. \index{subject}{instruction selection}
  11304. The output of select instructions is a program in the \LangXIndCall{}
  11305. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  11306. \index{subject}{x86}
  11307. \begin{figure}[tp]
  11308. \fbox{
  11309. \begin{minipage}{0.96\textwidth}
  11310. \small
  11311. \[
  11312. \begin{array}{lcl}
  11313. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  11314. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  11315. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  11316. \Instr &::=& \ldots
  11317. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  11318. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  11319. \Block &::= & \Instr\ldots \\
  11320. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  11321. \LangXIndCallM{} &::= & \Def\ldots
  11322. \end{array}
  11323. \]
  11324. \end{minipage}
  11325. }
  11326. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  11327. \label{fig:x86-3-concrete}
  11328. \end{figure}
  11329. \begin{figure}[tp]
  11330. \fbox{
  11331. \begin{minipage}{0.96\textwidth}
  11332. \small
  11333. \[
  11334. \begin{array}{lcl}
  11335. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11336. \MID \BYTEREG{\Reg} } \\
  11337. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  11338. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  11339. \MID \TAILJMP{\Arg}{\itm{int}}\\
  11340. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  11341. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  11342. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  11343. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11344. \end{array}
  11345. \]
  11346. \end{minipage}
  11347. }
  11348. \caption{The abstract syntax of \LangXIndCall{} (extends
  11349. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  11350. \label{fig:x86-3}
  11351. \end{figure}
  11352. An assignment of a function reference to a variable becomes a
  11353. load-effective-address instruction as follows: \\
  11354. \begin{tabular}{lcl}
  11355. \begin{minipage}{0.35\textwidth}
  11356. \begin{lstlisting}
  11357. |$\itm{lhs}$| = (fun-ref |$f$|);
  11358. \end{lstlisting}
  11359. \end{minipage}
  11360. &
  11361. $\Rightarrow$\qquad\qquad
  11362. &
  11363. \begin{minipage}{0.3\textwidth}
  11364. \begin{lstlisting}
  11365. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  11366. \end{lstlisting}
  11367. \end{minipage}
  11368. \end{tabular} \\
  11369. Regarding function definitions, we need to remove the parameters and
  11370. instead perform parameter passing using the conventions discussed in
  11371. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  11372. registers. We recommend turning the parameters into local variables
  11373. and generating instructions at the beginning of the function to move
  11374. from the argument passing registers to these local variables.
  11375. \begin{lstlisting}
  11376. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  11377. |$\Rightarrow$|
  11378. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  11379. \end{lstlisting}
  11380. The $G'$ control-flow graph is the same as $G$ except that the
  11381. \code{start} block is modified to add the instructions for moving from
  11382. the argument registers to the parameter variables. So the \code{start}
  11383. block of $G$ shown on the left is changed to the code on the right.
  11384. \begin{center}
  11385. \begin{minipage}{0.3\textwidth}
  11386. \begin{lstlisting}
  11387. start:
  11388. |$\itm{instr}_1$|
  11389. |$\vdots$|
  11390. |$\itm{instr}_n$|
  11391. \end{lstlisting}
  11392. \end{minipage}
  11393. $\Rightarrow$
  11394. \begin{minipage}{0.3\textwidth}
  11395. \begin{lstlisting}
  11396. start:
  11397. movq %rdi, |$x_1$|
  11398. movq %rsi, |$x_2$|
  11399. |$\vdots$|
  11400. |$\itm{instr}_1$|
  11401. |$\vdots$|
  11402. |$\itm{instr}_n$|
  11403. \end{lstlisting}
  11404. \end{minipage}
  11405. \end{center}
  11406. By changing the parameters to local variables, we are giving the
  11407. register allocator control over which registers or stack locations to
  11408. use for them. If you implemented the move-biasing challenge
  11409. (Section~\ref{sec:move-biasing}), the register allocator will try to
  11410. assign the parameter variables to the corresponding argument register,
  11411. in which case the \code{patch-instructions} pass will remove the
  11412. \code{movq} instruction. This happens in the example translation in
  11413. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  11414. the \code{add} function.
  11415. %
  11416. Also, note that the register allocator will perform liveness analysis
  11417. on this sequence of move instructions and build the interference
  11418. graph. So, for example, $x_1$ will be marked as interfering with
  11419. \code{rsi} and that will prevent the assignment of $x_1$ to
  11420. \code{rsi}, which is good, because that would overwrite the argument
  11421. that needs to move into $x_2$.
  11422. Next, consider the compilation of function calls. In the mirror image
  11423. of handling the parameters of function definitions, the arguments need
  11424. to be moved to the argument passing registers. The function call
  11425. itself is performed with an indirect function call. The return value
  11426. from the function is stored in \code{rax}, so it needs to be moved
  11427. into the \itm{lhs}.
  11428. \begin{lstlisting}
  11429. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  11430. |$\Rightarrow$|
  11431. movq |$\itm{arg}_1$|, %rdi
  11432. movq |$\itm{arg}_2$|, %rsi
  11433. |$\vdots$|
  11434. callq *|\itm{fun}|
  11435. movq %rax, |\itm{lhs}|
  11436. \end{lstlisting}
  11437. The \code{IndirectCallq} AST node includes an integer for the arity of
  11438. the function, i.e., the number of parameters. That information is
  11439. useful in the \code{uncover-live} pass for determining which
  11440. argument-passing registers are potentially read during the call.
  11441. For tail calls, the parameter passing is the same as non-tail calls:
  11442. generate instructions to move the arguments into to the argument
  11443. passing registers. After that we need to pop the frame from the
  11444. procedure call stack. However, we do not yet know how big the frame
  11445. is; that gets determined during register allocation. So instead of
  11446. generating those instructions here, we invent a new instruction that
  11447. means ``pop the frame and then do an indirect jump'', which we name
  11448. \code{TailJmp}. The abstract syntax for this instruction includes an
  11449. argument that specifies where to jump and an integer that represents
  11450. the arity of the function being called.
  11451. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  11452. using the label \code{start} for the initial block of a program, and
  11453. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  11454. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  11455. can be compiled to an assignment to \code{rax} followed by a jump to
  11456. \code{conclusion}. With the addition of function definitions, we will
  11457. have a starting block and conclusion for each function, but their
  11458. labels need to be unique. We recommend prepending the function's name
  11459. to \code{start} and \code{conclusion}, respectively, to obtain unique
  11460. labels. (Alternatively, one could \code{gensym} labels for the start
  11461. and conclusion and store them in the $\itm{info}$ field of the
  11462. function definition.)
  11463. \section{Register Allocation}
  11464. \label{sec:register-allocation-r4}
  11465. \subsection{Liveness Analysis}
  11466. \label{sec:liveness-analysis-r4}
  11467. \index{subject}{liveness analysis}
  11468. %% The rest of the passes need only minor modifications to handle the new
  11469. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  11470. %% \code{leaq}.
  11471. The \code{IndirectCallq} instruction should be treated like
  11472. \code{Callq} regarding its written locations $W$, in that they should
  11473. include all the caller-saved registers. Recall that the reason for
  11474. that is to force call-live variables to be assigned to callee-saved
  11475. registers or to be spilled to the stack.
  11476. Regarding the set of read locations $R$ the arity field of
  11477. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  11478. argument-passing registers should be considered as read by those
  11479. instructions.
  11480. \subsection{Build Interference Graph}
  11481. \label{sec:build-interference-r4}
  11482. With the addition of function definitions, we compute an interference
  11483. graph for each function (not just one for the whole program).
  11484. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  11485. spill vector-typed variables that are live during a call to the
  11486. \code{collect}. With the addition of functions to our language, we
  11487. need to revisit this issue. Many functions perform allocation and
  11488. therefore have calls to the collector inside of them. Thus, we should
  11489. not only spill a vector-typed variable when it is live during a call
  11490. to \code{collect}, but we should spill the variable if it is live
  11491. during any function call. Thus, in the \code{build-interference} pass,
  11492. we recommend adding interference edges between call-live vector-typed
  11493. variables and the callee-saved registers (in addition to the usual
  11494. addition of edges between call-live variables and the caller-saved
  11495. registers).
  11496. \subsection{Allocate Registers}
  11497. The primary change to the \code{allocate-registers} pass is adding an
  11498. auxiliary function for handling definitions (the \Def{} non-terminal
  11499. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  11500. logic is the same as described in
  11501. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  11502. allocation is performed many times, once for each function definition,
  11503. instead of just once for the whole program.
  11504. \section{Patch Instructions}
  11505. In \code{patch-instructions}, you should deal with the x86
  11506. idiosyncrasy that the destination argument of \code{leaq} must be a
  11507. register. Additionally, you should ensure that the argument of
  11508. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  11509. code generation more convenient, because we trample many registers
  11510. before the tail call (as explained in the next section).
  11511. \section{Print x86}
  11512. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  11513. \code{IndirectCallq} are straightforward: output their concrete
  11514. syntax.
  11515. \begin{lstlisting}
  11516. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  11517. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  11518. \end{lstlisting}
  11519. The \code{TailJmp} node requires a bit work. A straightforward
  11520. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  11521. before the jump we need to pop the current frame. This sequence of
  11522. instructions is the same as the code for the conclusion of a function,
  11523. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  11524. Regarding function definitions, you will need to generate a prelude
  11525. and conclusion for each one. This code is similar to the prelude and
  11526. conclusion that you generated for the \code{main} function in
  11527. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  11528. should carry out the following steps.
  11529. \begin{enumerate}
  11530. \item Start with \code{.global} and \code{.align} directives followed
  11531. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  11532. example.)
  11533. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  11534. pointer.
  11535. \item Push to the stack all of the callee-saved registers that were
  11536. used for register allocation.
  11537. \item Move the stack pointer \code{rsp} down by the size of the stack
  11538. frame for this function, which depends on the number of regular
  11539. spills. (Aligned to 16 bytes.)
  11540. \item Move the root stack pointer \code{r15} up by the size of the
  11541. root-stack frame for this function, which depends on the number of
  11542. spilled vectors. \label{root-stack-init}
  11543. \item Initialize to zero all of the entries in the root-stack frame.
  11544. \item Jump to the start block.
  11545. \end{enumerate}
  11546. The prelude of the \code{main} function has one additional task: call
  11547. the \code{initialize} function to set up the garbage collector and
  11548. move the value of the global \code{rootstack\_begin} in
  11549. \code{r15}. This should happen before step \ref{root-stack-init}
  11550. above, which depends on \code{r15}.
  11551. The conclusion of every function should do the following.
  11552. \begin{enumerate}
  11553. \item Move the stack pointer back up by the size of the stack frame
  11554. for this function.
  11555. \item Restore the callee-saved registers by popping them from the
  11556. stack.
  11557. \item Move the root stack pointer back down by the size of the
  11558. root-stack frame for this function.
  11559. \item Restore \code{rbp} by popping it from the stack.
  11560. \item Return to the caller with the \code{retq} instruction.
  11561. \end{enumerate}
  11562. \begin{exercise}\normalfont
  11563. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  11564. Create 5 new programs that use functions, including examples that pass
  11565. functions and return functions from other functions, recursive
  11566. functions, functions that create vectors, and functions that make tail
  11567. calls. Test your compiler on these new programs and all of your
  11568. previously created test programs.
  11569. \end{exercise}
  11570. \begin{figure}[tbp]
  11571. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11572. \node (Rfun) at (0,2) {\large \LangFun{}};
  11573. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  11574. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  11575. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  11576. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  11577. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  11578. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  11579. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  11580. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11581. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11582. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11583. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11584. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11585. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11586. \path[->,bend left=15] (Rfun) edge [above] node
  11587. {\ttfamily\footnotesize shrink} (Rfun-1);
  11588. \path[->,bend left=15] (Rfun-1) edge [above] node
  11589. {\ttfamily\footnotesize uniquify} (Rfun-2);
  11590. \path[->,bend left=15] (Rfun-2) edge [right] node
  11591. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  11592. \path[->,bend left=15] (F1-1) edge [below] node
  11593. {\ttfamily\footnotesize limit-functions} (F1-2);
  11594. \path[->,bend right=15] (F1-2) edge [above] node
  11595. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  11596. \path[->,bend right=15] (F1-3) edge [above] node
  11597. {\ttfamily\footnotesize remove-complex.} (F1-4);
  11598. \path[->,bend left=15] (F1-4) edge [right] node
  11599. {\ttfamily\footnotesize explicate-control} (C3-2);
  11600. \path[->,bend right=15] (C3-2) edge [left] node
  11601. {\ttfamily\footnotesize select-instr.} (x86-2);
  11602. \path[->,bend left=15] (x86-2) edge [left] node
  11603. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11604. \path[->,bend right=15] (x86-2-1) edge [below] node
  11605. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11606. \path[->,bend right=15] (x86-2-2) edge [left] node
  11607. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11608. \path[->,bend left=15] (x86-3) edge [above] node
  11609. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11610. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  11611. \end{tikzpicture}
  11612. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  11613. \label{fig:Rfun-passes}
  11614. \end{figure}
  11615. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  11616. compiling \LangFun{} to x86.
  11617. \section{An Example Translation}
  11618. \label{sec:functions-example}
  11619. Figure~\ref{fig:add-fun} shows an example translation of a simple
  11620. function in \LangFun{} to x86. The figure also includes the results of the
  11621. \code{explicate\_control} and \code{select-instructions} passes.
  11622. \begin{figure}[htbp]
  11623. \begin{tabular}{ll}
  11624. \begin{minipage}{0.5\textwidth}
  11625. % s3_2.rkt
  11626. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11627. (define (add [x : Integer] [y : Integer])
  11628. : Integer
  11629. (+ x y))
  11630. (add 40 2)
  11631. \end{lstlisting}
  11632. $\Downarrow$
  11633. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11634. (define (add86 [x87 : Integer]
  11635. [y88 : Integer]) : Integer
  11636. add86start:
  11637. return (+ x87 y88);
  11638. )
  11639. (define (main) : Integer ()
  11640. mainstart:
  11641. tmp89 = (fun-ref add86);
  11642. (tail-call tmp89 40 2)
  11643. )
  11644. \end{lstlisting}
  11645. \end{minipage}
  11646. &
  11647. $\Rightarrow$
  11648. \begin{minipage}{0.5\textwidth}
  11649. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11650. (define (add86) : Integer
  11651. add86start:
  11652. movq %rdi, x87
  11653. movq %rsi, y88
  11654. movq x87, %rax
  11655. addq y88, %rax
  11656. jmp add11389conclusion
  11657. )
  11658. (define (main) : Integer
  11659. mainstart:
  11660. leaq (fun-ref add86), tmp89
  11661. movq $40, %rdi
  11662. movq $2, %rsi
  11663. tail-jmp tmp89
  11664. )
  11665. \end{lstlisting}
  11666. $\Downarrow$
  11667. \end{minipage}
  11668. \end{tabular}
  11669. \begin{tabular}{ll}
  11670. \begin{minipage}{0.3\textwidth}
  11671. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11672. .globl add86
  11673. .align 16
  11674. add86:
  11675. pushq %rbp
  11676. movq %rsp, %rbp
  11677. jmp add86start
  11678. add86start:
  11679. movq %rdi, %rax
  11680. addq %rsi, %rax
  11681. jmp add86conclusion
  11682. add86conclusion:
  11683. popq %rbp
  11684. retq
  11685. \end{lstlisting}
  11686. \end{minipage}
  11687. &
  11688. \begin{minipage}{0.5\textwidth}
  11689. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11690. .globl main
  11691. .align 16
  11692. main:
  11693. pushq %rbp
  11694. movq %rsp, %rbp
  11695. movq $16384, %rdi
  11696. movq $16384, %rsi
  11697. callq initialize
  11698. movq rootstack_begin(%rip), %r15
  11699. jmp mainstart
  11700. mainstart:
  11701. leaq add86(%rip), %rcx
  11702. movq $40, %rdi
  11703. movq $2, %rsi
  11704. movq %rcx, %rax
  11705. popq %rbp
  11706. jmp *%rax
  11707. mainconclusion:
  11708. popq %rbp
  11709. retq
  11710. \end{lstlisting}
  11711. \end{minipage}
  11712. \end{tabular}
  11713. \caption{Example compilation of a simple function to x86.}
  11714. \label{fig:add-fun}
  11715. \end{figure}
  11716. % Challenge idea: inlining! (simple version)
  11717. % Further Reading
  11718. \fi % racketEd
  11719. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11720. \chapter{Lexically Scoped Functions}
  11721. \label{ch:Rlam}
  11722. \index{subject}{lambda}
  11723. \index{subject}{lexical scoping}
  11724. \if\edition\racketEd
  11725. This chapter studies lexically scoped functions as they appear in
  11726. functional languages such as Racket. By lexical scoping we mean that a
  11727. function's body may refer to variables whose binding site is outside
  11728. of the function, in an enclosing scope.
  11729. %
  11730. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  11731. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  11732. \key{lambda} form. The body of the \key{lambda}, refers to three
  11733. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  11734. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  11735. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  11736. parameter of function \code{f}. The \key{lambda} is returned from the
  11737. function \code{f}. The main expression of the program includes two
  11738. calls to \code{f} with different arguments for \code{x}, first
  11739. \code{5} then \code{3}. The functions returned from \code{f} are bound
  11740. to variables \code{g} and \code{h}. Even though these two functions
  11741. were created by the same \code{lambda}, they are really different
  11742. functions because they use different values for \code{x}. Applying
  11743. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  11744. \code{15} produces \code{22}. The result of this program is \code{42}.
  11745. \begin{figure}[btp]
  11746. % s4_6.rkt
  11747. \begin{lstlisting}
  11748. (define (f [x : Integer]) : (Integer -> Integer)
  11749. (let ([y 4])
  11750. (lambda: ([z : Integer]) : Integer
  11751. (+ x (+ y z)))))
  11752. (let ([g (f 5)])
  11753. (let ([h (f 3)])
  11754. (+ (g 11) (h 15))))
  11755. \end{lstlisting}
  11756. \caption{Example of a lexically scoped function.}
  11757. \label{fig:lexical-scoping}
  11758. \end{figure}
  11759. The approach that we take for implementing lexically scoped
  11760. functions is to compile them into top-level function definitions,
  11761. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  11762. provide special treatment for variable occurrences such as \code{x}
  11763. and \code{y} in the body of the \code{lambda} of
  11764. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  11765. refer to variables defined outside of it. To identify such variable
  11766. occurrences, we review the standard notion of free variable.
  11767. \begin{definition}
  11768. A variable is \emph{free in expression} $e$ if the variable occurs
  11769. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  11770. variable}
  11771. \end{definition}
  11772. For example, in the expression \code{(+ x (+ y z))} the variables
  11773. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  11774. only \code{x} and \code{y} are free in the following expression
  11775. because \code{z} is bound by the \code{lambda}.
  11776. \begin{lstlisting}
  11777. (lambda: ([z : Integer]) : Integer
  11778. (+ x (+ y z)))
  11779. \end{lstlisting}
  11780. So the free variables of a \code{lambda} are the ones that will need
  11781. special treatment. We need to arrange for some way to transport, at
  11782. runtime, the values of those variables from the point where the
  11783. \code{lambda} was created to the point where the \code{lambda} is
  11784. applied. An efficient solution to the problem, due to
  11785. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  11786. free variables together with the function pointer for the lambda's
  11787. code, an arrangement called a \emph{flat closure} (which we shorten to
  11788. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  11789. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  11790. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  11791. pointers. The function pointer resides at index $0$ and the
  11792. values for the free variables will fill in the rest of the vector.
  11793. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  11794. how closures work. It's a three-step dance. The program first calls
  11795. function \code{f}, which creates a closure for the \code{lambda}. The
  11796. closure is a vector whose first element is a pointer to the top-level
  11797. function that we will generate for the \code{lambda}, the second
  11798. element is the value of \code{x}, which is \code{5}, and the third
  11799. element is \code{4}, the value of \code{y}. The closure does not
  11800. contain an element for \code{z} because \code{z} is not a free
  11801. variable of the \code{lambda}. Creating the closure is step 1 of the
  11802. dance. The closure is returned from \code{f} and bound to \code{g}, as
  11803. shown in Figure~\ref{fig:closures}.
  11804. %
  11805. The second call to \code{f} creates another closure, this time with
  11806. \code{3} in the second slot (for \code{x}). This closure is also
  11807. returned from \code{f} but bound to \code{h}, which is also shown in
  11808. Figure~\ref{fig:closures}.
  11809. \begin{figure}[tbp]
  11810. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  11811. \caption{Example closure representation for the \key{lambda}'s
  11812. in Figure~\ref{fig:lexical-scoping}.}
  11813. \label{fig:closures}
  11814. \end{figure}
  11815. Continuing with the example, consider the application of \code{g} to
  11816. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  11817. obtain the function pointer in the first element of the closure and
  11818. call it, passing in the closure itself and then the regular arguments,
  11819. in this case \code{11}. This technique for applying a closure is step
  11820. 2 of the dance.
  11821. %
  11822. But doesn't this \code{lambda} only take 1 argument, for parameter
  11823. \code{z}? The third and final step of the dance is generating a
  11824. top-level function for a \code{lambda}. We add an additional
  11825. parameter for the closure and we insert a \code{let} at the beginning
  11826. of the function for each free variable, to bind those variables to the
  11827. appropriate elements from the closure parameter.
  11828. %
  11829. This three-step dance is known as \emph{closure conversion}. We
  11830. discuss the details of closure conversion in
  11831. Section~\ref{sec:closure-conversion} and the code generated from the
  11832. example in Section~\ref{sec:example-lambda}. But first we define the
  11833. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  11834. \section{The \LangLam{} Language}
  11835. \label{sec:r5}
  11836. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  11837. functions and lexical scoping, is defined in
  11838. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  11839. the \key{lambda} form to the grammar for \LangFun{}, which already has
  11840. syntax for function application.
  11841. \begin{figure}[tp]
  11842. \centering
  11843. \fbox{
  11844. \begin{minipage}{0.96\textwidth}
  11845. \small
  11846. \[
  11847. \begin{array}{lcl}
  11848. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  11849. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  11850. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  11851. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11852. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11853. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11854. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11855. \MID (\key{and}\;\Exp\;\Exp)
  11856. \MID (\key{or}\;\Exp\;\Exp)
  11857. \MID (\key{not}\;\Exp) } \\
  11858. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11859. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  11860. (\key{vector-ref}\;\Exp\;\Int)} \\
  11861. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11862. \MID (\Exp \; \Exp\ldots) } \\
  11863. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  11864. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  11865. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11866. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  11867. \end{array}
  11868. \]
  11869. \end{minipage}
  11870. }
  11871. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  11872. with \key{lambda}.}
  11873. \label{fig:Rlam-concrete-syntax}
  11874. \end{figure}
  11875. \begin{figure}[tp]
  11876. \centering
  11877. \fbox{
  11878. \begin{minipage}{0.96\textwidth}
  11879. \small
  11880. \[
  11881. \begin{array}{lcl}
  11882. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  11883. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11884. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11885. &\MID& \gray{ \BOOL{\itm{bool}}
  11886. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11887. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  11888. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  11889. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  11890. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  11891. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11892. \end{array}
  11893. \]
  11894. \end{minipage}
  11895. }
  11896. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  11897. \label{fig:Rlam-syntax}
  11898. \end{figure}
  11899. \index{subject}{interpreter}
  11900. \label{sec:interp-Rlambda}
  11901. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  11902. \LangLam{}. The case for \key{lambda} saves the current environment
  11903. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  11904. the environment from the \key{lambda}, the \code{lam-env}, when
  11905. interpreting the body of the \key{lambda}. The \code{lam-env}
  11906. environment is extended with the mapping of parameters to argument
  11907. values.
  11908. \begin{figure}[tbp]
  11909. \begin{lstlisting}
  11910. (define interp-Rlambda_class
  11911. (class interp-Rfun_class
  11912. (super-new)
  11913. (define/override (interp-op op)
  11914. (match op
  11915. ['procedure-arity
  11916. (lambda (v)
  11917. (match v
  11918. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  11919. [else (error 'interp-op "expected a function, not ~a" v)]))]
  11920. [else (super interp-op op)]))
  11921. (define/override ((interp-exp env) e)
  11922. (define recur (interp-exp env))
  11923. (match e
  11924. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  11925. `(function ,xs ,body ,env)]
  11926. [else ((super interp-exp env) e)]))
  11927. ))
  11928. (define (interp-Rlambda p)
  11929. (send (new interp-Rlambda_class) interp-program p))
  11930. \end{lstlisting}
  11931. \caption{Interpreter for \LangLam{}.}
  11932. \label{fig:interp-Rlambda}
  11933. \end{figure}
  11934. \label{sec:type-check-r5}
  11935. \index{subject}{type checking}
  11936. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  11937. \key{lambda} form. The body of the \key{lambda} is checked in an
  11938. environment that includes the current environment (because it is
  11939. lexically scoped) and also includes the \key{lambda}'s parameters. We
  11940. require the body's type to match the declared return type.
  11941. \begin{figure}[tbp]
  11942. \begin{lstlisting}
  11943. (define (type-check-Rlambda env)
  11944. (lambda (e)
  11945. (match e
  11946. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  11947. (define-values (new-body bodyT)
  11948. ((type-check-exp (append (map cons xs Ts) env)) body))
  11949. (define ty `(,@Ts -> ,rT))
  11950. (cond
  11951. [(equal? rT bodyT)
  11952. (values (HasType (Lambda params rT new-body) ty) ty)]
  11953. [else
  11954. (error "mismatch in return type" bodyT rT)])]
  11955. ...
  11956. )))
  11957. \end{lstlisting}
  11958. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  11959. \label{fig:type-check-Rlambda}
  11960. \end{figure}
  11961. \section{Reveal Functions and the $F_2$ language}
  11962. \label{sec:reveal-functions-r5}
  11963. To support the \code{procedure-arity} operator we need to communicate
  11964. the arity of a function to the point of closure creation. We can
  11965. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  11966. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  11967. output of this pass is the language $F_2$, whose syntax is defined in
  11968. Figure~\ref{fig:f2-syntax}.
  11969. \begin{figure}[tp]
  11970. \centering
  11971. \fbox{
  11972. \begin{minipage}{0.96\textwidth}
  11973. \[
  11974. \begin{array}{lcl}
  11975. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  11976. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11977. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  11978. \end{array}
  11979. \]
  11980. \end{minipage}
  11981. }
  11982. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  11983. (Figure~\ref{fig:Rlam-syntax}).}
  11984. \label{fig:f2-syntax}
  11985. \end{figure}
  11986. \section{Closure Conversion}
  11987. \label{sec:closure-conversion}
  11988. \index{subject}{closure conversion}
  11989. The compiling of lexically-scoped functions into top-level function
  11990. definitions is accomplished in the pass \code{convert-to-closures}
  11991. that comes after \code{reveal-functions} and before
  11992. \code{limit-functions}.
  11993. As usual, we implement the pass as a recursive function over the
  11994. AST. All of the action is in the cases for \key{Lambda} and
  11995. \key{Apply}. We transform a \key{Lambda} expression into an expression
  11996. that creates a closure, that is, a vector whose first element is a
  11997. function pointer and the rest of the elements are the free variables
  11998. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  11999. using \code{vector} so that we can distinguish closures from vectors
  12000. in Section~\ref{sec:optimize-closures} and to record the arity. In
  12001. the generated code below, the \itm{name} is a unique symbol generated
  12002. to identify the function and the \itm{arity} is the number of
  12003. parameters (the length of \itm{ps}).
  12004. \begin{lstlisting}
  12005. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  12006. |$\Rightarrow$|
  12007. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  12008. \end{lstlisting}
  12009. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  12010. create a top-level function definition for each \key{Lambda}, as
  12011. shown below.\\
  12012. \begin{minipage}{0.8\textwidth}
  12013. \begin{lstlisting}
  12014. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  12015. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  12016. ...
  12017. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  12018. |\itm{body'}|)...))
  12019. \end{lstlisting}
  12020. \end{minipage}\\
  12021. The \code{clos} parameter refers to the closure. Translate the type
  12022. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  12023. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  12024. $\itm{fvts}$ are the types of the free variables in the lambda and the
  12025. underscore \code{\_} is a dummy type that we use because it is rather
  12026. difficult to give a type to the function in the closure's
  12027. type.\footnote{To give an accurate type to a closure, we would need to
  12028. add existential types to the type checker~\citep{Minamide:1996ys}.}
  12029. The dummy type is considered to be equal to any other type during type
  12030. checking. The sequence of \key{Let} forms bind the free variables to
  12031. their values obtained from the closure.
  12032. Closure conversion turns functions into vectors, so the type
  12033. annotations in the program must also be translated. We recommend
  12034. defining a auxiliary recursive function for this purpose. Function
  12035. types should be translated as follows.
  12036. \begin{lstlisting}
  12037. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  12038. |$\Rightarrow$|
  12039. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  12040. \end{lstlisting}
  12041. The above type says that the first thing in the vector is a function
  12042. pointer. The first parameter of the function pointer is a vector (a
  12043. closure) and the rest of the parameters are the ones from the original
  12044. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  12045. the closure omits the types of the free variables because 1) those
  12046. types are not available in this context and 2) we do not need them in
  12047. the code that is generated for function application.
  12048. We transform function application into code that retrieves the
  12049. function pointer from the closure and then calls the function, passing
  12050. in the closure as the first argument. We bind $e'$ to a temporary
  12051. variable to avoid code duplication.
  12052. \begin{lstlisting}
  12053. (Apply |$e$| |\itm{es}|)
  12054. |$\Rightarrow$|
  12055. (Let |\itm{tmp}| |$e'$|
  12056. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  12057. \end{lstlisting}
  12058. There is also the question of what to do with references top-level
  12059. function definitions. To maintain a uniform translation of function
  12060. application, we turn function references into closures.
  12061. \begin{tabular}{lll}
  12062. \begin{minipage}{0.3\textwidth}
  12063. \begin{lstlisting}
  12064. (FunRefArity |$f$| |$n$|)
  12065. \end{lstlisting}
  12066. \end{minipage}
  12067. &
  12068. $\Rightarrow$
  12069. &
  12070. \begin{minipage}{0.5\textwidth}
  12071. \begin{lstlisting}
  12072. (Closure |$n$| (FunRef |$f$|) '())
  12073. \end{lstlisting}
  12074. \end{minipage}
  12075. \end{tabular} \\
  12076. %
  12077. The top-level function definitions need to be updated as well to take
  12078. an extra closure parameter.
  12079. \section{An Example Translation}
  12080. \label{sec:example-lambda}
  12081. Figure~\ref{fig:lexical-functions-example} shows the result of
  12082. \code{reveal-functions} and \code{convert-to-closures} for the example
  12083. program demonstrating lexical scoping that we discussed at the
  12084. beginning of this chapter.
  12085. \begin{figure}[tbp]
  12086. \begin{minipage}{0.8\textwidth}
  12087. % tests/lambda_test_6.rkt
  12088. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12089. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  12090. (let ([y8 4])
  12091. (lambda: ([z9 : Integer]) : Integer
  12092. (+ x7 (+ y8 z9)))))
  12093. (define (main) : Integer
  12094. (let ([g0 ((fun-ref-arity f6 1) 5)])
  12095. (let ([h1 ((fun-ref-arity f6 1) 3)])
  12096. (+ (g0 11) (h1 15)))))
  12097. \end{lstlisting}
  12098. $\Rightarrow$
  12099. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12100. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  12101. (let ([y8 4])
  12102. (closure 1 (list (fun-ref lambda2) x7 y8))))
  12103. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  12104. (let ([x7 (vector-ref fvs3 1)])
  12105. (let ([y8 (vector-ref fvs3 2)])
  12106. (+ x7 (+ y8 z9)))))
  12107. (define (main) : Integer
  12108. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  12109. ((vector-ref clos5 0) clos5 5))])
  12110. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  12111. ((vector-ref clos6 0) clos6 3))])
  12112. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  12113. \end{lstlisting}
  12114. \end{minipage}
  12115. \caption{Example of closure conversion.}
  12116. \label{fig:lexical-functions-example}
  12117. \end{figure}
  12118. \begin{exercise}\normalfont
  12119. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  12120. Create 5 new programs that use \key{lambda} functions and make use of
  12121. lexical scoping. Test your compiler on these new programs and all of
  12122. your previously created test programs.
  12123. \end{exercise}
  12124. \section{Expose Allocation}
  12125. \label{sec:expose-allocation-r5}
  12126. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  12127. that allocates and initializes a vector, similar to the translation of
  12128. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  12129. The only difference is replacing the use of
  12130. \ALLOC{\itm{len}}{\itm{type}} with
  12131. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  12132. \section{Explicate Control and \LangCLam{}}
  12133. \label{sec:explicate-r5}
  12134. The output language of \code{explicate\_control} is \LangCLam{} whose
  12135. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  12136. difference with respect to \LangCFun{} is the addition of the
  12137. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  12138. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  12139. similar to the handling of other expressions such as primitive
  12140. operators.
  12141. \begin{figure}[tp]
  12142. \fbox{
  12143. \begin{minipage}{0.96\textwidth}
  12144. \small
  12145. \[
  12146. \begin{array}{lcl}
  12147. \Exp &::= & \ldots
  12148. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  12149. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12150. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12151. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12152. \MID \GOTO{\itm{label}} } \\
  12153. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12154. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  12155. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  12156. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  12157. \end{array}
  12158. \]
  12159. \end{minipage}
  12160. }
  12161. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  12162. \label{fig:c4-syntax}
  12163. \end{figure}
  12164. \section{Select Instructions}
  12165. \label{sec:select-instructions-Rlambda}
  12166. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  12167. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  12168. (Section~\ref{sec:select-instructions-gc}). The only difference is
  12169. that you should place the \itm{arity} in the tag that is stored at
  12170. position $0$ of the vector. Recall that in
  12171. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  12172. was not used. We store the arity in the $5$ bits starting at position
  12173. $58$.
  12174. Compile the \code{procedure-arity} operator into a sequence of
  12175. instructions that access the tag from position $0$ of the vector and
  12176. extract the $5$-bits starting at position $58$ from the tag.
  12177. \begin{figure}[p]
  12178. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12179. \node (Rfun) at (0,2) {\large \LangFun{}};
  12180. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  12181. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  12182. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  12183. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  12184. \node (F1-3) at (6,0) {\large $F_1$};
  12185. \node (F1-4) at (3,0) {\large $F_1$};
  12186. \node (F1-5) at (0,0) {\large $F_1$};
  12187. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  12188. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12189. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12190. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12191. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12192. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12193. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12194. \path[->,bend left=15] (Rfun) edge [above] node
  12195. {\ttfamily\footnotesize shrink} (Rfun-2);
  12196. \path[->,bend left=15] (Rfun-2) edge [above] node
  12197. {\ttfamily\footnotesize uniquify} (Rfun-3);
  12198. \path[->,bend left=15] (Rfun-3) edge [right] node
  12199. {\ttfamily\footnotesize reveal-functions} (F1-1);
  12200. \path[->,bend left=15] (F1-1) edge [below] node
  12201. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12202. \path[->,bend right=15] (F1-2) edge [above] node
  12203. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12204. \path[->,bend right=15] (F1-3) edge [above] node
  12205. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12206. \path[->,bend right=15] (F1-4) edge [above] node
  12207. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12208. \path[->,bend right=15] (F1-5) edge [right] node
  12209. {\ttfamily\footnotesize explicate-control} (C3-2);
  12210. \path[->,bend left=15] (C3-2) edge [left] node
  12211. {\ttfamily\footnotesize select-instr.} (x86-2);
  12212. \path[->,bend right=15] (x86-2) edge [left] node
  12213. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12214. \path[->,bend right=15] (x86-2-1) edge [below] node
  12215. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12216. \path[->,bend right=15] (x86-2-2) edge [left] node
  12217. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12218. \path[->,bend left=15] (x86-3) edge [above] node
  12219. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12220. \path[->,bend left=15] (x86-4) edge [right] node
  12221. {\ttfamily\footnotesize print-x86} (x86-5);
  12222. \end{tikzpicture}
  12223. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  12224. functions.}
  12225. \label{fig:Rlambda-passes}
  12226. \end{figure}
  12227. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  12228. for the compilation of \LangLam{}.
  12229. \clearpage
  12230. \section{Challenge: Optimize Closures}
  12231. \label{sec:optimize-closures}
  12232. In this chapter we compiled lexically-scoped functions into a
  12233. relatively efficient representation: flat closures. However, even this
  12234. representation comes with some overhead. For example, consider the
  12235. following program with a function \code{tail-sum} that does not have
  12236. any free variables and where all the uses of \code{tail-sum} are in
  12237. applications where we know that only \code{tail-sum} is being applied
  12238. (and not any other functions).
  12239. \begin{center}
  12240. \begin{minipage}{0.95\textwidth}
  12241. \begin{lstlisting}
  12242. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  12243. (if (eq? n 0)
  12244. r
  12245. (tail-sum (- n 1) (+ n r))))
  12246. (+ (tail-sum 5 0) 27)
  12247. \end{lstlisting}
  12248. \end{minipage}
  12249. \end{center}
  12250. As described in this chapter, we uniformly apply closure conversion to
  12251. all functions, obtaining the following output for this program.
  12252. \begin{center}
  12253. \begin{minipage}{0.95\textwidth}
  12254. \begin{lstlisting}
  12255. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  12256. (if (eq? n2 0)
  12257. r3
  12258. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  12259. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  12260. (define (main) : Integer
  12261. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  12262. ((vector-ref clos6 0) clos6 5 0)) 27))
  12263. \end{lstlisting}
  12264. \end{minipage}
  12265. \end{center}
  12266. In the previous Chapter, there would be no allocation in the program
  12267. and the calls to \code{tail-sum} would be direct calls. In contrast,
  12268. the above program allocates memory for each \code{closure} and the
  12269. calls to \code{tail-sum} are indirect. These two differences incur
  12270. considerable overhead in a program such as this one, where the
  12271. allocations and indirect calls occur inside a tight loop.
  12272. One might think that this problem is trivial to solve: can't we just
  12273. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  12274. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  12275. e'_n$)} instead of treating it like a call to a closure? We would
  12276. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  12277. %
  12278. However, this problem is not so trivial because a global function may
  12279. ``escape'' and become involved in applications that also involve
  12280. closures. Consider the following example in which the application
  12281. \code{(f 41)} needs to be compiled into a closure application, because
  12282. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  12283. function might also get bound to \code{f}.
  12284. \begin{lstlisting}
  12285. (define (add1 [x : Integer]) : Integer
  12286. (+ x 1))
  12287. (let ([y (read)])
  12288. (let ([f (if (eq? (read) 0)
  12289. add1
  12290. (lambda: ([x : Integer]) : Integer (- x y)))])
  12291. (f 41)))
  12292. \end{lstlisting}
  12293. If a global function name is used in any way other than as the
  12294. operator in a direct call, then we say that the function
  12295. \emph{escapes}. If a global function does not escape, then we do not
  12296. need to perform closure conversion on the function.
  12297. \begin{exercise}\normalfont
  12298. Implement an auxiliary function for detecting which global
  12299. functions escape. Using that function, implement an improved version
  12300. of closure conversion that does not apply closure conversion to
  12301. global functions that do not escape but instead compiles them as
  12302. regular functions. Create several new test cases that check whether
  12303. you properly detect whether global functions escape or not.
  12304. \end{exercise}
  12305. So far we have reduced the overhead of calling global functions, but
  12306. it would also be nice to reduce the overhead of calling a
  12307. \code{lambda} when we can determine at compile time which
  12308. \code{lambda} will be called. We refer to such calls as \emph{known
  12309. calls}. Consider the following example in which a \code{lambda} is
  12310. bound to \code{f} and then applied.
  12311. \begin{lstlisting}
  12312. (let ([y (read)])
  12313. (let ([f (lambda: ([x : Integer]) : Integer
  12314. (+ x y))])
  12315. (f 21)))
  12316. \end{lstlisting}
  12317. Closure conversion compiles \code{(f 21)} into an indirect call:
  12318. \begin{lstlisting}
  12319. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  12320. (let ([y2 (vector-ref fvs6 1)])
  12321. (+ x3 y2)))
  12322. (define (main) : Integer
  12323. (let ([y2 (read)])
  12324. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  12325. ((vector-ref f4 0) f4 21))))
  12326. \end{lstlisting}
  12327. but we can instead compile the application \code{(f 21)} into a direct call
  12328. to \code{lambda5}:
  12329. \begin{lstlisting}
  12330. (define (main) : Integer
  12331. (let ([y2 (read)])
  12332. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  12333. ((fun-ref lambda5) f4 21))))
  12334. \end{lstlisting}
  12335. The problem of determining which lambda will be called from a
  12336. particular application is quite challenging in general and the topic
  12337. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  12338. following exercise we recommend that you compile an application to a
  12339. direct call when the operator is a variable and the variable is
  12340. \code{let}-bound to a closure. This can be accomplished by maintaining
  12341. an environment mapping \code{let}-bound variables to function names.
  12342. Extend the environment whenever you encounter a closure on the
  12343. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  12344. to the name of the global function for the closure. This pass should
  12345. come after closure conversion.
  12346. \begin{exercise}\normalfont
  12347. Implement a compiler pass, named \code{optimize-known-calls}, that
  12348. compiles known calls into direct calls. Verify that your compiler is
  12349. successful in this regard on several example programs.
  12350. \end{exercise}
  12351. These exercises only scratches the surface of optimizing of
  12352. closures. A good next step for the interested reader is to look at the
  12353. work of \citet{Keep:2012ab}.
  12354. \section{Further Reading}
  12355. The notion of lexically scoped anonymous functions predates modern
  12356. computers by about a decade. They were invented by
  12357. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  12358. foundation for logic. Anonymous functions were included in the
  12359. LISP~\citep{McCarthy:1960dz} programming language but were initially
  12360. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  12361. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  12362. compile Scheme programs. However, environments were represented as
  12363. linked lists, so variable lookup was linear in the size of the
  12364. environment. In this chapter we represent environments using flat
  12365. closures, which were invented by
  12366. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  12367. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  12368. closures, variable lookup is constant time but the time to create a
  12369. closure is proportional to the number of its free variables. Flat
  12370. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  12371. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  12372. \fi
  12373. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12374. \chapter{Dynamic Typing}
  12375. \label{ch:Rdyn}
  12376. \index{subject}{dynamic typing}
  12377. \if\edition\racketEd
  12378. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  12379. typed language that is a subset of Racket. This is in contrast to the
  12380. previous chapters, which have studied the compilation of Typed
  12381. Racket. In dynamically typed languages such as \LangDyn{}, a given
  12382. expression may produce a value of a different type each time it is
  12383. executed. Consider the following example with a conditional \code{if}
  12384. expression that may return a Boolean or an integer depending on the
  12385. input to the program.
  12386. % part of dynamic_test_25.rkt
  12387. \begin{lstlisting}
  12388. (not (if (eq? (read) 1) #f 0))
  12389. \end{lstlisting}
  12390. Languages that allow expressions to produce different kinds of values
  12391. are called \emph{polymorphic}, a word composed of the Greek roots
  12392. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  12393. are several kinds of polymorphism in programming languages, such as
  12394. subtype polymorphism and parametric
  12395. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  12396. study in this chapter does not have a special name but it is the kind
  12397. that arises in dynamically typed languages.
  12398. Another characteristic of dynamically typed languages is that
  12399. primitive operations, such as \code{not}, are often defined to operate
  12400. on many different types of values. In fact, in Racket, the \code{not}
  12401. operator produces a result for any kind of value: given \code{\#f} it
  12402. returns \code{\#t} and given anything else it returns \code{\#f}.
  12403. Furthermore, even when primitive operations restrict their inputs to
  12404. values of a certain type, this restriction is enforced at runtime
  12405. instead of during compilation. For example, the following vector
  12406. reference results in a run-time contract violation because the index
  12407. must be in integer, not a Boolean such as \code{\#t}.
  12408. \begin{lstlisting}
  12409. (vector-ref (vector 42) #t)
  12410. \end{lstlisting}
  12411. \begin{figure}[tp]
  12412. \centering
  12413. \fbox{
  12414. \begin{minipage}{0.97\textwidth}
  12415. \[
  12416. \begin{array}{rcl}
  12417. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  12418. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12419. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  12420. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  12421. &\MID& \key{\#t} \MID \key{\#f}
  12422. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  12423. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  12424. \MID \CUNIOP{\key{not}}{\Exp} \\
  12425. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  12426. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  12427. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  12428. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  12429. &\MID& \LP\Exp \; \Exp\ldots\RP
  12430. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  12431. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  12432. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  12433. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  12434. \LangDynM{} &::=& \Def\ldots\; \Exp
  12435. \end{array}
  12436. \]
  12437. \end{minipage}
  12438. }
  12439. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  12440. \label{fig:r7-concrete-syntax}
  12441. \end{figure}
  12442. \begin{figure}[tp]
  12443. \centering
  12444. \fbox{
  12445. \begin{minipage}{0.96\textwidth}
  12446. \small
  12447. \[
  12448. \begin{array}{lcl}
  12449. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  12450. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  12451. &\MID& \BOOL{\itm{bool}}
  12452. \MID \IF{\Exp}{\Exp}{\Exp} \\
  12453. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  12454. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  12455. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  12456. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  12457. \end{array}
  12458. \]
  12459. \end{minipage}
  12460. }
  12461. \caption{The abstract syntax of \LangDyn{}.}
  12462. \label{fig:r7-syntax}
  12463. \end{figure}
  12464. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  12465. defined in Figures~\ref{fig:r7-concrete-syntax} and
  12466. \ref{fig:r7-syntax}.
  12467. %
  12468. There is no type checker for \LangDyn{} because it is not a statically
  12469. typed language (it's dynamically typed!).
  12470. The definitional interpreter for \LangDyn{} is presented in
  12471. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  12472. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  12473. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  12474. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  12475. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  12476. value} that combines an underlying value with a tag that identifies
  12477. what kind of value it is. We define the following struct
  12478. to represented tagged values.
  12479. \begin{lstlisting}
  12480. (struct Tagged (value tag) #:transparent)
  12481. \end{lstlisting}
  12482. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  12483. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  12484. but don't always capture all the information that a type does. For
  12485. example, a vector of type \code{(Vector Any Any)} is tagged with
  12486. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  12487. is tagged with \code{Procedure}.
  12488. Next consider the match case for \code{vector-ref}. The
  12489. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  12490. is used to ensure that the first argument is a vector and the second
  12491. is an integer. If they are not, a \code{trapped-error} is raised.
  12492. Recall from Section~\ref{sec:interp_Rint} that when a definition
  12493. interpreter raises a \code{trapped-error} error, the compiled code
  12494. must also signal an error by exiting with return code \code{255}. A
  12495. \code{trapped-error} is also raised if the index is not less than
  12496. length of the vector.
  12497. \begin{figure}[tbp]
  12498. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12499. (define ((interp-Rdyn-exp env) ast)
  12500. (define recur (interp-Rdyn-exp env))
  12501. (match ast
  12502. [(Var x) (lookup x env)]
  12503. [(Int n) (Tagged n 'Integer)]
  12504. [(Bool b) (Tagged b 'Boolean)]
  12505. [(Lambda xs rt body)
  12506. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  12507. [(Prim 'vector es)
  12508. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  12509. [(Prim 'vector-ref (list e1 e2))
  12510. (define vec (recur e1)) (define i (recur e2))
  12511. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  12512. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  12513. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  12514. (vector-ref (Tagged-value vec) (Tagged-value i))]
  12515. [(Prim 'vector-set! (list e1 e2 e3))
  12516. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  12517. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  12518. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  12519. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  12520. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  12521. (Tagged (void) 'Void)]
  12522. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  12523. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  12524. [(Prim 'or (list e1 e2))
  12525. (define v1 (recur e1))
  12526. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  12527. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  12528. [(Prim op (list e1))
  12529. #:when (set-member? type-predicates op)
  12530. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  12531. [(Prim op es)
  12532. (define args (map recur es))
  12533. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  12534. (unless (for/or ([expected-tags (op-tags op)])
  12535. (equal? expected-tags tags))
  12536. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  12537. (tag-value
  12538. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  12539. [(If q t f)
  12540. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  12541. [(Apply f es)
  12542. (define new-f (recur f)) (define args (map recur es))
  12543. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  12544. (match f-val
  12545. [`(function ,xs ,body ,lam-env)
  12546. (unless (eq? (length xs) (length args))
  12547. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  12548. (define new-env (append (map cons xs args) lam-env))
  12549. ((interp-Rdyn-exp new-env) body)]
  12550. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  12551. \end{lstlisting}
  12552. \caption{Interpreter for the \LangDyn{} language.}
  12553. \label{fig:interp-Rdyn}
  12554. \end{figure}
  12555. \begin{figure}[tbp]
  12556. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12557. (define (interp-op op)
  12558. (match op
  12559. ['+ fx+]
  12560. ['- fx-]
  12561. ['read read-fixnum]
  12562. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  12563. ['< (lambda (v1 v2)
  12564. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  12565. ['<= (lambda (v1 v2)
  12566. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  12567. ['> (lambda (v1 v2)
  12568. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  12569. ['>= (lambda (v1 v2)
  12570. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  12571. ['boolean? boolean?]
  12572. ['integer? fixnum?]
  12573. ['void? void?]
  12574. ['vector? vector?]
  12575. ['vector-length vector-length]
  12576. ['procedure? (match-lambda
  12577. [`(functions ,xs ,body ,env) #t] [else #f])]
  12578. [else (error 'interp-op "unknown operator" op)]))
  12579. (define (op-tags op)
  12580. (match op
  12581. ['+ '((Integer Integer))]
  12582. ['- '((Integer Integer) (Integer))]
  12583. ['read '(())]
  12584. ['not '((Boolean))]
  12585. ['< '((Integer Integer))]
  12586. ['<= '((Integer Integer))]
  12587. ['> '((Integer Integer))]
  12588. ['>= '((Integer Integer))]
  12589. ['vector-length '((Vector))]))
  12590. (define type-predicates
  12591. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  12592. (define (tag-value v)
  12593. (cond [(boolean? v) (Tagged v 'Boolean)]
  12594. [(fixnum? v) (Tagged v 'Integer)]
  12595. [(procedure? v) (Tagged v 'Procedure)]
  12596. [(vector? v) (Tagged v 'Vector)]
  12597. [(void? v) (Tagged v 'Void)]
  12598. [else (error 'tag-value "unidentified value ~a" v)]))
  12599. (define (check-tag val expected ast)
  12600. (define tag (Tagged-tag val))
  12601. (unless (eq? tag expected)
  12602. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  12603. \end{lstlisting}
  12604. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  12605. \label{fig:interp-Rdyn-aux}
  12606. \end{figure}
  12607. \clearpage
  12608. \section{Representation of Tagged Values}
  12609. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  12610. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  12611. values at the bit level. Because almost every operation in \LangDyn{}
  12612. involves manipulating tagged values, the representation must be
  12613. efficient. Recall that all of our values are 64 bits. We shall steal
  12614. the 3 right-most bits to encode the tag. We use $001$ to identify
  12615. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  12616. and $101$ for the void value. We define the following auxiliary
  12617. function for mapping types to tag codes.
  12618. \begin{align*}
  12619. \itm{tagof}(\key{Integer}) &= 001 \\
  12620. \itm{tagof}(\key{Boolean}) &= 100 \\
  12621. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  12622. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  12623. \itm{tagof}(\key{Void}) &= 101
  12624. \end{align*}
  12625. This stealing of 3 bits comes at some price: our integers are reduced
  12626. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  12627. affect vectors and procedures because those values are addresses, and
  12628. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  12629. they are always $000$. Thus, we do not lose information by overwriting
  12630. the rightmost 3 bits with the tag and we can simply zero-out the tag
  12631. to recover the original address.
  12632. To make tagged values into first-class entities, we can give them a
  12633. type, called \code{Any}, and define operations such as \code{Inject}
  12634. and \code{Project} for creating and using them, yielding the \LangAny{}
  12635. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  12636. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  12637. in greater detail.
  12638. \section{The \LangAny{} Language}
  12639. \label{sec:Rany-lang}
  12640. \begin{figure}[tp]
  12641. \centering
  12642. \fbox{
  12643. \begin{minipage}{0.96\textwidth}
  12644. \small
  12645. \[
  12646. \begin{array}{lcl}
  12647. \Type &::= & \ldots \MID \key{Any} \\
  12648. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  12649. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  12650. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  12651. \MID \code{procedure?} \MID \code{void?} \\
  12652. \Exp &::=& \ldots
  12653. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  12654. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  12655. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  12656. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12657. \end{array}
  12658. \]
  12659. \end{minipage}
  12660. }
  12661. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  12662. \label{fig:Rany-syntax}
  12663. \end{figure}
  12664. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  12665. (The concrete syntax of \LangAny{} is in the Appendix,
  12666. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  12667. converts the value produced by expression $e$ of type $T$ into a
  12668. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  12669. produced by expression $e$ into a value of type $T$ or else halts the
  12670. program if the type tag is not equivalent to $T$.
  12671. %
  12672. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  12673. restricted to a flat type $\FType$, which simplifies the
  12674. implementation and corresponds with what is needed for compiling \LangDyn{}.
  12675. The \code{any-vector} operators adapt the vector operations so that
  12676. they can be applied to a value of type \code{Any}. They also
  12677. generalize the vector operations in that the index is not restricted
  12678. to be a literal integer in the grammar but is allowed to be any
  12679. expression.
  12680. The type predicates such as \key{boolean?} expect their argument to
  12681. produce a tagged value; they return \key{\#t} if the tag corresponds
  12682. to the predicate and they return \key{\#f} otherwise.
  12683. The type checker for \LangAny{} is shown in
  12684. Figures~\ref{fig:type-check-Rany-part-1} and
  12685. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  12686. Figure~\ref{fig:type-check-Rany-aux}.
  12687. %
  12688. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  12689. auxiliary functions \code{apply-inject} and \code{apply-project} are
  12690. in Figure~\ref{fig:apply-project}.
  12691. \begin{figure}[btp]
  12692. \begin{lstlisting}[basicstyle=\ttfamily\small]
  12693. (define type-check-Rany_class
  12694. (class type-check-Rlambda_class
  12695. (super-new)
  12696. (inherit check-type-equal?)
  12697. (define/override (type-check-exp env)
  12698. (lambda (e)
  12699. (define recur (type-check-exp env))
  12700. (match e
  12701. [(Inject e1 ty)
  12702. (unless (flat-ty? ty)
  12703. (error 'type-check "may only inject from flat type, not ~a" ty))
  12704. (define-values (new-e1 e-ty) (recur e1))
  12705. (check-type-equal? e-ty ty e)
  12706. (values (Inject new-e1 ty) 'Any)]
  12707. [(Project e1 ty)
  12708. (unless (flat-ty? ty)
  12709. (error 'type-check "may only project to flat type, not ~a" ty))
  12710. (define-values (new-e1 e-ty) (recur e1))
  12711. (check-type-equal? e-ty 'Any e)
  12712. (values (Project new-e1 ty) ty)]
  12713. [(Prim 'any-vector-length (list e1))
  12714. (define-values (e1^ t1) (recur e1))
  12715. (check-type-equal? t1 'Any e)
  12716. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  12717. [(Prim 'any-vector-ref (list e1 e2))
  12718. (define-values (e1^ t1) (recur e1))
  12719. (define-values (e2^ t2) (recur e2))
  12720. (check-type-equal? t1 'Any e)
  12721. (check-type-equal? t2 'Integer e)
  12722. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  12723. [(Prim 'any-vector-set! (list e1 e2 e3))
  12724. (define-values (e1^ t1) (recur e1))
  12725. (define-values (e2^ t2) (recur e2))
  12726. (define-values (e3^ t3) (recur e3))
  12727. (check-type-equal? t1 'Any e)
  12728. (check-type-equal? t2 'Integer e)
  12729. (check-type-equal? t3 'Any e)
  12730. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  12731. \end{lstlisting}
  12732. \caption{Type checker for the \LangAny{} language, part 1.}
  12733. \label{fig:type-check-Rany-part-1}
  12734. \end{figure}
  12735. \begin{figure}[btp]
  12736. \begin{lstlisting}[basicstyle=\ttfamily\small]
  12737. [(ValueOf e ty)
  12738. (define-values (new-e e-ty) (recur e))
  12739. (values (ValueOf new-e ty) ty)]
  12740. [(Prim pred (list e1))
  12741. #:when (set-member? (type-predicates) pred)
  12742. (define-values (new-e1 e-ty) (recur e1))
  12743. (check-type-equal? e-ty 'Any e)
  12744. (values (Prim pred (list new-e1)) 'Boolean)]
  12745. [(If cnd thn els)
  12746. (define-values (cnd^ Tc) (recur cnd))
  12747. (define-values (thn^ Tt) (recur thn))
  12748. (define-values (els^ Te) (recur els))
  12749. (check-type-equal? Tc 'Boolean cnd)
  12750. (check-type-equal? Tt Te e)
  12751. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  12752. [(Exit) (values (Exit) '_)]
  12753. [(Prim 'eq? (list arg1 arg2))
  12754. (define-values (e1 t1) (recur arg1))
  12755. (define-values (e2 t2) (recur arg2))
  12756. (match* (t1 t2)
  12757. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  12758. [(other wise) (check-type-equal? t1 t2 e)])
  12759. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  12760. [else ((super type-check-exp env) e)])))
  12761. ))
  12762. \end{lstlisting}
  12763. \caption{Type checker for the \LangAny{} language, part 2.}
  12764. \label{fig:type-check-Rany-part-2}
  12765. \end{figure}
  12766. \begin{figure}[tbp]
  12767. \begin{lstlisting}
  12768. (define/override (operator-types)
  12769. (append
  12770. '((integer? . ((Any) . Boolean))
  12771. (vector? . ((Any) . Boolean))
  12772. (procedure? . ((Any) . Boolean))
  12773. (void? . ((Any) . Boolean))
  12774. (tag-of-any . ((Any) . Integer))
  12775. (make-any . ((_ Integer) . Any))
  12776. )
  12777. (super operator-types)))
  12778. (define/public (type-predicates)
  12779. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  12780. (define/public (combine-types t1 t2)
  12781. (match (list t1 t2)
  12782. [(list '_ t2) t2]
  12783. [(list t1 '_) t1]
  12784. [(list `(Vector ,ts1 ...)
  12785. `(Vector ,ts2 ...))
  12786. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  12787. (combine-types t1 t2)))]
  12788. [(list `(,ts1 ... -> ,rt1)
  12789. `(,ts2 ... -> ,rt2))
  12790. `(,@(for/list ([t1 ts1] [t2 ts2])
  12791. (combine-types t1 t2))
  12792. -> ,(combine-types rt1 rt2))]
  12793. [else t1]))
  12794. (define/public (flat-ty? ty)
  12795. (match ty
  12796. [(or `Integer `Boolean '_ `Void) #t]
  12797. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  12798. [`(,ts ... -> ,rt)
  12799. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  12800. [else #f]))
  12801. \end{lstlisting}
  12802. \caption{Auxiliary methods for type checking \LangAny{}.}
  12803. \label{fig:type-check-Rany-aux}
  12804. \end{figure}
  12805. \begin{figure}[btp]
  12806. \begin{lstlisting}
  12807. (define interp-Rany_class
  12808. (class interp-Rlambda_class
  12809. (super-new)
  12810. (define/override (interp-op op)
  12811. (match op
  12812. ['boolean? (match-lambda
  12813. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  12814. [else #f])]
  12815. ['integer? (match-lambda
  12816. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  12817. [else #f])]
  12818. ['vector? (match-lambda
  12819. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  12820. [else #f])]
  12821. ['procedure? (match-lambda
  12822. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  12823. [else #f])]
  12824. ['eq? (match-lambda*
  12825. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  12826. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  12827. [ls (apply (super interp-op op) ls)])]
  12828. ['any-vector-ref (lambda (v i)
  12829. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  12830. ['any-vector-set! (lambda (v i a)
  12831. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  12832. ['any-vector-length (lambda (v)
  12833. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  12834. [else (super interp-op op)]))
  12835. (define/override ((interp-exp env) e)
  12836. (define recur (interp-exp env))
  12837. (match e
  12838. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  12839. [(Project e ty2) (apply-project (recur e) ty2)]
  12840. [else ((super interp-exp env) e)]))
  12841. ))
  12842. (define (interp-Rany p)
  12843. (send (new interp-Rany_class) interp-program p))
  12844. \end{lstlisting}
  12845. \caption{Interpreter for \LangAny{}.}
  12846. \label{fig:interp-Rany}
  12847. \end{figure}
  12848. \begin{figure}[tbp]
  12849. \begin{lstlisting}
  12850. (define/public (apply-inject v tg) (Tagged v tg))
  12851. (define/public (apply-project v ty2)
  12852. (define tag2 (any-tag ty2))
  12853. (match v
  12854. [(Tagged v1 tag1)
  12855. (cond
  12856. [(eq? tag1 tag2)
  12857. (match ty2
  12858. [`(Vector ,ts ...)
  12859. (define l1 ((interp-op 'vector-length) v1))
  12860. (cond
  12861. [(eq? l1 (length ts)) v1]
  12862. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  12863. l1 (length ts))])]
  12864. [`(,ts ... -> ,rt)
  12865. (match v1
  12866. [`(function ,xs ,body ,env)
  12867. (cond [(eq? (length xs) (length ts)) v1]
  12868. [else
  12869. (error 'apply-project "arity mismatch ~a != ~a"
  12870. (length xs) (length ts))])]
  12871. [else (error 'apply-project "expected function not ~a" v1)])]
  12872. [else v1])]
  12873. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  12874. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  12875. \end{lstlisting}
  12876. \caption{Auxiliary functions for injection and projection.}
  12877. \label{fig:apply-project}
  12878. \end{figure}
  12879. \clearpage
  12880. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  12881. \label{sec:compile-r7}
  12882. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  12883. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  12884. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  12885. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  12886. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  12887. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  12888. the Boolean \code{\#t}, which must be injected to produce an
  12889. expression of type \key{Any}.
  12890. %
  12891. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  12892. addition, is representative of compilation for many primitive
  12893. operations: the arguments have type \key{Any} and must be projected to
  12894. \key{Integer} before the addition can be performed.
  12895. The compilation of \key{lambda} (third row of
  12896. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  12897. produce type annotations: we simply use \key{Any}.
  12898. %
  12899. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  12900. has to account for some differences in behavior between \LangDyn{} and
  12901. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  12902. kind of values can be used in various places. For example, the
  12903. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  12904. the arguments need not be of the same type (in that case the
  12905. result is \code{\#f}).
  12906. \begin{figure}[btp]
  12907. \centering
  12908. \begin{tabular}{|lll|} \hline
  12909. \begin{minipage}{0.27\textwidth}
  12910. \begin{lstlisting}
  12911. #t
  12912. \end{lstlisting}
  12913. \end{minipage}
  12914. &
  12915. $\Rightarrow$
  12916. &
  12917. \begin{minipage}{0.65\textwidth}
  12918. \begin{lstlisting}
  12919. (inject #t Boolean)
  12920. \end{lstlisting}
  12921. \end{minipage}
  12922. \\[2ex]\hline
  12923. \begin{minipage}{0.27\textwidth}
  12924. \begin{lstlisting}
  12925. (+ |$e_1$| |$e_2$|)
  12926. \end{lstlisting}
  12927. \end{minipage}
  12928. &
  12929. $\Rightarrow$
  12930. &
  12931. \begin{minipage}{0.65\textwidth}
  12932. \begin{lstlisting}
  12933. (inject
  12934. (+ (project |$e'_1$| Integer)
  12935. (project |$e'_2$| Integer))
  12936. Integer)
  12937. \end{lstlisting}
  12938. \end{minipage}
  12939. \\[2ex]\hline
  12940. \begin{minipage}{0.27\textwidth}
  12941. \begin{lstlisting}
  12942. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  12943. \end{lstlisting}
  12944. \end{minipage}
  12945. &
  12946. $\Rightarrow$
  12947. &
  12948. \begin{minipage}{0.65\textwidth}
  12949. \begin{lstlisting}
  12950. (inject
  12951. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  12952. (Any|$\ldots$|Any -> Any))
  12953. \end{lstlisting}
  12954. \end{minipage}
  12955. \\[2ex]\hline
  12956. \begin{minipage}{0.27\textwidth}
  12957. \begin{lstlisting}
  12958. (|$e_0$| |$e_1 \ldots e_n$|)
  12959. \end{lstlisting}
  12960. \end{minipage}
  12961. &
  12962. $\Rightarrow$
  12963. &
  12964. \begin{minipage}{0.65\textwidth}
  12965. \begin{lstlisting}
  12966. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  12967. \end{lstlisting}
  12968. \end{minipage}
  12969. \\[2ex]\hline
  12970. \begin{minipage}{0.27\textwidth}
  12971. \begin{lstlisting}
  12972. (vector-ref |$e_1$| |$e_2$|)
  12973. \end{lstlisting}
  12974. \end{minipage}
  12975. &
  12976. $\Rightarrow$
  12977. &
  12978. \begin{minipage}{0.65\textwidth}
  12979. \begin{lstlisting}
  12980. (any-vector-ref |$e_1'$| |$e_2'$|)
  12981. \end{lstlisting}
  12982. \end{minipage}
  12983. \\[2ex]\hline
  12984. \begin{minipage}{0.27\textwidth}
  12985. \begin{lstlisting}
  12986. (if |$e_1$| |$e_2$| |$e_3$|)
  12987. \end{lstlisting}
  12988. \end{minipage}
  12989. &
  12990. $\Rightarrow$
  12991. &
  12992. \begin{minipage}{0.65\textwidth}
  12993. \begin{lstlisting}
  12994. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  12995. \end{lstlisting}
  12996. \end{minipage}
  12997. \\[2ex]\hline
  12998. \begin{minipage}{0.27\textwidth}
  12999. \begin{lstlisting}
  13000. (eq? |$e_1$| |$e_2$|)
  13001. \end{lstlisting}
  13002. \end{minipage}
  13003. &
  13004. $\Rightarrow$
  13005. &
  13006. \begin{minipage}{0.65\textwidth}
  13007. \begin{lstlisting}
  13008. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  13009. \end{lstlisting}
  13010. \end{minipage}
  13011. \\[2ex]\hline
  13012. \begin{minipage}{0.27\textwidth}
  13013. \begin{lstlisting}
  13014. (not |$e_1$|)
  13015. \end{lstlisting}
  13016. \end{minipage}
  13017. &
  13018. $\Rightarrow$
  13019. &
  13020. \begin{minipage}{0.65\textwidth}
  13021. \begin{lstlisting}
  13022. (if (eq? |$e'_1$| (inject #f Boolean))
  13023. (inject #t Boolean) (inject #f Boolean))
  13024. \end{lstlisting}
  13025. \end{minipage}
  13026. \\[2ex]\hline
  13027. \end{tabular}
  13028. \caption{Cast Insertion}
  13029. \label{fig:compile-r7-Rany}
  13030. \end{figure}
  13031. \section{Reveal Casts}
  13032. \label{sec:reveal-casts-Rany}
  13033. % TODO: define R'_6
  13034. In the \code{reveal-casts} pass we recommend compiling \code{project}
  13035. into an \code{if} expression that checks whether the value's tag
  13036. matches the target type; if it does, the value is converted to a value
  13037. of the target type by removing the tag; if it does not, the program
  13038. exits. To perform these actions we need a new primitive operation,
  13039. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  13040. The \code{tag-of-any} operation retrieves the type tag from a tagged
  13041. value of type \code{Any}. The \code{ValueOf} form retrieves the
  13042. underlying value from a tagged value. The \code{ValueOf} form
  13043. includes the type for the underlying value which is used by the type
  13044. checker. Finally, the \code{Exit} form ends the execution of the
  13045. program.
  13046. If the target type of the projection is \code{Boolean} or
  13047. \code{Integer}, then \code{Project} can be translated as follows.
  13048. \begin{center}
  13049. \begin{minipage}{1.0\textwidth}
  13050. \begin{lstlisting}
  13051. (Project |$e$| |$\FType$|)
  13052. |$\Rightarrow$|
  13053. (Let |$\itm{tmp}$| |$e'$|
  13054. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  13055. (Int |$\itm{tagof}(\FType)$|)))
  13056. (ValueOf |$\itm{tmp}$| |$\FType$|)
  13057. (Exit)))
  13058. \end{lstlisting}
  13059. \end{minipage}
  13060. \end{center}
  13061. If the target type of the projection is a vector or function type,
  13062. then there is a bit more work to do. For vectors, check that the
  13063. length of the vector type matches the length of the vector (using the
  13064. \code{vector-length} primitive). For functions, check that the number
  13065. of parameters in the function type matches the function's arity (using
  13066. \code{procedure-arity}).
  13067. Regarding \code{inject}, we recommend compiling it to a slightly
  13068. lower-level primitive operation named \code{make-any}. This operation
  13069. takes a tag instead of a type.
  13070. \begin{center}
  13071. \begin{minipage}{1.0\textwidth}
  13072. \begin{lstlisting}
  13073. (Inject |$e$| |$\FType$|)
  13074. |$\Rightarrow$|
  13075. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  13076. \end{lstlisting}
  13077. \end{minipage}
  13078. \end{center}
  13079. The type predicates (\code{boolean?}, etc.) can be translated into
  13080. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  13081. translation of \code{Project}.
  13082. The \code{any-vector-ref} and \code{any-vector-set!} operations
  13083. combine the projection action with the vector operation. Also, the
  13084. read and write operations allow arbitrary expressions for the index so
  13085. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  13086. cannot guarantee that the index is within bounds. Thus, we insert code
  13087. to perform bounds checking at runtime. The translation for
  13088. \code{any-vector-ref} is as follows and the other two operations are
  13089. translated in a similar way.
  13090. \begin{lstlisting}
  13091. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  13092. |$\Rightarrow$|
  13093. (Let |$v$| |$e'_1$|
  13094. (Let |$i$| |$e'_2$|
  13095. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  13096. (If (Prim '< (list (Var |$i$|)
  13097. (Prim 'any-vector-length (list (Var |$v$|)))))
  13098. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  13099. (Exit))))
  13100. \end{lstlisting}
  13101. \section{Remove Complex Operands}
  13102. \label{sec:rco-Rany}
  13103. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  13104. The subexpression of \code{ValueOf} must be atomic.
  13105. \section{Explicate Control and \LangCAny{}}
  13106. \label{sec:explicate-Rany}
  13107. The output of \code{explicate\_control} is the \LangCAny{} language whose
  13108. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  13109. form that we added to \LangAny{} remains an expression and the \code{Exit}
  13110. expression becomes a $\Tail$. Also, note that the index argument of
  13111. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  13112. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  13113. \begin{figure}[tp]
  13114. \fbox{
  13115. \begin{minipage}{0.96\textwidth}
  13116. \small
  13117. \[
  13118. \begin{array}{lcl}
  13119. \Exp &::= & \ldots
  13120. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  13121. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  13122. &\MID& \VALUEOF{\Exp}{\FType} \\
  13123. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  13124. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  13125. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  13126. \MID \GOTO{\itm{label}} } \\
  13127. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  13128. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  13129. \MID \LP\key{Exit}\RP \\
  13130. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  13131. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  13132. \end{array}
  13133. \]
  13134. \end{minipage}
  13135. }
  13136. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  13137. \label{fig:c5-syntax}
  13138. \end{figure}
  13139. \section{Select Instructions}
  13140. \label{sec:select-Rany}
  13141. In the \code{select-instructions} pass we translate the primitive
  13142. operations on the \code{Any} type to x86 instructions that involve
  13143. manipulating the 3 tag bits of the tagged value.
  13144. \paragraph{Make-any}
  13145. We recommend compiling the \key{make-any} primitive as follows if the
  13146. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  13147. shifts the destination to the left by the number of bits specified its
  13148. source argument (in this case $3$, the length of the tag) and it
  13149. preserves the sign of the integer. We use the \key{orq} instruction to
  13150. combine the tag and the value to form the tagged value. \\
  13151. \begin{lstlisting}
  13152. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  13153. |$\Rightarrow$|
  13154. movq |$e'$|, |\itm{lhs'}|
  13155. salq $3, |\itm{lhs'}|
  13156. orq $|$\itm{tag}$|, |\itm{lhs'}|
  13157. \end{lstlisting}
  13158. The instruction selection for vectors and procedures is different
  13159. because their is no need to shift them to the left. The rightmost 3
  13160. bits are already zeros as described at the beginning of this
  13161. chapter. So we just combine the value and the tag using \key{orq}. \\
  13162. \begin{lstlisting}
  13163. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  13164. |$\Rightarrow$|
  13165. movq |$e'$|, |\itm{lhs'}|
  13166. orq $|$\itm{tag}$|, |\itm{lhs'}|
  13167. \end{lstlisting}
  13168. \paragraph{Tag-of-any}
  13169. Recall that the \code{tag-of-any} operation extracts the type tag from
  13170. a value of type \code{Any}. The type tag is the bottom three bits, so
  13171. we obtain the tag by taking the bitwise-and of the value with $111$
  13172. ($7$ in decimal).
  13173. \begin{lstlisting}
  13174. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  13175. |$\Rightarrow$|
  13176. movq |$e'$|, |\itm{lhs'}|
  13177. andq $7, |\itm{lhs'}|
  13178. \end{lstlisting}
  13179. \paragraph{ValueOf}
  13180. Like \key{make-any}, the instructions for \key{ValueOf} are different
  13181. depending on whether the type $T$ is a pointer (vector or procedure)
  13182. or not (Integer or Boolean). The following shows the instruction
  13183. selection for Integer and Boolean. We produce an untagged value by
  13184. shifting it to the right by 3 bits.
  13185. \begin{lstlisting}
  13186. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  13187. |$\Rightarrow$|
  13188. movq |$e'$|, |\itm{lhs'}|
  13189. sarq $3, |\itm{lhs'}|
  13190. \end{lstlisting}
  13191. %
  13192. In the case for vectors and procedures, there is no need to
  13193. shift. Instead we just need to zero-out the rightmost 3 bits. We
  13194. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  13195. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  13196. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  13197. then apply \code{andq} with the tagged value to get the desired
  13198. result. \\
  13199. \begin{lstlisting}
  13200. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  13201. |$\Rightarrow$|
  13202. movq $|$-8$|, |\itm{lhs'}|
  13203. andq |$e'$|, |\itm{lhs'}|
  13204. \end{lstlisting}
  13205. %% \paragraph{Type Predicates} We leave it to the reader to
  13206. %% devise a sequence of instructions to implement the type predicates
  13207. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  13208. \paragraph{Any-vector-length}
  13209. \begin{lstlisting}
  13210. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  13211. |$\Longrightarrow$|
  13212. movq |$\neg 111$|, %r11
  13213. andq |$a_1'$|, %r11
  13214. movq 0(%r11), %r11
  13215. andq $126, %r11
  13216. sarq $1, %r11
  13217. movq %r11, |$\itm{lhs'}$|
  13218. \end{lstlisting}
  13219. \paragraph{Any-vector-ref}
  13220. The index may be an arbitrary atom so instead of computing the offset
  13221. at compile time, instructions need to be generated to compute the
  13222. offset at runtime as follows. Note the use of the new instruction
  13223. \code{imulq}.
  13224. \begin{center}
  13225. \begin{minipage}{0.96\textwidth}
  13226. \begin{lstlisting}
  13227. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  13228. |$\Longrightarrow$|
  13229. movq |$\neg 111$|, %r11
  13230. andq |$a_1'$|, %r11
  13231. movq |$a_2'$|, %rax
  13232. addq $1, %rax
  13233. imulq $8, %rax
  13234. addq %rax, %r11
  13235. movq 0(%r11) |$\itm{lhs'}$|
  13236. \end{lstlisting}
  13237. \end{minipage}
  13238. \end{center}
  13239. \paragraph{Any-vector-set!}
  13240. The code generation for \code{any-vector-set!} is similar to the other
  13241. \code{any-vector} operations.
  13242. \section{Register Allocation for \LangAny{}}
  13243. \label{sec:register-allocation-Rany}
  13244. \index{subject}{register allocation}
  13245. There is an interesting interaction between tagged values and garbage
  13246. collection that has an impact on register allocation. A variable of
  13247. type \code{Any} might refer to a vector and therefore it might be a
  13248. root that needs to be inspected and copied during garbage
  13249. collection. Thus, we need to treat variables of type \code{Any} in a
  13250. similar way to variables of type \code{Vector} for purposes of
  13251. register allocation. In particular,
  13252. \begin{itemize}
  13253. \item If a variable of type \code{Any} is live during a function call,
  13254. then it must be spilled. This can be accomplished by changing
  13255. \code{build-interference} to mark all variables of type \code{Any}
  13256. that are live after a \code{callq} as interfering with all the
  13257. registers.
  13258. \item If a variable of type \code{Any} is spilled, it must be spilled
  13259. to the root stack instead of the normal procedure call stack.
  13260. \end{itemize}
  13261. Another concern regarding the root stack is that the garbage collector
  13262. needs to differentiate between (1) plain old pointers to tuples, (2) a
  13263. tagged value that points to a tuple, and (3) a tagged value that is
  13264. not a tuple. We enable this differentiation by choosing not to use the
  13265. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  13266. reserved for identifying plain old pointers to tuples. That way, if
  13267. one of the first three bits is set, then we have a tagged value and
  13268. inspecting the tag can differentiation between vectors ($010$) and the
  13269. other kinds of values.
  13270. \begin{exercise}\normalfont
  13271. Expand your compiler to handle \LangAny{} as discussed in the last few
  13272. sections. Create 5 new programs that use the \code{Any} type and the
  13273. new operations (\code{inject}, \code{project}, \code{boolean?},
  13274. etc.). Test your compiler on these new programs and all of your
  13275. previously created test programs.
  13276. \end{exercise}
  13277. \begin{exercise}\normalfont
  13278. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  13279. Create tests for \LangDyn{} by adapting ten of your previous test programs
  13280. by removing type annotations. Add 5 more tests programs that
  13281. specifically rely on the language being dynamically typed. That is,
  13282. they should not be legal programs in a statically typed language, but
  13283. nevertheless, they should be valid \LangDyn{} programs that run to
  13284. completion without error.
  13285. \end{exercise}
  13286. \begin{figure}[p]
  13287. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13288. \node (Rfun) at (0,4) {\large \LangDyn{}};
  13289. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  13290. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  13291. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  13292. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  13293. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  13294. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  13295. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  13296. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  13297. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  13298. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  13299. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  13300. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13301. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13302. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13303. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13304. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13305. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13306. \path[->,bend left=15] (Rfun) edge [above] node
  13307. {\ttfamily\footnotesize shrink} (Rfun-2);
  13308. \path[->,bend left=15] (Rfun-2) edge [above] node
  13309. {\ttfamily\footnotesize uniquify} (Rfun-3);
  13310. \path[->,bend left=15] (Rfun-3) edge [above] node
  13311. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  13312. \path[->,bend right=15] (Rfun-4) edge [left] node
  13313. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  13314. \path[->,bend left=15] (Rfun-5) edge [above] node
  13315. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  13316. \path[->,bend left=15] (Rfun-6) edge [left] node
  13317. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  13318. \path[->,bend left=15] (Rfun-7) edge [below] node
  13319. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  13320. \path[->,bend right=15] (F1-2) edge [above] node
  13321. {\ttfamily\footnotesize limit-fun.} (F1-3);
  13322. \path[->,bend right=15] (F1-3) edge [above] node
  13323. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  13324. \path[->,bend right=15] (F1-4) edge [above] node
  13325. {\ttfamily\footnotesize remove-complex.} (F1-5);
  13326. \path[->,bend right=15] (F1-5) edge [right] node
  13327. {\ttfamily\footnotesize explicate-control} (C3-2);
  13328. \path[->,bend left=15] (C3-2) edge [left] node
  13329. {\ttfamily\footnotesize select-instr.} (x86-2);
  13330. \path[->,bend right=15] (x86-2) edge [left] node
  13331. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  13332. \path[->,bend right=15] (x86-2-1) edge [below] node
  13333. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  13334. \path[->,bend right=15] (x86-2-2) edge [left] node
  13335. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  13336. \path[->,bend left=15] (x86-3) edge [above] node
  13337. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13338. \path[->,bend left=15] (x86-4) edge [right] node
  13339. {\ttfamily\footnotesize print-x86} (x86-5);
  13340. \end{tikzpicture}
  13341. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  13342. \label{fig:Rdyn-passes}
  13343. \end{figure}
  13344. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  13345. for the compilation of \LangDyn{}.
  13346. % Further Reading
  13347. \fi % racketEd
  13348. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13349. \chapter{Objects}
  13350. \label{ch:Robject}
  13351. \index{subject}{objects}
  13352. \index{subject}{classes}
  13353. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13354. \chapter{Gradual Typing}
  13355. \label{ch:Rgrad}
  13356. \index{subject}{gradual typing}
  13357. \if\edition\racketEd
  13358. This chapter studies a language, \LangGrad{}, in which the programmer
  13359. can choose between static and dynamic type checking in different parts
  13360. of a program, thereby mixing the statically typed \LangLoop{} language
  13361. with the dynamically typed \LangDyn{}. There are several approaches to
  13362. mixing static and dynamic typing, including multi-language
  13363. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  13364. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  13365. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  13366. programmer controls the amount of static versus dynamic checking by
  13367. adding or removing type annotations on parameters and
  13368. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  13369. %
  13370. The concrete syntax of \LangGrad{} is defined in
  13371. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  13372. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  13373. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  13374. non-terminals that make type annotations optional. The return types
  13375. are not optional in the abstract syntax; the parser fills in
  13376. \code{Any} when the return type is not specified in the concrete
  13377. syntax.
  13378. \begin{figure}[tp]
  13379. \centering
  13380. \fbox{
  13381. \begin{minipage}{0.96\textwidth}
  13382. \small
  13383. \[
  13384. \begin{array}{lcl}
  13385. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  13386. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  13387. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  13388. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  13389. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  13390. &\MID& \gray{\key{\#t} \MID \key{\#f}
  13391. \MID (\key{and}\;\Exp\;\Exp)
  13392. \MID (\key{or}\;\Exp\;\Exp)
  13393. \MID (\key{not}\;\Exp) } \\
  13394. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  13395. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  13396. (\key{vector-ref}\;\Exp\;\Int)} \\
  13397. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  13398. \MID (\Exp \; \Exp\ldots) } \\
  13399. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  13400. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  13401. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  13402. \MID \CBEGIN{\Exp\ldots}{\Exp}
  13403. \MID \CWHILE{\Exp}{\Exp} } \\
  13404. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  13405. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  13406. \end{array}
  13407. \]
  13408. \end{minipage}
  13409. }
  13410. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  13411. \label{fig:Rgrad-concrete-syntax}
  13412. \end{figure}
  13413. \begin{figure}[tp]
  13414. \centering
  13415. \fbox{
  13416. \begin{minipage}{0.96\textwidth}
  13417. \small
  13418. \[
  13419. \begin{array}{lcl}
  13420. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  13421. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  13422. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  13423. &\MID& \gray{ \BOOL{\itm{bool}}
  13424. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  13425. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  13426. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  13427. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  13428. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  13429. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  13430. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  13431. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13432. \end{array}
  13433. \]
  13434. \end{minipage}
  13435. }
  13436. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  13437. \label{fig:Rgrad-syntax}
  13438. \end{figure}
  13439. Both the type checker and the interpreter for \LangGrad{} require some
  13440. interesting changes to enable gradual typing, which we discuss in the
  13441. next two sections in the context of the \code{map-vec} example from
  13442. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  13443. revised the \code{map-vec} example, omitting the type annotations from
  13444. the \code{add1} function.
  13445. \begin{figure}[btp]
  13446. % gradual_test_9.rkt
  13447. \begin{lstlisting}
  13448. (define (map-vec [f : (Integer -> Integer)]
  13449. [v : (Vector Integer Integer)])
  13450. : (Vector Integer Integer)
  13451. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13452. (define (add1 x) (+ x 1))
  13453. (vector-ref (map-vec add1 (vector 0 41)) 1)
  13454. \end{lstlisting}
  13455. \caption{A partially-typed version of the \code{map-vec} example.}
  13456. \label{fig:gradual-map-vec}
  13457. \end{figure}
  13458. \section{Type Checking \LangGrad{} and \LangCast{}}
  13459. \label{sec:gradual-type-check}
  13460. The type checker for \LangGrad{} uses the \code{Any} type for missing
  13461. parameter and return types. For example, the \code{x} parameter of
  13462. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  13463. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  13464. consider the \code{+} operator inside \code{add1}. It expects both
  13465. arguments to have type \code{Integer}, but its first argument \code{x}
  13466. has type \code{Any}. In a gradually typed language, such differences
  13467. are allowed so long as the types are \emph{consistent}, that is, they
  13468. are equal except in places where there is an \code{Any} type. The type
  13469. \code{Any} is consistent with every other type.
  13470. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  13471. \begin{figure}[tbp]
  13472. \begin{lstlisting}
  13473. (define/public (consistent? t1 t2)
  13474. (match* (t1 t2)
  13475. [('Integer 'Integer) #t]
  13476. [('Boolean 'Boolean) #t]
  13477. [('Void 'Void) #t]
  13478. [('Any t2) #t]
  13479. [(t1 'Any) #t]
  13480. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13481. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  13482. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13483. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  13484. (consistent? rt1 rt2))]
  13485. [(other wise) #f]))
  13486. \end{lstlisting}
  13487. \caption{The consistency predicate on types.}
  13488. \label{fig:consistent}
  13489. \end{figure}
  13490. Returning to the \code{map-vec} example of
  13491. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  13492. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  13493. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  13494. because the two types are consistent. In particular, \code{->} is
  13495. equal to \code{->} and because \code{Any} is consistent with
  13496. \code{Integer}.
  13497. Next consider a program with an error, such as applying the
  13498. \code{map-vec} to a function that sometimes returns a Boolean, as
  13499. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  13500. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  13501. consistent with the type of parameter \code{f} of \code{map-vec}, that
  13502. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  13503. Integer)}. One might say that a gradual type checker is optimistic
  13504. in that it accepts programs that might execute without a runtime type
  13505. error.
  13506. %
  13507. Unfortunately, running this program with input \code{1} triggers an
  13508. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  13509. performs checking at runtime to ensure the integrity of the static
  13510. types, such as the \code{(Integer -> Integer)} annotation on parameter
  13511. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  13512. new \code{Cast} form that is inserted by the type checker. Thus, the
  13513. output of the type checker is a program in the \LangCast{} language, which
  13514. adds \code{Cast} to \LangLoop{}, as shown in
  13515. Figure~\ref{fig:Rgrad-prime-syntax}.
  13516. \begin{figure}[tp]
  13517. \centering
  13518. \fbox{
  13519. \begin{minipage}{0.96\textwidth}
  13520. \small
  13521. \[
  13522. \begin{array}{lcl}
  13523. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  13524. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13525. \end{array}
  13526. \]
  13527. \end{minipage}
  13528. }
  13529. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  13530. \label{fig:Rgrad-prime-syntax}
  13531. \end{figure}
  13532. \begin{figure}[tbp]
  13533. \begin{lstlisting}
  13534. (define (map-vec [f : (Integer -> Integer)]
  13535. [v : (Vector Integer Integer)])
  13536. : (Vector Integer Integer)
  13537. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13538. (define (add1 x) (+ x 1))
  13539. (define (true) #t)
  13540. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  13541. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  13542. \end{lstlisting}
  13543. \caption{A variant of the \code{map-vec} example with an error.}
  13544. \label{fig:map-vec-maybe-add1}
  13545. \end{figure}
  13546. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  13547. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  13548. inserted every time the type checker sees two types that are
  13549. consistent but not equal. In the \code{add1} function, \code{x} is
  13550. cast to \code{Integer} and the result of the \code{+} is cast to
  13551. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  13552. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  13553. \begin{figure}[btp]
  13554. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13555. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13556. : (Vector Integer Integer)
  13557. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13558. (define (add1 [x : Any]) : Any
  13559. (cast (+ (cast x Any Integer) 1) Integer Any))
  13560. (define (true) : Any (cast #t Boolean Any))
  13561. (define (maybe-add1 [x : Any]) : Any
  13562. (if (eq? 0 (read)) (add1 x) (true)))
  13563. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  13564. (vector 0 41)) 0)
  13565. \end{lstlisting}
  13566. \caption{Output of type checking \code{map-vec}
  13567. and \code{maybe-add1}.}
  13568. \label{fig:map-vec-cast}
  13569. \end{figure}
  13570. The type checker for \LangGrad{} is defined in
  13571. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  13572. and \ref{fig:type-check-Rgradual-3}.
  13573. \begin{figure}[tbp]
  13574. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13575. (define type-check-gradual_class
  13576. (class type-check-Rwhile_class
  13577. (super-new)
  13578. (inherit operator-types type-predicates)
  13579. (define/override (type-check-exp env)
  13580. (lambda (e)
  13581. (define recur (type-check-exp env))
  13582. (match e
  13583. [(Prim 'vector-length (list e1))
  13584. (define-values (e1^ t) (recur e1))
  13585. (match t
  13586. [`(Vector ,ts ...)
  13587. (values (Prim 'vector-length (list e1^)) 'Integer)]
  13588. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  13589. [(Prim 'vector-ref (list e1 e2))
  13590. (define-values (e1^ t1) (recur e1))
  13591. (define-values (e2^ t2) (recur e2))
  13592. (check-consistent? t2 'Integer e)
  13593. (match t1
  13594. [`(Vector ,ts ...)
  13595. (match e2^
  13596. [(Int i)
  13597. (unless (and (0 . <= . i) (i . < . (length ts)))
  13598. (error 'type-check "invalid index ~a in ~a" i e))
  13599. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  13600. [else (define e1^^ (make-cast e1^ t1 'Any))
  13601. (define e2^^ (make-cast e2^ t2 'Integer))
  13602. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  13603. ['Any
  13604. (define e2^^ (make-cast e2^ t2 'Integer))
  13605. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  13606. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  13607. [(Prim 'vector-set! (list e1 e2 e3) )
  13608. (define-values (e1^ t1) (recur e1))
  13609. (define-values (e2^ t2) (recur e2))
  13610. (define-values (e3^ t3) (recur e3))
  13611. (check-consistent? t2 'Integer e)
  13612. (match t1
  13613. [`(Vector ,ts ...)
  13614. (match e2^
  13615. [(Int i)
  13616. (unless (and (0 . <= . i) (i . < . (length ts)))
  13617. (error 'type-check "invalid index ~a in ~a" i e))
  13618. (check-consistent? (list-ref ts i) t3 e)
  13619. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  13620. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  13621. [else
  13622. (define e1^^ (make-cast e1^ t1 'Any))
  13623. (define e2^^ (make-cast e2^ t2 'Integer))
  13624. (define e3^^ (make-cast e3^ t3 'Any))
  13625. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  13626. ['Any
  13627. (define e2^^ (make-cast e2^ t2 'Integer))
  13628. (define e3^^ (make-cast e3^ t3 'Any))
  13629. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  13630. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  13631. \end{lstlisting}
  13632. \caption{Type checker for the \LangGrad{} language, part 1.}
  13633. \label{fig:type-check-Rgradual-1}
  13634. \end{figure}
  13635. \begin{figure}[tbp]
  13636. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13637. [(Prim 'eq? (list e1 e2))
  13638. (define-values (e1^ t1) (recur e1))
  13639. (define-values (e2^ t2) (recur e2))
  13640. (check-consistent? t1 t2 e)
  13641. (define T (meet t1 t2))
  13642. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  13643. 'Boolean)]
  13644. [(Prim 'not (list e1))
  13645. (define-values (e1^ t1) (recur e1))
  13646. (match t1
  13647. ['Any
  13648. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  13649. (Bool #t) (Bool #f)))]
  13650. [else
  13651. (define-values (t-ret new-es^)
  13652. (type-check-op 'not (list t1) (list e1^) e))
  13653. (values (Prim 'not new-es^) t-ret)])]
  13654. [(Prim 'and (list e1 e2))
  13655. (recur (If e1 e2 (Bool #f)))]
  13656. [(Prim 'or (list e1 e2))
  13657. (define tmp (gensym 'tmp))
  13658. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  13659. [(Prim op es)
  13660. #:when (not (set-member? explicit-prim-ops op))
  13661. (define-values (new-es ts)
  13662. (for/lists (exprs types) ([e es])
  13663. (recur e)))
  13664. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  13665. (values (Prim op new-es^) t-ret)]
  13666. [(If e1 e2 e3)
  13667. (define-values (e1^ T1) (recur e1))
  13668. (define-values (e2^ T2) (recur e2))
  13669. (define-values (e3^ T3) (recur e3))
  13670. (check-consistent? T2 T3 e)
  13671. (match T1
  13672. ['Boolean
  13673. (define Tif (join T2 T3))
  13674. (values (If e1^ (make-cast e2^ T2 Tif)
  13675. (make-cast e3^ T3 Tif)) Tif)]
  13676. ['Any
  13677. (define Tif (meet T2 T3))
  13678. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  13679. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  13680. Tif)]
  13681. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  13682. [(HasType e1 T)
  13683. (define-values (e1^ T1) (recur e1))
  13684. (check-consistent? T1 T)
  13685. (values (make-cast e1^ T1 T) T)]
  13686. [(SetBang x e1)
  13687. (define-values (e1^ T1) (recur e1))
  13688. (define varT (dict-ref env x))
  13689. (check-consistent? T1 varT e)
  13690. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  13691. [(WhileLoop e1 e2)
  13692. (define-values (e1^ T1) (recur e1))
  13693. (check-consistent? T1 'Boolean e)
  13694. (define-values (e2^ T2) ((type-check-exp env) e2))
  13695. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  13696. \end{lstlisting}
  13697. \caption{Type checker for the \LangGrad{} language, part 2.}
  13698. \label{fig:type-check-Rgradual-2}
  13699. \end{figure}
  13700. \begin{figure}[tbp]
  13701. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13702. [(Apply e1 e2s)
  13703. (define-values (e1^ T1) (recur e1))
  13704. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  13705. (match T1
  13706. [`(,T1ps ... -> ,T1rt)
  13707. (for ([T2 T2s] [Tp T1ps])
  13708. (check-consistent? T2 Tp e))
  13709. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  13710. (make-cast e2 src tgt)))
  13711. (values (Apply e1^ e2s^^) T1rt)]
  13712. [`Any
  13713. (define e1^^ (make-cast e1^ 'Any
  13714. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  13715. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  13716. (make-cast e2 src 'Any)))
  13717. (values (Apply e1^^ e2s^^) 'Any)]
  13718. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  13719. [(Lambda params Tr e1)
  13720. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  13721. (match p
  13722. [`[,x : ,T] (values x T)]
  13723. [(? symbol? x) (values x 'Any)])))
  13724. (define-values (e1^ T1)
  13725. ((type-check-exp (append (map cons xs Ts) env)) e1))
  13726. (check-consistent? Tr T1 e)
  13727. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  13728. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  13729. [else ((super type-check-exp env) e)]
  13730. )))
  13731. \end{lstlisting}
  13732. \caption{Type checker for the \LangGrad{} language, part 3.}
  13733. \label{fig:type-check-Rgradual-3}
  13734. \end{figure}
  13735. \begin{figure}[tbp]
  13736. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13737. (define/public (join t1 t2)
  13738. (match* (t1 t2)
  13739. [('Integer 'Integer) 'Integer]
  13740. [('Boolean 'Boolean) 'Boolean]
  13741. [('Void 'Void) 'Void]
  13742. [('Any t2) t2]
  13743. [(t1 'Any) t1]
  13744. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13745. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  13746. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13747. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  13748. -> ,(join rt1 rt2))]))
  13749. (define/public (meet t1 t2)
  13750. (match* (t1 t2)
  13751. [('Integer 'Integer) 'Integer]
  13752. [('Boolean 'Boolean) 'Boolean]
  13753. [('Void 'Void) 'Void]
  13754. [('Any t2) 'Any]
  13755. [(t1 'Any) 'Any]
  13756. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13757. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  13758. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13759. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  13760. -> ,(meet rt1 rt2))]))
  13761. (define/public (make-cast e src tgt)
  13762. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  13763. (define/public (check-consistent? t1 t2 e)
  13764. (unless (consistent? t1 t2)
  13765. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  13766. (define/override (type-check-op op arg-types args e)
  13767. (match (dict-ref (operator-types) op)
  13768. [`(,param-types . ,return-type)
  13769. (for ([at arg-types] [pt param-types])
  13770. (check-consistent? at pt e))
  13771. (values return-type
  13772. (for/list ([e args] [s arg-types] [t param-types])
  13773. (make-cast e s t)))]
  13774. [else (error 'type-check-op "unrecognized ~a" op)]))
  13775. (define explicit-prim-ops
  13776. (set-union
  13777. (type-predicates)
  13778. (set 'procedure-arity 'eq?
  13779. 'vector 'vector-length 'vector-ref 'vector-set!
  13780. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  13781. (define/override (fun-def-type d)
  13782. (match d
  13783. [(Def f params rt info body)
  13784. (define ps
  13785. (for/list ([p params])
  13786. (match p
  13787. [`[,x : ,T] T]
  13788. [(? symbol?) 'Any]
  13789. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  13790. `(,@ps -> ,rt)]
  13791. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  13792. \end{lstlisting}
  13793. \caption{Auxiliary functions for type checking \LangGrad{}.}
  13794. \label{fig:type-check-Rgradual-aux}
  13795. \end{figure}
  13796. \clearpage
  13797. \section{Interpreting \LangCast{}}
  13798. \label{sec:interp-casts}
  13799. The runtime behavior of first-order casts is straightforward, that is,
  13800. casts involving simple types such as \code{Integer} and
  13801. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  13802. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  13803. puts the integer into a tagged value
  13804. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  13805. \code{Integer} is accomplished with the \code{Project} operator, that
  13806. is, by checking the value's tag and either retrieving the underlying
  13807. integer or signaling an error if it the tag is not the one for
  13808. integers (Figure~\ref{fig:apply-project}).
  13809. %
  13810. Things get more interesting for higher-order casts, that is, casts
  13811. involving function or vector types.
  13812. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  13813. Any)} to \code{(Integer -> Integer)}. When a function flows through
  13814. this cast at runtime, we can't know in general whether the function
  13815. will always return an integer.\footnote{Predicting the return value of
  13816. a function is equivalent to the halting problem, which is
  13817. undecidable.} The \LangCast{} interpreter therefore delays the checking
  13818. of the cast until the function is applied. This is accomplished by
  13819. wrapping \code{maybe-add1} in a new function that casts its parameter
  13820. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  13821. casts the return value from \code{Any} to \code{Integer}.
  13822. Turning our attention to casts involving vector types, we consider the
  13823. example in Figure~\ref{fig:map-vec-bang} that defines a
  13824. partially-typed version of \code{map-vec} whose parameter \code{v} has
  13825. type \code{(Vector Any Any)} and that updates \code{v} in place
  13826. instead of returning a new vector. So we name this function
  13827. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  13828. the type checker inserts a cast from \code{(Vector Integer Integer)}
  13829. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  13830. cast between vector types would be a build a new vector whose elements
  13831. are the result of casting each of the original elements to the
  13832. appropriate target type. However, this approach is only valid for
  13833. immutable vectors; and our vectors are mutable. In the example of
  13834. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  13835. the updates inside of \code{map-vec!} would happen to the new vector
  13836. and not the original one.
  13837. \begin{figure}[tbp]
  13838. % gradual_test_11.rkt
  13839. \begin{lstlisting}
  13840. (define (map-vec! [f : (Any -> Any)]
  13841. [v : (Vector Any Any)]) : Void
  13842. (begin
  13843. (vector-set! v 0 (f (vector-ref v 0)))
  13844. (vector-set! v 1 (f (vector-ref v 1)))))
  13845. (define (add1 x) (+ x 1))
  13846. (let ([v (vector 0 41)])
  13847. (begin (map-vec! add1 v) (vector-ref v 1)))
  13848. \end{lstlisting}
  13849. \caption{An example involving casts on vectors.}
  13850. \label{fig:map-vec-bang}
  13851. \end{figure}
  13852. Instead the interpreter needs to create a new kind of value, a
  13853. \emph{vector proxy}, that intercepts every vector operation. On a
  13854. read, the proxy reads from the underlying vector and then applies a
  13855. cast to the resulting value. On a write, the proxy casts the argument
  13856. value and then performs the write to the underlying vector. For the
  13857. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  13858. \code{0} from \code{Integer} to \code{Any}. For the first
  13859. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  13860. to \code{Integer}.
  13861. The final category of cast that we need to consider are casts between
  13862. the \code{Any} type and either a function or a vector
  13863. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  13864. in which parameter \code{v} does not have a type annotation, so it is
  13865. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  13866. type \code{(Vector Integer Integer)} so the type checker inserts a
  13867. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  13868. thought is to use \code{Inject}, but that doesn't work because
  13869. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  13870. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  13871. to \code{Any}.
  13872. \begin{figure}[tbp]
  13873. \begin{lstlisting}
  13874. (define (map-vec! [f : (Any -> Any)] v) : Void
  13875. (begin
  13876. (vector-set! v 0 (f (vector-ref v 0)))
  13877. (vector-set! v 1 (f (vector-ref v 1)))))
  13878. (define (add1 x) (+ x 1))
  13879. (let ([v (vector 0 41)])
  13880. (begin (map-vec! add1 v) (vector-ref v 1)))
  13881. \end{lstlisting}
  13882. \caption{Casting a vector to \code{Any}.}
  13883. \label{fig:map-vec-any}
  13884. \end{figure}
  13885. The \LangCast{} interpreter uses an auxiliary function named
  13886. \code{apply-cast} to cast a value from a source type to a target type,
  13887. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  13888. of the kinds of casts that we've discussed in this section.
  13889. \begin{figure}[tbp]
  13890. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13891. (define/public (apply-cast v s t)
  13892. (match* (s t)
  13893. [(t1 t2) #:when (equal? t1 t2) v]
  13894. [('Any t2)
  13895. (match t2
  13896. [`(,ts ... -> ,rt)
  13897. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  13898. (define v^ (apply-project v any->any))
  13899. (apply-cast v^ any->any `(,@ts -> ,rt))]
  13900. [`(Vector ,ts ...)
  13901. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  13902. (define v^ (apply-project v vec-any))
  13903. (apply-cast v^ vec-any `(Vector ,@ts))]
  13904. [else (apply-project v t2)])]
  13905. [(t1 'Any)
  13906. (match t1
  13907. [`(,ts ... -> ,rt)
  13908. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  13909. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  13910. (apply-inject v^ (any-tag any->any))]
  13911. [`(Vector ,ts ...)
  13912. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  13913. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  13914. (apply-inject v^ (any-tag vec-any))]
  13915. [else (apply-inject v (any-tag t1))])]
  13916. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13917. (define x (gensym 'x))
  13918. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  13919. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  13920. (define cast-writes
  13921. (for/list ([t1 ts1] [t2 ts2])
  13922. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  13923. `(vector-proxy ,(vector v (apply vector cast-reads)
  13924. (apply vector cast-writes)))]
  13925. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13926. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  13927. `(function ,xs ,(Cast
  13928. (Apply (Value v)
  13929. (for/list ([x xs][t1 ts1][t2 ts2])
  13930. (Cast (Var x) t2 t1)))
  13931. rt1 rt2) ())]
  13932. ))
  13933. \end{lstlisting}
  13934. \caption{The \code{apply-cast} auxiliary method.}
  13935. \label{fig:apply-cast}
  13936. \end{figure}
  13937. The interpreter for \LangCast{} is defined in
  13938. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  13939. dispatching to \code{apply-cast}. To handle the addition of vector
  13940. proxies, we update the vector primitives in \code{interp-op} using the
  13941. functions in Figure~\ref{fig:guarded-vector}.
  13942. \begin{figure}[tbp]
  13943. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13944. (define interp-Rcast_class
  13945. (class interp-Rwhile_class
  13946. (super-new)
  13947. (inherit apply-fun apply-inject apply-project)
  13948. (define/override (interp-op op)
  13949. (match op
  13950. ['vector-length guarded-vector-length]
  13951. ['vector-ref guarded-vector-ref]
  13952. ['vector-set! guarded-vector-set!]
  13953. ['any-vector-ref (lambda (v i)
  13954. (match v [`(tagged ,v^ ,tg)
  13955. (guarded-vector-ref v^ i)]))]
  13956. ['any-vector-set! (lambda (v i a)
  13957. (match v [`(tagged ,v^ ,tg)
  13958. (guarded-vector-set! v^ i a)]))]
  13959. ['any-vector-length (lambda (v)
  13960. (match v [`(tagged ,v^ ,tg)
  13961. (guarded-vector-length v^)]))]
  13962. [else (super interp-op op)]
  13963. ))
  13964. (define/override ((interp-exp env) e)
  13965. (define (recur e) ((interp-exp env) e))
  13966. (match e
  13967. [(Value v) v]
  13968. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  13969. [else ((super interp-exp env) e)]))
  13970. ))
  13971. (define (interp-Rcast p)
  13972. (send (new interp-Rcast_class) interp-program p))
  13973. \end{lstlisting}
  13974. \caption{The interpreter for \LangCast{}.}
  13975. \label{fig:interp-Rcast}
  13976. \end{figure}
  13977. \begin{figure}[tbp]
  13978. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13979. (define (guarded-vector-ref vec i)
  13980. (match vec
  13981. [`(vector-proxy ,proxy)
  13982. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  13983. (define rd (vector-ref (vector-ref proxy 1) i))
  13984. (apply-fun rd (list val) 'guarded-vector-ref)]
  13985. [else (vector-ref vec i)]))
  13986. (define (guarded-vector-set! vec i arg)
  13987. (match vec
  13988. [`(vector-proxy ,proxy)
  13989. (define wr (vector-ref (vector-ref proxy 2) i))
  13990. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  13991. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  13992. [else (vector-set! vec i arg)]))
  13993. (define (guarded-vector-length vec)
  13994. (match vec
  13995. [`(vector-proxy ,proxy)
  13996. (guarded-vector-length (vector-ref proxy 0))]
  13997. [else (vector-length vec)]))
  13998. \end{lstlisting}
  13999. \caption{The guarded-vector auxiliary functions.}
  14000. \label{fig:guarded-vector}
  14001. \end{figure}
  14002. \section{Lower Casts}
  14003. \label{sec:lower-casts}
  14004. The next step in the journey towards x86 is the \code{lower-casts}
  14005. pass that translates the casts in \LangCast{} to the lower-level
  14006. \code{Inject} and \code{Project} operators and a new operator for
  14007. creating vector proxies, extending the \LangLoop{} language to create
  14008. \LangProxy{}. We recommend creating an auxiliary function named
  14009. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  14010. and a target type, and translates it to expression in \LangProxy{} that has
  14011. the same behavior as casting the expression from the source to the
  14012. target type in the interpreter.
  14013. The \code{lower-cast} function can follow a code structure similar to
  14014. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  14015. the interpreter for \LangCast{} because it must handle the same cases as
  14016. \code{apply-cast} and it needs to mimic the behavior of
  14017. \code{apply-cast}. The most interesting cases are those concerning the
  14018. casts between two vector types and between two function types.
  14019. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  14020. type to another vector type is accomplished by creating a proxy that
  14021. intercepts the operations on the underlying vector. Here we make the
  14022. creation of the proxy explicit with the \code{vector-proxy} primitive
  14023. operation. It takes three arguments, the first is an expression for
  14024. the vector, the second is a vector of functions for casting an element
  14025. that is being read from the vector, and the third is a vector of
  14026. functions for casting an element that is being written to the vector.
  14027. You can create the functions using \code{Lambda}. Also, as we shall
  14028. see in the next section, we need to differentiate these vectors from
  14029. the user-created ones, so we recommend using a new primitive operator
  14030. named \code{raw-vector} instead of \code{vector} to create these
  14031. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  14032. the output of \code{lower-casts} on the example in
  14033. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  14034. integers to a vector of \code{Any}.
  14035. \begin{figure}[tbp]
  14036. \begin{lstlisting}
  14037. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  14038. (begin
  14039. (vector-set! v 0 (f (vector-ref v 0)))
  14040. (vector-set! v 1 (f (vector-ref v 1)))))
  14041. (define (add1 [x : Any]) : Any
  14042. (inject (+ (project x Integer) 1) Integer))
  14043. (let ([v (vector 0 41)])
  14044. (begin
  14045. (map-vec! add1 (vector-proxy v
  14046. (raw-vector (lambda: ([x9 : Integer]) : Any
  14047. (inject x9 Integer))
  14048. (lambda: ([x9 : Integer]) : Any
  14049. (inject x9 Integer)))
  14050. (raw-vector (lambda: ([x9 : Any]) : Integer
  14051. (project x9 Integer))
  14052. (lambda: ([x9 : Any]) : Integer
  14053. (project x9 Integer)))))
  14054. (vector-ref v 1)))
  14055. \end{lstlisting}
  14056. \caption{Output of \code{lower-casts} on the example in
  14057. Figure~\ref{fig:map-vec-bang}.}
  14058. \label{fig:map-vec-bang-lower-cast}
  14059. \end{figure}
  14060. A cast from one function type to another function type is accomplished
  14061. by generating a \code{Lambda} whose parameter and return types match
  14062. the target function type. The body of the \code{Lambda} should cast
  14063. the parameters from the target type to the source type (yes,
  14064. backwards! functions are contravariant\index{subject}{contravariant} in the
  14065. parameters), then call the underlying function, and finally cast the
  14066. result from the source return type to the target return type.
  14067. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  14068. \code{lower-casts} pass on the \code{map-vec} example in
  14069. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  14070. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  14071. \begin{figure}[tbp]
  14072. \begin{lstlisting}
  14073. (define (map-vec [f : (Integer -> Integer)]
  14074. [v : (Vector Integer Integer)])
  14075. : (Vector Integer Integer)
  14076. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14077. (define (add1 [x : Any]) : Any
  14078. (inject (+ (project x Integer) 1) Integer))
  14079. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  14080. (project (add1 (inject x9 Integer)) Integer))
  14081. (vector 0 41)) 1)
  14082. \end{lstlisting}
  14083. \caption{Output of \code{lower-casts} on the example in
  14084. Figure~\ref{fig:gradual-map-vec}.}
  14085. \label{fig:map-vec-lower-cast}
  14086. \end{figure}
  14087. \section{Differentiate Proxies}
  14088. \label{sec:differentiate-proxies}
  14089. So far the job of differentiating vectors and vector proxies has been
  14090. the job of the interpreter. For example, the interpreter for \LangCast{}
  14091. implements \code{vector-ref} using the \code{guarded-vector-ref}
  14092. function in Figure~\ref{fig:guarded-vector}. In the
  14093. \code{differentiate-proxies} pass we shift this responsibility to the
  14094. generated code.
  14095. We begin by designing the output language $R^p_8$. In
  14096. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  14097. proxies. In $R^p_8$ we return the \code{Vector} type to
  14098. its original meaning, as the type of real vectors, and we introduce a
  14099. new type, \code{PVector}, whose values can be either real vectors or
  14100. vector proxies. This new type comes with a suite of new primitive
  14101. operations for creating and using values of type \code{PVector}. We
  14102. don't need to introduce a new type to represent vector proxies. A
  14103. proxy is represented by a vector containing three things: 1) the
  14104. underlying vector, 2) a vector of functions for casting elements that
  14105. are read from the vector, and 3) a vector of functions for casting
  14106. values to be written to the vector. So we define the following
  14107. abbreviation for the type of a vector proxy:
  14108. \[
  14109. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  14110. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  14111. \to (\key{PVector}~ T' \ldots)
  14112. \]
  14113. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  14114. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  14115. %
  14116. Next we describe each of the new primitive operations.
  14117. \begin{description}
  14118. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  14119. (\key{PVector} $T \ldots$)]\ \\
  14120. %
  14121. This operation brands a vector as a value of the \code{PVector} type.
  14122. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  14123. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  14124. %
  14125. This operation brands a vector proxy as value of the \code{PVector} type.
  14126. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  14127. \code{Boolean}] \ \\
  14128. %
  14129. returns true if the value is a vector proxy and false if it is a
  14130. real vector.
  14131. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  14132. (\key{Vector} $T \ldots$)]\ \\
  14133. %
  14134. Assuming that the input is a vector (and not a proxy), this
  14135. operation returns the vector.
  14136. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  14137. $\to$ \code{Boolean}]\ \\
  14138. %
  14139. Given a vector proxy, this operation returns the length of the
  14140. underlying vector.
  14141. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  14142. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  14143. %
  14144. Given a vector proxy, this operation returns the $i$th element of
  14145. the underlying vector.
  14146. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  14147. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  14148. proxy, this operation writes a value to the $i$th element of the
  14149. underlying vector.
  14150. \end{description}
  14151. Now to discuss the translation that differentiates vectors from
  14152. proxies. First, every type annotation in the program must be
  14153. translated (recursively) to replace \code{Vector} with \code{PVector}.
  14154. Next, we must insert uses of \code{PVector} operations in the
  14155. appropriate places. For example, we wrap every vector creation with an
  14156. \code{inject-vector}.
  14157. \begin{lstlisting}
  14158. (vector |$e_1 \ldots e_n$|)
  14159. |$\Rightarrow$|
  14160. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  14161. \end{lstlisting}
  14162. The \code{raw-vector} operator that we introduced in the previous
  14163. section does not get injected.
  14164. \begin{lstlisting}
  14165. (raw-vector |$e_1 \ldots e_n$|)
  14166. |$\Rightarrow$|
  14167. (vector |$e'_1 \ldots e'_n$|)
  14168. \end{lstlisting}
  14169. The \code{vector-proxy} primitive translates as follows.
  14170. \begin{lstlisting}
  14171. (vector-proxy |$e_1~e_2~e_3$|)
  14172. |$\Rightarrow$|
  14173. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  14174. \end{lstlisting}
  14175. We translate the vector operations into conditional expressions that
  14176. check whether the value is a proxy and then dispatch to either the
  14177. appropriate proxy vector operation or the regular vector operation.
  14178. For example, the following is the translation for \code{vector-ref}.
  14179. \begin{lstlisting}
  14180. (vector-ref |$e_1$| |$i$|)
  14181. |$\Rightarrow$|
  14182. (let ([|$v~e_1$|])
  14183. (if (proxy? |$v$|)
  14184. (proxy-vector-ref |$v$| |$i$|)
  14185. (vector-ref (project-vector |$v$|) |$i$|)
  14186. \end{lstlisting}
  14187. Note in the case of a real vector, we must apply \code{project-vector}
  14188. before the \code{vector-ref}.
  14189. \section{Reveal Casts}
  14190. \label{sec:reveal-casts-gradual}
  14191. Recall that the \code{reveal-casts} pass
  14192. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  14193. \code{Inject} and \code{Project} into lower-level operations. In
  14194. particular, \code{Project} turns into a conditional expression that
  14195. inspects the tag and retrieves the underlying value. Here we need to
  14196. augment the translation of \code{Project} to handle the situation when
  14197. the target type is \code{PVector}. Instead of using
  14198. \code{vector-length} we need to use \code{proxy-vector-length}.
  14199. \begin{lstlisting}
  14200. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  14201. |$\Rightarrow$|
  14202. (let |$\itm{tmp}$| |$e'$|
  14203. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  14204. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  14205. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  14206. (exit)))
  14207. \end{lstlisting}
  14208. \section{Closure Conversion}
  14209. \label{sec:closure-conversion-gradual}
  14210. The closure conversion pass only requires one minor adjustment. The
  14211. auxiliary function that translates type annotations needs to be
  14212. updated to handle the \code{PVector} type.
  14213. \section{Explicate Control}
  14214. \label{sec:explicate-control-gradual}
  14215. Update the \code{explicate\_control} pass to handle the new primitive
  14216. operations on the \code{PVector} type.
  14217. \section{Select Instructions}
  14218. \label{sec:select-instructions-gradual}
  14219. Recall that the \code{select-instructions} pass is responsible for
  14220. lowering the primitive operations into x86 instructions. So we need
  14221. to translate the new \code{PVector} operations to x86. To do so, the
  14222. first question we need to answer is how will we differentiate the two
  14223. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  14224. We need just one bit to accomplish this, and use the bit in position
  14225. $57$ of the 64-bit tag at the front of every vector (see
  14226. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  14227. for \code{inject-vector} we leave it that way.
  14228. \begin{lstlisting}
  14229. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  14230. |$\Rightarrow$|
  14231. movq |$e'_1$|, |$\itm{lhs'}$|
  14232. \end{lstlisting}
  14233. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  14234. \begin{lstlisting}
  14235. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  14236. |$\Rightarrow$|
  14237. movq |$e'_1$|, %r11
  14238. movq |$(1 << 57)$|, %rax
  14239. orq 0(%r11), %rax
  14240. movq %rax, 0(%r11)
  14241. movq %r11, |$\itm{lhs'}$|
  14242. \end{lstlisting}
  14243. The \code{proxy?} operation consumes the information so carefully
  14244. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  14245. isolates the $57$th bit to tell whether the value is a real vector or
  14246. a proxy.
  14247. \begin{lstlisting}
  14248. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  14249. |$\Rightarrow$|
  14250. movq |$e_1'$|, %r11
  14251. movq 0(%r11), %rax
  14252. sarq $57, %rax
  14253. andq $1, %rax
  14254. movq %rax, |$\itm{lhs'}$|
  14255. \end{lstlisting}
  14256. The \code{project-vector} operation is straightforward to translate,
  14257. so we leave it up to the reader.
  14258. Regarding the \code{proxy-vector} operations, the runtime provides
  14259. procedures that implement them (they are recursive functions!) so
  14260. here we simply need to translate these vector operations into the
  14261. appropriate function call. For example, here is the translation for
  14262. \code{proxy-vector-ref}.
  14263. \begin{lstlisting}
  14264. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  14265. |$\Rightarrow$|
  14266. movq |$e_1'$|, %rdi
  14267. movq |$e_2'$|, %rsi
  14268. callq proxy_vector_ref
  14269. movq %rax, |$\itm{lhs'}$|
  14270. \end{lstlisting}
  14271. We have another batch of vector operations to deal with, those for the
  14272. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  14273. \code{any-vector-ref} when there is a \code{vector-ref} on something
  14274. of type \code{Any}, and similarly for \code{any-vector-set!} and
  14275. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  14276. Section~\ref{sec:select-Rany} we selected instructions for these
  14277. operations based on the idea that the underlying value was a real
  14278. vector. But in the current setting, the underlying value is of type
  14279. \code{PVector}. So \code{any-vector-ref} can be translates to
  14280. pseudo-x86 as follows. We begin by projecting the underlying value out
  14281. of the tagged value and then call the \code{proxy\_vector\_ref}
  14282. procedure in the runtime.
  14283. \begin{lstlisting}
  14284. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  14285. movq |$\neg 111$|, %rdi
  14286. andq |$e_1'$|, %rdi
  14287. movq |$e_2'$|, %rsi
  14288. callq proxy_vector_ref
  14289. movq %rax, |$\itm{lhs'}$|
  14290. \end{lstlisting}
  14291. The \code{any-vector-set!} and \code{any-vector-length} operators can
  14292. be translated in a similar way.
  14293. \begin{exercise}\normalfont
  14294. Implement a compiler for the gradually-typed \LangGrad{} language by
  14295. extending and adapting your compiler for \LangLoop{}. Create 10 new
  14296. partially-typed test programs. In addition to testing with these
  14297. new programs, also test your compiler on all the tests for \LangLoop{}
  14298. and tests for \LangDyn{}. Sometimes you may get a type checking error
  14299. on the \LangDyn{} programs but you can adapt them by inserting
  14300. a cast to the \code{Any} type around each subexpression
  14301. causing a type error. While \LangDyn{} doesn't have explicit casts,
  14302. you can induce one by wrapping the subexpression \code{e}
  14303. with a call to an un-annotated identity function, like this:
  14304. \code{((lambda (x) x) e)}.
  14305. \end{exercise}
  14306. \begin{figure}[p]
  14307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14308. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  14309. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  14310. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  14311. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  14312. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  14313. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  14314. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  14315. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  14316. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  14317. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  14318. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  14319. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  14320. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  14321. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  14322. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14323. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14324. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14325. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14326. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14327. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14328. \path[->,bend right=15] (Rgradual) edge [above] node
  14329. {\ttfamily\footnotesize type-check} (Rgradualp);
  14330. \path[->,bend right=15] (Rgradualp) edge [above] node
  14331. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  14332. \path[->,bend right=15] (Rwhilepp) edge [right] node
  14333. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  14334. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  14335. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  14336. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  14337. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  14338. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  14339. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  14340. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  14341. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  14342. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  14343. {\ttfamily\footnotesize convert-assignments} (F1-1);
  14344. \path[->,bend left=15] (F1-1) edge [below] node
  14345. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  14346. \path[->,bend right=15] (F1-2) edge [above] node
  14347. {\ttfamily\footnotesize limit-fun.} (F1-3);
  14348. \path[->,bend right=15] (F1-3) edge [above] node
  14349. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  14350. \path[->,bend right=15] (F1-4) edge [above] node
  14351. {\ttfamily\footnotesize remove-complex.} (F1-5);
  14352. \path[->,bend right=15] (F1-5) edge [right] node
  14353. {\ttfamily\footnotesize explicate-control} (C3-2);
  14354. \path[->,bend left=15] (C3-2) edge [left] node
  14355. {\ttfamily\footnotesize select-instr.} (x86-2);
  14356. \path[->,bend right=15] (x86-2) edge [left] node
  14357. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  14358. \path[->,bend right=15] (x86-2-1) edge [below] node
  14359. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  14360. \path[->,bend right=15] (x86-2-2) edge [left] node
  14361. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  14362. \path[->,bend left=15] (x86-3) edge [above] node
  14363. {\ttfamily\footnotesize patch-instr.} (x86-4);
  14364. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  14365. \end{tikzpicture}
  14366. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  14367. \label{fig:Rgradual-passes}
  14368. \end{figure}
  14369. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  14370. for the compilation of \LangGrad{}.
  14371. \section{Further Reading}
  14372. This chapter just scratches the surface of gradual typing. The basic
  14373. approach described here is missing two key ingredients that one would
  14374. want in a implementation of gradual typing: blame
  14375. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  14376. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  14377. problem addressed by blame tracking is that when a cast on a
  14378. higher-order value fails, it often does so at a point in the program
  14379. that is far removed from the original cast. Blame tracking is a
  14380. technique for propagating extra information through casts and proxies
  14381. so that when a cast fails, the error message can point back to the
  14382. original location of the cast in the source program.
  14383. The problem addressed by space-efficient casts also relates to
  14384. higher-order casts. It turns out that in partially typed programs, a
  14385. function or vector can flow through very-many casts at runtime. With
  14386. the approach described in this chapter, each cast adds another
  14387. \code{lambda} wrapper or a vector proxy. Not only does this take up
  14388. considerable space, but it also makes the function calls and vector
  14389. operations slow. For example, a partially-typed version of quicksort
  14390. could, in the worst case, build a chain of proxies of length $O(n)$
  14391. around the vector, changing the overall time complexity of the
  14392. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  14393. solution to this problem by representing casts using the coercion
  14394. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  14395. long chains of proxies by compressing them into a concise normal
  14396. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  14397. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  14398. the Grift compiler.
  14399. \begin{center}
  14400. \url{https://github.com/Gradual-Typing/Grift}
  14401. \end{center}
  14402. There are also interesting interactions between gradual typing and
  14403. other language features, such as parametetric polymorphism,
  14404. information-flow types, and type inference, to name a few. We
  14405. recommend the reader to the online gradual typing bibliography:
  14406. \begin{center}
  14407. \url{http://samth.github.io/gradual-typing-bib/}
  14408. \end{center}
  14409. % TODO: challenge problem:
  14410. % type analysis and type specialization?
  14411. % coercions?
  14412. \fi
  14413. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14414. \chapter{Parametric Polymorphism}
  14415. \label{ch:Rpoly}
  14416. \index{subject}{parametric polymorphism}
  14417. \index{subject}{generics}
  14418. \if\edition\racketEd
  14419. This chapter studies the compilation of parametric
  14420. polymorphism\index{subject}{parametric polymorphism}
  14421. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  14422. Racket. Parametric polymorphism enables improved code reuse by
  14423. parameterizing functions and data structures with respect to the types
  14424. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  14425. revisits the \code{map-vec} example but this time gives it a more
  14426. fitting type. This \code{map-vec} function is parameterized with
  14427. respect to the element type of the vector. The type of \code{map-vec}
  14428. is the following polymorphic type as specified by the \code{All} and
  14429. the type parameter \code{a}.
  14430. \begin{lstlisting}
  14431. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14432. \end{lstlisting}
  14433. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  14434. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  14435. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  14436. \code{a}, but we could have just as well applied \code{map-vec} to a
  14437. vector of Booleans (and a function on Booleans).
  14438. \begin{figure}[tbp]
  14439. % poly_test_2.rkt
  14440. \begin{lstlisting}
  14441. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  14442. (define (map-vec f v)
  14443. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14444. (define (add1 [x : Integer]) : Integer (+ x 1))
  14445. (vector-ref (map-vec add1 (vector 0 41)) 1)
  14446. \end{lstlisting}
  14447. \caption{The \code{map-vec} example using parametric polymorphism.}
  14448. \label{fig:map-vec-poly}
  14449. \end{figure}
  14450. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  14451. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  14452. syntax. We add a second form for function definitions in which a type
  14453. declaration comes before the \code{define}. In the abstract syntax,
  14454. the return type in the \code{Def} is \code{Any}, but that should be
  14455. ignored in favor of the return type in the type declaration. (The
  14456. \code{Any} comes from using the same parser as in
  14457. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  14458. enables the use of an \code{All} type for a function, thereby making
  14459. it polymorphic. The grammar for types is extended to include
  14460. polymorphic types and type variables.
  14461. \begin{figure}[tp]
  14462. \centering
  14463. \fbox{
  14464. \begin{minipage}{0.96\textwidth}
  14465. \small
  14466. \[
  14467. \begin{array}{lcl}
  14468. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14469. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  14470. &\MID& \LP\key{:}~\Var~\Type\RP \\
  14471. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  14472. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  14473. \end{array}
  14474. \]
  14475. \end{minipage}
  14476. }
  14477. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  14478. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  14479. \label{fig:Rpoly-concrete-syntax}
  14480. \end{figure}
  14481. \begin{figure}[tp]
  14482. \centering
  14483. \fbox{
  14484. \begin{minipage}{0.96\textwidth}
  14485. \small
  14486. \[
  14487. \begin{array}{lcl}
  14488. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14489. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  14490. &\MID& \DECL{\Var}{\Type} \\
  14491. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  14492. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14493. \end{array}
  14494. \]
  14495. \end{minipage}
  14496. }
  14497. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  14498. (Figure~\ref{fig:Rwhile-syntax}).}
  14499. \label{fig:Rpoly-syntax}
  14500. \end{figure}
  14501. By including polymorphic types in the $\Type$ non-terminal we choose
  14502. to make them first-class which has interesting repercussions on the
  14503. compiler. Many languages with polymorphism, such as
  14504. C++~\citep{stroustrup88:_param_types} and Standard
  14505. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  14506. it is useful to see an example of first-class polymorphism. In
  14507. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  14508. whose parameter is a polymorphic function. The occurrence of a
  14509. polymorphic type underneath a function type is enabled by the normal
  14510. recursive structure of the grammar for $\Type$ and the categorization
  14511. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  14512. applies the polymorphic function to a Boolean and to an integer.
  14513. \begin{figure}[tbp]
  14514. \begin{lstlisting}
  14515. (: apply-twice ((All (b) (b -> b)) -> Integer))
  14516. (define (apply-twice f)
  14517. (if (f #t) (f 42) (f 777)))
  14518. (: id (All (a) (a -> a)))
  14519. (define (id x) x)
  14520. (apply-twice id)
  14521. \end{lstlisting}
  14522. \caption{An example illustrating first-class polymorphism.}
  14523. \label{fig:apply-twice}
  14524. \end{figure}
  14525. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  14526. three new responsibilities (compared to \LangLoop{}). The type checking of
  14527. function application is extended to handle the case where the operator
  14528. expression is a polymorphic function. In that case the type arguments
  14529. are deduced by matching the type of the parameters with the types of
  14530. the arguments.
  14531. %
  14532. The \code{match-types} auxiliary function carries out this deduction
  14533. by recursively descending through a parameter type \code{pt} and the
  14534. corresponding argument type \code{at}, making sure that they are equal
  14535. except when there is a type parameter on the left (in the parameter
  14536. type). If it's the first time that the type parameter has been
  14537. encountered, then the algorithm deduces an association of the type
  14538. parameter to the corresponding type on the right (in the argument
  14539. type). If it's not the first time that the type parameter has been
  14540. encountered, the algorithm looks up its deduced type and makes sure
  14541. that it is equal to the type on the right.
  14542. %
  14543. Once the type arguments are deduced, the operator expression is
  14544. wrapped in an \code{Inst} AST node (for instantiate) that records the
  14545. type of the operator, but more importantly, records the deduced type
  14546. arguments. The return type of the application is the return type of
  14547. the polymorphic function, but with the type parameters replaced by the
  14548. deduced type arguments, using the \code{subst-type} function.
  14549. The second responsibility of the type checker is extending the
  14550. function \code{type-equal?} to handle the \code{All} type. This is
  14551. not quite a simple as equal on other types, such as function and
  14552. vector types, because two polymorphic types can be syntactically
  14553. different even though they are equivalent types. For example,
  14554. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  14555. Two polymorphic types should be considered equal if they differ only
  14556. in the choice of the names of the type parameters. The
  14557. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  14558. renames the type parameters of the first type to match the type
  14559. parameters of the second type.
  14560. The third responsibility of the type checker is making sure that only
  14561. defined type variables appear in type annotations. The
  14562. \code{check-well-formed} function defined in
  14563. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  14564. sure that each type variable has been defined.
  14565. The output language of the type checker is \LangInst{}, defined in
  14566. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  14567. declaration and polymorphic function into a single definition, using
  14568. the \code{Poly} form, to make polymorphic functions more convenient to
  14569. process in next pass of the compiler.
  14570. \begin{figure}[tp]
  14571. \centering
  14572. \fbox{
  14573. \begin{minipage}{0.96\textwidth}
  14574. \small
  14575. \[
  14576. \begin{array}{lcl}
  14577. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14578. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  14579. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  14580. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  14581. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14582. \end{array}
  14583. \]
  14584. \end{minipage}
  14585. }
  14586. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  14587. (Figure~\ref{fig:Rwhile-syntax}).}
  14588. \label{fig:Rpoly-prime-syntax}
  14589. \end{figure}
  14590. The output of the type checker on the polymorphic \code{map-vec}
  14591. example is listed in Figure~\ref{fig:map-vec-type-check}.
  14592. \begin{figure}[tbp]
  14593. % poly_test_2.rkt
  14594. \begin{lstlisting}
  14595. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  14596. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  14597. (define (add1 [x : Integer]) : Integer (+ x 1))
  14598. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14599. (Integer))
  14600. add1 (vector 0 41)) 1)
  14601. \end{lstlisting}
  14602. \caption{Output of the type checker on the \code{map-vec} example.}
  14603. \label{fig:map-vec-type-check}
  14604. \end{figure}
  14605. \begin{figure}[tbp]
  14606. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14607. (define type-check-poly-class
  14608. (class type-check-Rwhile-class
  14609. (super-new)
  14610. (inherit check-type-equal?)
  14611. (define/override (type-check-apply env e1 es)
  14612. (define-values (e^ ty) ((type-check-exp env) e1))
  14613. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  14614. ((type-check-exp env) e)))
  14615. (match ty
  14616. [`(,ty^* ... -> ,rt)
  14617. (for ([arg-ty ty*] [param-ty ty^*])
  14618. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  14619. (values e^ es^ rt)]
  14620. [`(All ,xs (,tys ... -> ,rt))
  14621. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  14622. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  14623. (match-types env^^ param-ty arg-ty)))
  14624. (define targs
  14625. (for/list ([x xs])
  14626. (match (dict-ref env^^ x (lambda () #f))
  14627. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  14628. x (Apply e1 es))]
  14629. [ty ty])))
  14630. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  14631. [else (error 'type-check "expected a function, not ~a" ty)]))
  14632. (define/override ((type-check-exp env) e)
  14633. (match e
  14634. [(Lambda `([,xs : ,Ts] ...) rT body)
  14635. (for ([T Ts]) ((check-well-formed env) T))
  14636. ((check-well-formed env) rT)
  14637. ((super type-check-exp env) e)]
  14638. [(HasType e1 ty)
  14639. ((check-well-formed env) ty)
  14640. ((super type-check-exp env) e)]
  14641. [else ((super type-check-exp env) e)]))
  14642. (define/override ((type-check-def env) d)
  14643. (verbose 'type-check "poly/def" d)
  14644. (match d
  14645. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  14646. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  14647. (for ([p ps]) ((check-well-formed ts-env) p))
  14648. ((check-well-formed ts-env) rt)
  14649. (define new-env (append ts-env (map cons xs ps) env))
  14650. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14651. (check-type-equal? ty^ rt body)
  14652. (Generic ts (Def f p:t* rt info body^))]
  14653. [else ((super type-check-def env) d)]))
  14654. (define/override (type-check-program p)
  14655. (match p
  14656. [(Program info body)
  14657. (type-check-program (ProgramDefsExp info '() body))]
  14658. [(ProgramDefsExp info ds body)
  14659. (define ds^ (combine-decls-defs ds))
  14660. (define new-env (for/list ([d ds^])
  14661. (cons (def-name d) (fun-def-type d))))
  14662. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  14663. (define-values (body^ ty) ((type-check-exp new-env) body))
  14664. (check-type-equal? ty 'Integer body)
  14665. (ProgramDefsExp info ds^^ body^)]))
  14666. ))
  14667. \end{lstlisting}
  14668. \caption{Type checker for the \LangPoly{} language.}
  14669. \label{fig:type-check-Rvar0}
  14670. \end{figure}
  14671. \begin{figure}[tbp]
  14672. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14673. (define/override (type-equal? t1 t2)
  14674. (match* (t1 t2)
  14675. [(`(All ,xs ,T1) `(All ,ys ,T2))
  14676. (define env (map cons xs ys))
  14677. (type-equal? (subst-type env T1) T2)]
  14678. [(other wise)
  14679. (super type-equal? t1 t2)]))
  14680. (define/public (match-types env pt at)
  14681. (match* (pt at)
  14682. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  14683. [('Void 'Void) env] [('Any 'Any) env]
  14684. [(`(Vector ,pts ...) `(Vector ,ats ...))
  14685. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  14686. (match-types env^ pt1 at1))]
  14687. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  14688. (define env^ (match-types env prt art))
  14689. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  14690. (match-types env^^ pt1 at1))]
  14691. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  14692. (define env^ (append (map cons pxs axs) env))
  14693. (match-types env^ pt1 at1)]
  14694. [((? symbol? x) at)
  14695. (match (dict-ref env x (lambda () #f))
  14696. [#f (error 'type-check "undefined type variable ~a" x)]
  14697. ['Type (cons (cons x at) env)]
  14698. [t^ (check-type-equal? at t^ 'matching) env])]
  14699. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  14700. (define/public (subst-type env pt)
  14701. (match pt
  14702. ['Integer 'Integer] ['Boolean 'Boolean]
  14703. ['Void 'Void] ['Any 'Any]
  14704. [`(Vector ,ts ...)
  14705. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  14706. [`(,ts ... -> ,rt)
  14707. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  14708. [`(All ,xs ,t)
  14709. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  14710. [(? symbol? x) (dict-ref env x)]
  14711. [else (error 'type-check "expected a type not ~a" pt)]))
  14712. (define/public (combine-decls-defs ds)
  14713. (match ds
  14714. ['() '()]
  14715. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  14716. (unless (equal? name f)
  14717. (error 'type-check "name mismatch, ~a != ~a" name f))
  14718. (match type
  14719. [`(All ,xs (,ps ... -> ,rt))
  14720. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  14721. (cons (Generic xs (Def name params^ rt info body))
  14722. (combine-decls-defs ds^))]
  14723. [`(,ps ... -> ,rt)
  14724. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  14725. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  14726. [else (error 'type-check "expected a function type, not ~a" type) ])]
  14727. [`(,(Def f params rt info body) . ,ds^)
  14728. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  14729. \end{lstlisting}
  14730. \caption{Auxiliary functions for type checking \LangPoly{}.}
  14731. \label{fig:type-check-Rvar0-aux}
  14732. \end{figure}
  14733. \begin{figure}[tbp]
  14734. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  14735. (define/public ((check-well-formed env) ty)
  14736. (match ty
  14737. ['Integer (void)]
  14738. ['Boolean (void)]
  14739. ['Void (void)]
  14740. [(? symbol? a)
  14741. (match (dict-ref env a (lambda () #f))
  14742. ['Type (void)]
  14743. [else (error 'type-check "undefined type variable ~a" a)])]
  14744. [`(Vector ,ts ...)
  14745. (for ([t ts]) ((check-well-formed env) t))]
  14746. [`(,ts ... -> ,t)
  14747. (for ([t ts]) ((check-well-formed env) t))
  14748. ((check-well-formed env) t)]
  14749. [`(All ,xs ,t)
  14750. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  14751. ((check-well-formed env^) t)]
  14752. [else (error 'type-check "unrecognized type ~a" ty)]))
  14753. \end{lstlisting}
  14754. \caption{Well-formed types.}
  14755. \label{fig:well-formed-types}
  14756. \end{figure}
  14757. % TODO: interpreter for R'_10
  14758. \section{Compiling Polymorphism}
  14759. \label{sec:compiling-poly}
  14760. Broadly speaking, there are four approaches to compiling parametric
  14761. polymorphism, which we describe below.
  14762. \begin{description}
  14763. \item[Monomorphization] generates a different version of a polymorphic
  14764. function for each set of type arguments that it is used with,
  14765. producing type-specialized code. This approach results in the most
  14766. efficient code but requires whole-program compilation (no separate
  14767. compilation) and increases code size. For our current purposes
  14768. monomorphization is a non-starter because, with first-class
  14769. polymorphism, it is sometimes not possible to determine which
  14770. generic functions are used with which type arguments during
  14771. compilation. (It can be done at runtime, with just-in-time
  14772. compilation.) This approach is used to compile C++
  14773. templates~\citep{stroustrup88:_param_types} and polymorphic
  14774. functions in NESL~\citep{Blelloch:1993aa} and
  14775. ML~\citep{Weeks:2006aa}.
  14776. \item[Uniform representation] generates one version of each
  14777. polymorphic function but requires all values have a common ``boxed''
  14778. format, such as the tagged values of type \code{Any} in
  14779. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  14780. similarly to code in a dynamically typed language (like \LangDyn{}),
  14781. in which primitive operators require their arguments to be projected
  14782. from \code{Any} and their results are injected into \code{Any}. (In
  14783. object-oriented languages, the projection is accomplished via
  14784. virtual method dispatch.) The uniform representation approach is
  14785. compatible with separate compilation and with first-class
  14786. polymorphism. However, it produces the least-efficient code because
  14787. it introduces overhead in the entire program, including
  14788. non-polymorphic code. This approach is used in implementations of
  14789. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  14790. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  14791. Java~\citep{Bracha:1998fk}.
  14792. \item[Mixed representation] generates one version of each polymorphic
  14793. function, using a boxed representation for type
  14794. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  14795. and conversions are performed at the boundaries between monomorphic
  14796. and polymorphic (e.g. when a polymorphic function is instantiated
  14797. and called). This approach is compatible with separate compilation
  14798. and first-class polymorphism and maintains the efficiency of
  14799. monomorphic code. The tradeoff is increased overhead at the boundary
  14800. between monomorphic and polymorphic code. This approach is used in
  14801. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  14802. Java 5 with the addition of autoboxing.
  14803. \item[Type passing] uses the unboxed representation in both
  14804. monomorphic and polymorphic code. Each polymorphic function is
  14805. compiled to a single function with extra parameters that describe
  14806. the type arguments. The type information is used by the generated
  14807. code to know how to access the unboxed values at runtime. This
  14808. approach is used in implementation of the Napier88
  14809. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  14810. passing is compatible with separate compilation and first-class
  14811. polymorphism and maintains the efficiency for monomorphic
  14812. code. There is runtime overhead in polymorphic code from dispatching
  14813. on type information.
  14814. \end{description}
  14815. In this chapter we use the mixed representation approach, partly
  14816. because of its favorable attributes, and partly because it is
  14817. straightforward to implement using the tools that we have already
  14818. built to support gradual typing. To compile polymorphic functions, we
  14819. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  14820. \LangCast{}.
  14821. \section{Erase Types}
  14822. \label{sec:erase-types}
  14823. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  14824. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  14825. shows the output of the \code{erase-types} pass on the polymorphic
  14826. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  14827. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  14828. \code{All} types are removed from the type of \code{map-vec}.
  14829. \begin{figure}[tbp]
  14830. \begin{lstlisting}
  14831. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  14832. : (Vector Any Any)
  14833. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14834. (define (add1 [x : Integer]) : Integer (+ x 1))
  14835. (vector-ref ((cast map-vec
  14836. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  14837. ((Integer -> Integer) (Vector Integer Integer)
  14838. -> (Vector Integer Integer)))
  14839. add1 (vector 0 41)) 1)
  14840. \end{lstlisting}
  14841. \caption{The polymorphic \code{map-vec} example after type erasure.}
  14842. \label{fig:map-vec-erase}
  14843. \end{figure}
  14844. This process of type erasure creates a challenge at points of
  14845. instantiation. For example, consider the instantiation of
  14846. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  14847. The type of \code{map-vec} is
  14848. \begin{lstlisting}
  14849. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14850. \end{lstlisting}
  14851. and it is instantiated to
  14852. \begin{lstlisting}
  14853. ((Integer -> Integer) (Vector Integer Integer)
  14854. -> (Vector Integer Integer))
  14855. \end{lstlisting}
  14856. After erasure, the type of \code{map-vec} is
  14857. \begin{lstlisting}
  14858. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  14859. \end{lstlisting}
  14860. but we need to convert it to the instantiated type. This is easy to
  14861. do in the target language \LangCast{} with a single \code{cast}. In
  14862. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  14863. has been compiled to a \code{cast} from the type of \code{map-vec} to
  14864. the instantiated type. The source and target type of a cast must be
  14865. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  14866. because both the source and target are obtained from the same
  14867. polymorphic type of \code{map-vec}, replacing the type parameters with
  14868. \code{Any} in the former and with the deduced type arguments in the
  14869. later. (Recall that the \code{Any} type is consistent with any type.)
  14870. To implement the \code{erase-types} pass, we recommend defining a
  14871. recursive auxiliary function named \code{erase-type} that applies the
  14872. following two transformations. It replaces type variables with
  14873. \code{Any}
  14874. \begin{lstlisting}
  14875. |$x$|
  14876. |$\Rightarrow$|
  14877. Any
  14878. \end{lstlisting}
  14879. and it removes the polymorphic \code{All} types.
  14880. \begin{lstlisting}
  14881. (All |$xs$| |$T_1$|)
  14882. |$\Rightarrow$|
  14883. |$T'_1$|
  14884. \end{lstlisting}
  14885. Apply the \code{erase-type} function to all of the type annotations in
  14886. the program.
  14887. Regarding the translation of expressions, the case for \code{Inst} is
  14888. the interesting one. We translate it into a \code{Cast}, as shown
  14889. below. The type of the subexpression $e$ is the polymorphic type
  14890. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  14891. $T$, the type $T'$. The target type $T''$ is the result of
  14892. substituting the arguments types $ts$ for the type parameters $xs$ in
  14893. $T$ followed by doing type erasure.
  14894. \begin{lstlisting}
  14895. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  14896. |$\Rightarrow$|
  14897. (Cast |$e'$| |$T'$| |$T''$|)
  14898. \end{lstlisting}
  14899. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  14900. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  14901. Finally, each polymorphic function is translated to a regular
  14902. functions in which type erasure has been applied to all the type
  14903. annotations and the body.
  14904. \begin{lstlisting}
  14905. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  14906. |$\Rightarrow$|
  14907. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  14908. \end{lstlisting}
  14909. \begin{exercise}\normalfont
  14910. Implement a compiler for the polymorphic language \LangPoly{} by
  14911. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  14912. programs that use polymorphic functions. Some of them should make
  14913. use of first-class polymorphism.
  14914. \end{exercise}
  14915. \begin{figure}[p]
  14916. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14917. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  14918. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  14919. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  14920. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  14921. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  14922. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  14923. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  14924. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  14925. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  14926. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  14927. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  14928. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  14929. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  14930. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  14931. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  14932. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14933. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14934. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14935. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14936. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14937. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14938. \path[->,bend right=15] (Rpoly) edge [above] node
  14939. {\ttfamily\footnotesize type-check} (Rpolyp);
  14940. \path[->,bend right=15] (Rpolyp) edge [above] node
  14941. {\ttfamily\footnotesize erase-types} (Rgradualp);
  14942. \path[->,bend right=15] (Rgradualp) edge [above] node
  14943. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  14944. \path[->,bend right=15] (Rwhilepp) edge [right] node
  14945. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  14946. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  14947. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  14948. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  14949. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  14950. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  14951. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  14952. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  14953. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  14954. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  14955. {\ttfamily\footnotesize convert-assignments} (F1-1);
  14956. \path[->,bend left=15] (F1-1) edge [below] node
  14957. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  14958. \path[->,bend right=15] (F1-2) edge [above] node
  14959. {\ttfamily\footnotesize limit-fun.} (F1-3);
  14960. \path[->,bend right=15] (F1-3) edge [above] node
  14961. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  14962. \path[->,bend right=15] (F1-4) edge [above] node
  14963. {\ttfamily\footnotesize remove-complex.} (F1-5);
  14964. \path[->,bend right=15] (F1-5) edge [right] node
  14965. {\ttfamily\footnotesize explicate-control} (C3-2);
  14966. \path[->,bend left=15] (C3-2) edge [left] node
  14967. {\ttfamily\footnotesize select-instr.} (x86-2);
  14968. \path[->,bend right=15] (x86-2) edge [left] node
  14969. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  14970. \path[->,bend right=15] (x86-2-1) edge [below] node
  14971. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  14972. \path[->,bend right=15] (x86-2-2) edge [left] node
  14973. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  14974. \path[->,bend left=15] (x86-3) edge [above] node
  14975. {\ttfamily\footnotesize patch-instr.} (x86-4);
  14976. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  14977. \end{tikzpicture}
  14978. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  14979. \label{fig:Rpoly-passes}
  14980. \end{figure}
  14981. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  14982. for the compilation of \LangPoly{}.
  14983. % TODO: challenge problem: specialization of instantiations
  14984. % Further Reading
  14985. \fi
  14986. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14987. \clearpage
  14988. \appendix
  14989. \chapter{Appendix}
  14990. \if\edition\racketEd
  14991. \section{Interpreters}
  14992. \label{appendix:interp}
  14993. \index{subject}{interpreter}
  14994. We provide interpreters for each of the source languages \LangInt{},
  14995. \LangVar{}, $\ldots$ in the files \code{interp\_Rint.rkt},
  14996. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  14997. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  14998. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  14999. and x86 are in the \key{interp.rkt} file.
  15000. \section{Utility Functions}
  15001. \label{appendix:utilities}
  15002. The utility functions described in this section are in the
  15003. \key{utilities.rkt} file of the support code.
  15004. \paragraph{\code{interp-tests}}
  15005. The \key{interp-tests} function runs the compiler passes and the
  15006. interpreters on each of the specified tests to check whether each pass
  15007. is correct. The \key{interp-tests} function has the following
  15008. parameters:
  15009. \begin{description}
  15010. \item[name (a string)] a name to identify the compiler,
  15011. \item[typechecker] a function of exactly one argument that either
  15012. raises an error using the \code{error} function when it encounters a
  15013. type error, or returns \code{\#f} when it encounters a type
  15014. error. If there is no type error, the type checker returns the
  15015. program.
  15016. \item[passes] a list with one entry per pass. An entry is a list with
  15017. four things:
  15018. \begin{enumerate}
  15019. \item a string giving the name of the pass,
  15020. \item the function that implements the pass (a translator from AST
  15021. to AST),
  15022. \item a function that implements the interpreter (a function from
  15023. AST to result value) for the output language,
  15024. \item and a type checker for the output language. Type checkers for
  15025. the $R$ and $C$ languages are provided in the support code. For
  15026. example, the type checkers for \LangVar{} and \LangCVar{} are in
  15027. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  15028. type checker entry is optional. The support code does not provide
  15029. type checkers for the x86 languages.
  15030. \end{enumerate}
  15031. \item[source-interp] an interpreter for the source language. The
  15032. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  15033. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  15034. \item[tests] a list of test numbers that specifies which tests to
  15035. run. (see below)
  15036. \end{description}
  15037. %
  15038. The \key{interp-tests} function assumes that the subdirectory
  15039. \key{tests} has a collection of Racket programs whose names all start
  15040. with the family name, followed by an underscore and then the test
  15041. number, ending with the file extension \key{.rkt}. Also, for each test
  15042. program that calls \code{read} one or more times, there is a file with
  15043. the same name except that the file extension is \key{.in} that
  15044. provides the input for the Racket program. If the test program is
  15045. expected to fail type checking, then there should be an empty file of
  15046. the same name but with extension \key{.tyerr}.
  15047. \paragraph{\code{compiler-tests}}
  15048. runs the compiler passes to generate x86 (a \key{.s} file) and then
  15049. runs the GNU C compiler (gcc) to generate machine code. It runs the
  15050. machine code and checks that the output is $42$. The parameters to the
  15051. \code{compiler-tests} function are similar to those of the
  15052. \code{interp-tests} function, and consist of
  15053. \begin{itemize}
  15054. \item a compiler name (a string),
  15055. \item a type checker,
  15056. \item description of the passes,
  15057. \item name of a test-family, and
  15058. \item a list of test numbers.
  15059. \end{itemize}
  15060. \paragraph{\code{compile-file}}
  15061. takes a description of the compiler passes (see the comment for
  15062. \key{interp-tests}) and returns a function that, given a program file
  15063. name (a string ending in \key{.rkt}), applies all of the passes and
  15064. writes the output to a file whose name is the same as the program file
  15065. name but with \key{.rkt} replaced with \key{.s}.
  15066. \paragraph{\code{read-program}}
  15067. takes a file path and parses that file (it must be a Racket program)
  15068. into an abstract syntax tree.
  15069. \paragraph{\code{parse-program}}
  15070. takes an S-expression representation of an abstract syntax tree and converts it into
  15071. the struct-based representation.
  15072. \paragraph{\code{assert}}
  15073. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  15074. and displays the message \key{msg} if the Boolean \key{bool} is false.
  15075. \paragraph{\code{lookup}}
  15076. % remove discussion of lookup? -Jeremy
  15077. takes a key and an alist, and returns the first value that is
  15078. associated with the given key, if there is one. If not, an error is
  15079. triggered. The alist may contain both immutable pairs (built with
  15080. \key{cons}) and mutable pairs (built with \key{mcons}).
  15081. %The \key{map2} function ...
  15082. \fi %\racketEd
  15083. \section{x86 Instruction Set Quick-Reference}
  15084. \label{sec:x86-quick-reference}
  15085. \index{subject}{x86}
  15086. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  15087. do. We write $A \to B$ to mean that the value of $A$ is written into
  15088. location $B$. Address offsets are given in bytes. The instruction
  15089. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  15090. registers (such as \code{\%rax}), or memory references (such as
  15091. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  15092. reference per instruction. Other operands must be immediates or
  15093. registers.
  15094. \begin{table}[tbp]
  15095. \centering
  15096. \begin{tabular}{l|l}
  15097. \textbf{Instruction} & \textbf{Operation} \\ \hline
  15098. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  15099. \texttt{negq} $A$ & $- A \to A$ \\
  15100. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  15101. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  15102. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  15103. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  15104. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  15105. \texttt{retq} & Pops the return address and jumps to it \\
  15106. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  15107. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  15108. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  15109. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  15110. be an immediate) \\
  15111. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  15112. matches the condition code of the instruction, otherwise go to the
  15113. next instructions. The condition codes are \key{e} for ``equal'',
  15114. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  15115. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  15116. \texttt{jl} $L$ & \\
  15117. \texttt{jle} $L$ & \\
  15118. \texttt{jg} $L$ & \\
  15119. \texttt{jge} $L$ & \\
  15120. \texttt{jmp} $L$ & Jump to label $L$ \\
  15121. \texttt{movq} $A$, $B$ & $A \to B$ \\
  15122. \texttt{movzbq} $A$, $B$ &
  15123. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  15124. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  15125. and the extra bytes of $B$ are set to zero.} \\
  15126. & \\
  15127. & \\
  15128. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  15129. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  15130. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  15131. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  15132. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  15133. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  15134. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  15135. description of the condition codes. $A$ must be a single byte register
  15136. (e.g., \texttt{al} or \texttt{cl}).} \\
  15137. \texttt{setl} $A$ & \\
  15138. \texttt{setle} $A$ & \\
  15139. \texttt{setg} $A$ & \\
  15140. \texttt{setge} $A$ &
  15141. \end{tabular}
  15142. \vspace{5pt}
  15143. \caption{Quick-reference for the x86 instructions used in this book.}
  15144. \label{tab:x86-instr}
  15145. \end{table}
  15146. \if\edition\racketEd
  15147. \cleardoublepage
  15148. \section{Concrete Syntax for Intermediate Languages}
  15149. The concrete syntax of \LangAny{} is defined in
  15150. Figure~\ref{fig:Rany-concrete-syntax}.
  15151. \begin{figure}[tp]
  15152. \centering
  15153. \fbox{
  15154. \begin{minipage}{0.97\textwidth}\small
  15155. \[
  15156. \begin{array}{lcl}
  15157. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  15158. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  15159. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  15160. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15161. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15162. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15163. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  15164. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  15165. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  15166. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  15167. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  15168. \MID \LP\key{void?}\;\Exp\RP \\
  15169. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  15170. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  15171. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  15172. \end{array}
  15173. \]
  15174. \end{minipage}
  15175. }
  15176. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  15177. (Figure~\ref{fig:Rlam-syntax}).}
  15178. \label{fig:Rany-concrete-syntax}
  15179. \end{figure}
  15180. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  15181. defined in Figures~\ref{fig:c0-concrete-syntax},
  15182. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  15183. and \ref{fig:c3-concrete-syntax}, respectively.
  15184. \begin{figure}[tbp]
  15185. \fbox{
  15186. \begin{minipage}{0.96\textwidth}
  15187. \[
  15188. \begin{array}{lcl}
  15189. \Atm &::=& \Int \MID \Var \\
  15190. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  15191. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  15192. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  15193. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  15194. \end{array}
  15195. \]
  15196. \end{minipage}
  15197. }
  15198. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  15199. \label{fig:c0-concrete-syntax}
  15200. \end{figure}
  15201. \begin{figure}[tbp]
  15202. \fbox{
  15203. \begin{minipage}{0.96\textwidth}
  15204. \small
  15205. \[
  15206. \begin{array}{lcl}
  15207. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  15208. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  15209. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  15210. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  15211. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  15212. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  15213. \MID \key{goto}~\itm{label}\key{;}\\
  15214. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  15215. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  15216. \end{array}
  15217. \]
  15218. \end{minipage}
  15219. }
  15220. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  15221. \label{fig:c1-concrete-syntax}
  15222. \end{figure}
  15223. \begin{figure}[tbp]
  15224. \fbox{
  15225. \begin{minipage}{0.96\textwidth}
  15226. \small
  15227. \[
  15228. \begin{array}{lcl}
  15229. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  15230. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  15231. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  15232. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  15233. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  15234. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  15235. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  15236. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  15237. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  15238. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  15239. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  15240. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  15241. \end{array}
  15242. \]
  15243. \end{minipage}
  15244. }
  15245. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  15246. \label{fig:c2-concrete-syntax}
  15247. \end{figure}
  15248. \begin{figure}[tp]
  15249. \fbox{
  15250. \begin{minipage}{0.96\textwidth}
  15251. \small
  15252. \[
  15253. \begin{array}{lcl}
  15254. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  15255. \\
  15256. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  15257. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  15258. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  15259. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  15260. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  15261. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  15262. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  15263. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  15264. \MID \LP\key{collect} \,\itm{int}\RP }\\
  15265. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  15266. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  15267. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  15268. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  15269. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  15270. \LangCFunM{} & ::= & \Def\ldots
  15271. \end{array}
  15272. \]
  15273. \end{minipage}
  15274. }
  15275. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  15276. \label{fig:c3-concrete-syntax}
  15277. \end{figure}
  15278. \fi % racketEd
  15279. \backmatter
  15280. \addtocontents{toc}{\vspace{11pt}}
  15281. %% \addtocontents{toc}{\vspace{11pt}}
  15282. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  15283. \nocite{*}\let\bibname\refname
  15284. \addcontentsline{toc}{fmbm}{\refname}
  15285. \printbibliography
  15286. \printindex{authors}{Author Index}
  15287. \printindex{subject}{Subject Index}
  15288. \end{document}