book.tex 619 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. \usepackage[utf8]{inputenc}
  3. %% \usepackage{setspace}
  4. %% \doublespacing
  5. \usepackage{listings}
  6. \usepackage{verbatim}
  7. \usepackage{amssymb}
  8. \usepackage{lmodern} % better typewriter font for code
  9. %\usepackage{wrapfig}
  10. \usepackage{multirow}
  11. \usepackage{tcolorbox}
  12. \usepackage{color}
  13. %\usepackage{ifthen}
  14. \usepackage{upquote}
  15. \definecolor{lightgray}{gray}{1}
  16. \newcommand{\black}[1]{{\color{black} #1}}
  17. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  18. \newcommand{\gray}[1]{{\color{gray} #1}}
  19. \def\racketEd{0}
  20. \def\pythonEd{1}
  21. \def\edition{1}
  22. % material that is specific to the Racket edition of the book
  23. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  24. % would like a command for: \if\edition\racketEd\color{olive}
  25. % and : \fi\color{black}
  26. % material that is specific to the Python edition of the book
  27. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  28. %% For multiple indices:
  29. \usepackage{multind}
  30. \makeindex{subject}
  31. \makeindex{authors}
  32. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  33. \if\edition\racketEd
  34. \lstset{%
  35. language=Lisp,
  36. basicstyle=\ttfamily\small,
  37. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  38. deletekeywords={read,mapping,vector},
  39. escapechar=|,
  40. columns=flexible,
  41. moredelim=[is][\color{red}]{~}{~},
  42. showstringspaces=false
  43. }
  44. \fi
  45. \if\edition\pythonEd
  46. \lstset{%
  47. language=Python,
  48. basicstyle=\ttfamily\small,
  49. morekeywords={match,case,bool,int},
  50. deletekeywords={},
  51. escapechar=|,
  52. columns=flexible,
  53. moredelim=[is][\color{red}]{~}{~},
  54. showstringspaces=false
  55. }
  56. \fi
  57. %%% Any shortcut own defined macros place here
  58. %% sample of author macro:
  59. \input{defs}
  60. \newtheorem{exercise}[theorem]{Exercise}
  61. % Adjusted settings
  62. \setlength{\columnsep}{4pt}
  63. %% \begingroup
  64. %% \setlength{\intextsep}{0pt}%
  65. %% \setlength{\columnsep}{0pt}%
  66. %% \begin{wrapfigure}{r}{0.5\textwidth}
  67. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  68. %% \caption{Basic layout}
  69. %% \end{wrapfigure}
  70. %% \lipsum[1]
  71. %% \endgroup
  72. \newbox\oiintbox
  73. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  74. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  75. \def\oiint{\copy\oiintbox}
  76. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  77. %\usepackage{showframe}
  78. \def\ShowFrameLinethickness{0.125pt}
  79. \addbibresource{book.bib}
  80. \begin{document}
  81. \frontmatter
  82. \HalfTitle{Essentials of Compilation, \python{Python}\racket{Racket} Edition}
  83. \halftitlepage
  84. \Title{Essentials of Compilation, \python{Python}\racket{Racket} Edition}
  85. \Booksubtitle{The Incremental, Nano-Pass Approach}
  86. %\edition{First Edition}
  87. \BookAuthor{Jeremy G. Siek}
  88. \imprint{The MIT Press\\
  89. Cambridge, Massachusetts\\
  90. London, England}
  91. \begin{copyrightpage}
  92. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  93. or personal downloading under the
  94. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  95. license.
  96. Copyright in this monograph has been licensed exclusively to The MIT
  97. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  98. version to the public in 2022. All inquiries regarding rights should
  99. be addressed to The MIT Press, Rights and Permissions Department.
  100. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  101. %% All rights reserved. No part of this book may be reproduced in any
  102. %% form by any electronic or mechanical means (including photocopying,
  103. %% recording, or information storage and retrieval) without permission in
  104. %% writing from the publisher.
  105. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  106. %% United States of America.
  107. %% Library of Congress Cataloging-in-Publication Data is available.
  108. %% ISBN:
  109. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  110. \end{copyrightpage}
  111. \dedication{This book is dedicated to the programming language wonks
  112. at Indiana University.}
  113. %% \begin{epigraphpage}
  114. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  115. %% \textit{Book Name if any}}
  116. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  117. %% \end{epigraphpage}
  118. \tableofcontents
  119. %\listoffigures
  120. %\listoftables
  121. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  122. \chapter*{Preface}
  123. \addcontentsline{toc}{fmbm}{Preface}
  124. There is a magical moment when a programmer presses the ``run'' button
  125. and the software begins to execute. Somehow a program written in a
  126. high-level language is running on a computer that is only capable of
  127. shuffling bits. Here we reveal the wizardry that makes that moment
  128. possible. Beginning with the ground breaking work of Backus and
  129. colleagues in the 1950s, computer scientists discovered techniques for
  130. constructing programs, called \emph{compilers}, that automatically
  131. translate high-level programs into machine code.
  132. We take you on a journey by constructing your own compiler for a small
  133. but powerful language. Along the way we explain the essential
  134. concepts, algorithms, and data structures that underlie compilers. We
  135. develop your understanding of how programs are mapped onto computer
  136. hardware, which is helpful when reasoning about properties at the
  137. junction between hardware and software such as execution time,
  138. software errors, and security vulnerabilities. For those interested
  139. in pursuing compiler construction, our goal is to provide a
  140. stepping-stone to advanced topics such as just-in-time compilation,
  141. program analysis, and program optimization. For those interested in
  142. designing and implementing programming languages, we connect
  143. language design choices to their impact on the compiler and the generated
  144. code.
  145. A compiler is typically organized as a sequence of stages that
  146. progressively translate a program to code that runs on hardware. We
  147. take this approach to the extreme by partitioning our compiler into a
  148. large number of \emph{nanopasses}, each of which performs a single
  149. task. This allows us to test the output of each pass in isolation, and
  150. furthermore, allows us to focus our attention which makes the compiler
  151. far easier to understand.
  152. The most familiar approach to describing compilers is with one pass
  153. per chapter. The problem with that approach is it obfuscates how
  154. language features motivate design choices in a compiler. We take an
  155. \emph{incremental} approach in which we build a complete compiler in
  156. each chapter, starting with a small input language that includes only
  157. arithmetic and variables and we add new language features in
  158. subsequent chapters.
  159. Our choice of language features is designed to elicit the fundamental
  160. concepts and algorithms used in compilers.
  161. \begin{itemize}
  162. \item We begin with integer arithmetic and local variables in
  163. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  164. the fundamental tools of compiler construction: \emph{abstract
  165. syntax trees} and \emph{recursive functions}.
  166. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  167. \emph{graph coloring} to assign variables to machine registers.
  168. \item Chapter~\ref{ch:Lif} adds \code{if} expressions, which motivates
  169. an elegant recursive algorithm for translating them into conditional
  170. \code{goto}'s.
  171. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  172. programming languages with the addition of loops\racket{ and mutable
  173. variables}. This elicits the need for \emph{dataflow
  174. analysis} in the register allocator.
  175. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  176. \emph{garbage collection}.
  177. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  178. but lack lexical scoping, similar to the C programming
  179. language~\citep{Kernighan:1988nx} except that we generate efficient
  180. tail calls. The reader learns about the procedure call stack,
  181. \emph{calling conventions}, and their interaction with register
  182. allocation and garbage collection.
  183. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  184. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  185. \emph{closure conversion}, in which lambdas are translated into a
  186. combination of functions and tuples.
  187. % Chapter about classes and objects?
  188. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  189. point the input languages are statically typed. The reader extends
  190. the statically typed language with an \code{Any} type which serves
  191. as a target for compiling the dynamically typed language.
  192. {\if\edition\pythonEd
  193. \item Chapter~\ref{ch:Robject} adds support for \emph{objects} and
  194. \emph{classes}.
  195. \fi}
  196. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  197. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  198. in which different regions of a program may be static or dynamically
  199. typed. The reader implements runtime support for \emph{proxies} that
  200. allow values to safely move between regions.
  201. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  202. leveraging the \code{Any} type and type casts developed in Chapters
  203. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  204. \end{itemize}
  205. There are many language features that we do not include. Our choices
  206. balance the incidental complexity of a feature versus the fundamental
  207. concepts that it exposes. For example, we include tuples and not
  208. records because they both elicit the study of heap allocation and
  209. garbage collection but records come with more incidental complexity.
  210. Since 2009 drafts of this book have served as the textbook for 16-week
  211. compiler courses for upper-level undergraduates and first-year
  212. graduate students at the University of Colorado and Indiana
  213. University.
  214. %
  215. Students come into the course having learned the basics of
  216. programming, data structures and algorithms, and discrete
  217. mathematics.
  218. %
  219. At the beginning of the course, students form groups of 2-4 people.
  220. The groups complete one chapter every two weeks, starting with
  221. Chapter~\ref{ch:Lvar}. Many chapters include a challenge problem that
  222. we assign to the graduate students. The last two weeks of the course
  223. involve a final project in which students design and implement a
  224. compiler extension of their choosing. Chapters~\ref{ch:Rgrad} and
  225. \ref{ch:Rpoly} can be used in support of these projects or they can
  226. replace some of the other chapters. For example, a course with an
  227. emphasis on statically-typed imperative languages could include
  228. Chapter~\ref{ch:Rpoly} but skip Chapter~\ref{ch:Rdyn}. For compiler
  229. courses at universities on the quarter system, with 10 weeks, we
  230. recommend completing up through Chapter~\ref{ch:Rfun}. (If pressed
  231. for time, one can skip Chapter~\ref{ch:Rvec} but still include
  232. Chapter~\ref{ch:Rfun} by limiting the number of parameters allowed in
  233. functions.) Figure~\ref{fig:chapter-dependences} depicts the
  234. dependencies between chapters.
  235. This book has also been used in compiler courses at California
  236. Polytechnic State University, Portland State University, Rose–Hulman
  237. Institute of Technology, University of Massachusetts Lowell, and the
  238. University of Vermont.
  239. \begin{figure}[tp]
  240. {\if\edition\racketEd
  241. \begin{tikzpicture}[baseline=(current bounding box.center)]
  242. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  243. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  244. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  245. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  246. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  247. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  248. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  249. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  250. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  251. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  252. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  253. \path[->] (C1) edge [above] node {} (C2);
  254. \path[->] (C2) edge [above] node {} (C3);
  255. \path[->] (C3) edge [above] node {} (C4);
  256. \path[->] (C4) edge [above] node {} (C5);
  257. \path[->] (C5) edge [above] node {} (C6);
  258. \path[->] (C6) edge [above] node {} (C7);
  259. \path[->] (C4) edge [above] node {} (C8);
  260. \path[->] (C4) edge [above] node {} (C9);
  261. \path[->] (C8) edge [above] node {} (C10);
  262. \path[->] (C10) edge [above] node {} (C11);
  263. \end{tikzpicture}
  264. \fi}
  265. {\if\edition\pythonEd
  266. \begin{tikzpicture}[baseline=(current bounding box.center)]
  267. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  268. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  269. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  270. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  271. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  272. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  273. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  274. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  275. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Robject} Objects};
  276. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  277. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  278. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  279. \path[->] (C1) edge [above] node {} (C2);
  280. \path[->] (C2) edge [above] node {} (C3);
  281. \path[->] (C3) edge [above] node {} (C4);
  282. \path[->] (C4) edge [above] node {} (C5);
  283. \path[->] (C5) edge [above] node {} (C6);
  284. \path[->] (C6) edge [above] node {} (C7);
  285. \path[->] (C4) edge [above] node {} (C8);
  286. \path[->] (C4) edge [above] node {} (C9);
  287. \path[->] (C8) edge [above] node {} (C10);
  288. \path[->] (C8) edge [above] node {} (CO);
  289. \path[->] (C10) edge [above] node {} (C11);
  290. \end{tikzpicture}
  291. \fi}
  292. \caption{Diagram of chapter dependencies.}
  293. \label{fig:chapter-dependences}
  294. \end{figure}
  295. \racket{
  296. We use the \href{https://racket-lang.org/}{Racket} language both for
  297. the implementation of the compiler and for the input language, so the
  298. reader should be proficient with Racket or Scheme. There are many
  299. excellent resources for learning Scheme and
  300. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  301. }
  302. \python{
  303. This edition of the book uses \href{https://www.python.org/}{Python}
  304. both for the implementation of the compiler and for the input language, so the
  305. reader should be proficient with Python. There are many
  306. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  307. }
  308. The support code for this book is in the github repository at
  309. the following URL:
  310. \if\edition\racketEd
  311. \begin{center}\small
  312. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  313. \end{center}
  314. \fi
  315. \if\edition\pythonEd
  316. \begin{center}\small
  317. \url{https://github.com/IUCompilerCourse/}
  318. \end{center}
  319. \fi
  320. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  321. is helpful but not necessary for the reader to have taken a computer
  322. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  323. of x86-64 assembly language that are needed.
  324. %
  325. We follow the System V calling
  326. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  327. that we generate works with the runtime system (written in C) when it
  328. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  329. operating systems on Intel hardware.
  330. %
  331. On the Windows operating system, \code{gcc} uses the Microsoft x64
  332. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  333. assembly code that we generate does \emph{not} work with the runtime
  334. system on Windows. One workaround is to use a virtual machine with
  335. Linux as the guest operating system.
  336. \section*{Acknowledgments}
  337. The tradition of compiler construction at Indiana University goes back
  338. to research and courses on programming languages by Daniel Friedman in
  339. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  340. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  341. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  342. the compiler course and continued the development of Chez Scheme.
  343. %
  344. The compiler course evolved to incorporate novel pedagogical ideas
  345. while also including elements of real-world compilers. One of
  346. Friedman's ideas was to split the compiler into many small
  347. passes. Another idea, called ``the game'', was to test the code
  348. generated by each pass using interpreters.
  349. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  350. developed infrastructure to support this approach and evolved the
  351. course to use even smaller
  352. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  353. design decisions in this book are inspired by the assignment
  354. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  355. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  356. organization of the course made it difficult for students to
  357. understand the rationale for the compiler design. Ghuloum proposed the
  358. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  359. on.
  360. We thank the many students who served as teaching assistants for the
  361. compiler course at IU and made suggestions for improving the book
  362. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  363. thank Andre Kuhlenschmidt for his work on the garbage collector,
  364. Michael Vollmer for his work on efficient tail calls, and Michael
  365. Vitousek for his help running the first offering of the incremental
  366. compiler course at IU.
  367. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  368. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  369. for teaching courses based on drafts of this book and for their
  370. invaluable feedback.
  371. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  372. course in the early 2000's and especially for finding the bug that
  373. sent our garbage collector on a wild goose chase!
  374. \mbox{}\\
  375. \noindent Jeremy G. Siek \\
  376. Bloomington, Indiana
  377. \mainmatter
  378. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  379. \chapter{Preliminaries}
  380. \label{ch:trees-recur}
  381. In this chapter we review the basic tools that are needed to implement
  382. a compiler. Programs are typically input by a programmer as text,
  383. i.e., a sequence of characters. The program-as-text representation is
  384. called \emph{concrete syntax}. We use concrete syntax to concisely
  385. write down and talk about programs. Inside the compiler, we use
  386. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  387. that efficiently supports the operations that the compiler needs to
  388. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  389. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  390. from concrete syntax to abstract syntax is a process called
  391. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  392. implementation of parsing in this book.
  393. %
  394. \racket{A parser is provided in the support code for translating from
  395. concrete to abstract syntax.}
  396. %
  397. \python{We use Python's \code{ast} module to translate from concrete
  398. to abstract syntax.}
  399. ASTs can be represented in many different ways inside the compiler,
  400. depending on the programming language used to write the compiler.
  401. %
  402. \racket{We use Racket's
  403. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  404. feature to represent ASTs (Section~\ref{sec:ast}).}
  405. %
  406. \python{We use Python classes and objects to represent ASTs, especially the
  407. classes defined in the standard \code{ast} module for the Python
  408. source language.}
  409. %
  410. We use grammars to define the abstract syntax of programming languages
  411. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  412. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  413. recursive functions to construct and deconstruct ASTs
  414. (Section~\ref{sec:recursion}). This chapter provides an brief
  415. introduction to these ideas.
  416. \racket{\index{subject}{struct}}
  417. \python{\index{subject}{class}\index{subject}{object}}
  418. \section{Abstract Syntax Trees}
  419. \label{sec:ast}
  420. Compilers use abstract syntax trees to represent programs because they
  421. often need to ask questions like: for a given part of a program, what
  422. kind of language feature is it? What are its sub-parts? Consider the
  423. program on the left and its AST on the right. This program is an
  424. addition operation and it has two sub-parts, a
  425. \racket{read}\python{input} operation and a negation. The negation has
  426. another sub-part, the integer constant \code{8}. By using a tree to
  427. represent the program, we can easily follow the links to go from one
  428. part of a program to its sub-parts.
  429. \begin{center}
  430. \begin{minipage}{0.4\textwidth}
  431. \if\edition\racketEd
  432. \begin{lstlisting}
  433. (+ (read) (- 8))
  434. \end{lstlisting}
  435. \fi
  436. \if\edition\pythonEd
  437. \begin{lstlisting}
  438. input_int() + -8
  439. \end{lstlisting}
  440. \fi
  441. \end{minipage}
  442. \begin{minipage}{0.4\textwidth}
  443. \begin{equation}
  444. \begin{tikzpicture}
  445. \node[draw] (plus) at (0 , 0) {\key{+}};
  446. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  447. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  448. \node[draw] (8) at (1 , -3) {\key{8}};
  449. \draw[->] (plus) to (read);
  450. \draw[->] (plus) to (minus);
  451. \draw[->] (minus) to (8);
  452. \end{tikzpicture}
  453. \label{eq:arith-prog}
  454. \end{equation}
  455. \end{minipage}
  456. \end{center}
  457. We use the standard terminology for trees to describe ASTs: each
  458. rectangle above is called a \emph{node}. The arrows connect a node to its
  459. \emph{children} (which are also nodes). The top-most node is the
  460. \emph{root}. Every node except for the root has a \emph{parent} (the
  461. node it is the child of). If a node has no children, it is a
  462. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  463. \index{subject}{node}
  464. \index{subject}{children}
  465. \index{subject}{root}
  466. \index{subject}{parent}
  467. \index{subject}{leaf}
  468. \index{subject}{internal node}
  469. %% Recall that an \emph{symbolic expression} (S-expression) is either
  470. %% \begin{enumerate}
  471. %% \item an atom, or
  472. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  473. %% where $e_1$ and $e_2$ are each an S-expression.
  474. %% \end{enumerate}
  475. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  476. %% null value \code{'()}, etc. We can create an S-expression in Racket
  477. %% simply by writing a backquote (called a quasi-quote in Racket)
  478. %% followed by the textual representation of the S-expression. It is
  479. %% quite common to use S-expressions to represent a list, such as $a, b
  480. %% ,c$ in the following way:
  481. %% \begin{lstlisting}
  482. %% `(a . (b . (c . ())))
  483. %% \end{lstlisting}
  484. %% Each element of the list is in the first slot of a pair, and the
  485. %% second slot is either the rest of the list or the null value, to mark
  486. %% the end of the list. Such lists are so common that Racket provides
  487. %% special notation for them that removes the need for the periods
  488. %% and so many parenthesis:
  489. %% \begin{lstlisting}
  490. %% `(a b c)
  491. %% \end{lstlisting}
  492. %% The following expression creates an S-expression that represents AST
  493. %% \eqref{eq:arith-prog}.
  494. %% \begin{lstlisting}
  495. %% `(+ (read) (- 8))
  496. %% \end{lstlisting}
  497. %% When using S-expressions to represent ASTs, the convention is to
  498. %% represent each AST node as a list and to put the operation symbol at
  499. %% the front of the list. The rest of the list contains the children. So
  500. %% in the above case, the root AST node has operation \code{`+} and its
  501. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  502. %% diagram \eqref{eq:arith-prog}.
  503. %% To build larger S-expressions one often needs to splice together
  504. %% several smaller S-expressions. Racket provides the comma operator to
  505. %% splice an S-expression into a larger one. For example, instead of
  506. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  507. %% we could have first created an S-expression for AST
  508. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  509. %% S-expression.
  510. %% \begin{lstlisting}
  511. %% (define ast1.4 `(- 8))
  512. %% (define ast1_1 `(+ (read) ,ast1.4))
  513. %% \end{lstlisting}
  514. %% In general, the Racket expression that follows the comma (splice)
  515. %% can be any expression that produces an S-expression.
  516. {\if\edition\racketEd
  517. We define a Racket \code{struct} for each kind of node. For this
  518. chapter we require just two kinds of nodes: one for integer constants
  519. and one for primitive operations. The following is the \code{struct}
  520. definition for integer constants.
  521. \begin{lstlisting}
  522. (struct Int (value))
  523. \end{lstlisting}
  524. An integer node includes just one thing: the integer value.
  525. To create an AST node for the integer $8$, we write \INT{8}.
  526. \begin{lstlisting}
  527. (define eight (Int 8))
  528. \end{lstlisting}
  529. We say that the value created by \INT{8} is an
  530. \emph{instance} of the
  531. \code{Int} structure.
  532. The following is the \code{struct} definition for primitive operations.
  533. \begin{lstlisting}
  534. (struct Prim (op args))
  535. \end{lstlisting}
  536. A primitive operation node includes an operator symbol \code{op} and a
  537. list of child \code{args}. For example, to create an AST that negates
  538. the number $8$, we write \code{(Prim '- (list eight))}.
  539. \begin{lstlisting}
  540. (define neg-eight (Prim '- (list eight)))
  541. \end{lstlisting}
  542. Primitive operations may have zero or more children. The \code{read}
  543. operator has zero children:
  544. \begin{lstlisting}
  545. (define rd (Prim 'read '()))
  546. \end{lstlisting}
  547. whereas the addition operator has two children:
  548. \begin{lstlisting}
  549. (define ast1_1 (Prim '+ (list rd neg-eight)))
  550. \end{lstlisting}
  551. We have made a design choice regarding the \code{Prim} structure.
  552. Instead of using one structure for many different operations
  553. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  554. structure for each operation, as follows.
  555. \begin{lstlisting}
  556. (struct Read ())
  557. (struct Add (left right))
  558. (struct Neg (value))
  559. \end{lstlisting}
  560. The reason we choose to use just one structure is that in many parts
  561. of the compiler the code for the different primitive operators is the
  562. same, so we might as well just write that code once, which is enabled
  563. by using a single structure.
  564. \fi}
  565. {\if\edition\pythonEd
  566. We use a Python \code{class} for each kind of node.
  567. The following is the class definition for constants.
  568. \begin{lstlisting}
  569. class Constant:
  570. def __init__(self, value):
  571. self.value = value
  572. \end{lstlisting}
  573. An integer constant node includes just one thing: the integer value.
  574. To create an AST node for the integer $8$, we write \INT{8}.
  575. \begin{lstlisting}
  576. eight = Constant(8)
  577. \end{lstlisting}
  578. We say that the value created by \INT{8} is an
  579. \emph{instance} of the \code{Constant} class.
  580. The following is the class definition for unary operators.
  581. \begin{lstlisting}
  582. class UnaryOp:
  583. def __init__(self, op, operand):
  584. self.op = op
  585. self.operand = operand
  586. \end{lstlisting}
  587. The specific operation is specified by the \code{op} parameter. For
  588. example, the class \code{USub} is for unary subtraction. (More unary
  589. operators are introduced in later chapters.) To create an AST that
  590. negates the number $8$, we write the following.
  591. \begin{lstlisting}
  592. neg_eight = UnaryOp(USub(), eight)
  593. \end{lstlisting}
  594. The call to the \code{input\_int} function is represented by the
  595. \code{Call} and \code{Name} classes.
  596. \begin{lstlisting}
  597. class Call:
  598. def __init__(self, func, args):
  599. self.func = func
  600. self.args = args
  601. class Name:
  602. def __init__(self, id):
  603. self.id = id
  604. \end{lstlisting}
  605. To create an AST node that calls \code{input\_int}, we write
  606. \begin{lstlisting}
  607. read = Call(Name('input_int'), [])
  608. \end{lstlisting}
  609. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  610. the \code{BinOp} class for binary operators.
  611. \begin{lstlisting}
  612. class BinOp:
  613. def __init__(self, left, op, right):
  614. self.op = op
  615. self.left = left
  616. self.right = right
  617. \end{lstlisting}
  618. Similar to \code{UnaryOp}, the specific operation is specified by the
  619. \code{op} parameter, which for now is just an instance of the
  620. \code{Add} class. So to create the AST node that adds negative eight
  621. to some user input, we write the following.
  622. \begin{lstlisting}
  623. ast1_1 = BinOp(read, Add(), neg_eight)
  624. \end{lstlisting}
  625. \fi}
  626. When compiling a program such as \eqref{eq:arith-prog}, we need to
  627. know that the operation associated with the root node is addition and
  628. we need to be able to access its two children. \racket{Racket}\python{Python}
  629. provides pattern matching to support these kinds of queries, as we see in
  630. Section~\ref{sec:pattern-matching}.
  631. In this book, we often write down the concrete syntax of a program
  632. even when we really have in mind the AST because the concrete syntax
  633. is more concise. We recommend that, in your mind, you always think of
  634. programs as abstract syntax trees.
  635. \section{Grammars}
  636. \label{sec:grammar}
  637. \index{subject}{integer}
  638. \index{subject}{literal}
  639. \index{subject}{constant}
  640. A programming language can be thought of as a \emph{set} of programs.
  641. The set is typically infinite (one can always create larger and larger
  642. programs), so one cannot simply describe a language by listing all of
  643. the programs in the language. Instead we write down a set of rules, a
  644. \emph{grammar}, for building programs. Grammars are often used to
  645. define the concrete syntax of a language, but they can also be used to
  646. describe the abstract syntax. We write our rules in a variant of
  647. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  648. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  649. As an example, we describe a small language, named \LangInt{}, that consists of
  650. integers and arithmetic operations.
  651. \index{subject}{grammar}
  652. The first grammar rule for the abstract syntax of \LangInt{} says that an
  653. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  654. \begin{equation}
  655. \Exp ::= \INT{\Int} \label{eq:arith-int}
  656. \end{equation}
  657. %
  658. Each rule has a left-hand-side and a right-hand-side.
  659. If you have an AST node that matches the
  660. right-hand-side, then you can categorize it according to the
  661. left-hand-side.
  662. %
  663. A name such as $\Exp$ that is defined by the grammar rules is a
  664. \emph{non-terminal}. \index{subject}{non-terminal}
  665. %
  666. The name $\Int$ is also a non-terminal, but instead of defining it
  667. with a grammar rule, we define it with the following explanation. An
  668. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  669. $-$ (for negative integers), such that the sequence of decimals
  670. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  671. the representation of integers using 63 bits, which simplifies several
  672. aspects of compilation. \racket{Thus, these integers corresponds to
  673. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  674. \python{In contrast, integers in Python have unlimited precision, but
  675. the techniques need to handle unlimited precision fall outside the
  676. scope of this book.}
  677. The second grammar rule is the \READOP{} operation that receives an
  678. input integer from the user of the program.
  679. \begin{equation}
  680. \Exp ::= \READ{} \label{eq:arith-read}
  681. \end{equation}
  682. The third rule says that, given an $\Exp$ node, the negation of that
  683. node is also an $\Exp$.
  684. \begin{equation}
  685. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  686. \end{equation}
  687. Symbols in typewriter font are \emph{terminal} symbols and must
  688. literally appear in the program for the rule to be applicable.
  689. \index{subject}{terminal}
  690. We can apply these rules to categorize the ASTs that are in the
  691. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  692. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  693. following AST is an $\Exp$.
  694. \begin{center}
  695. \begin{minipage}{0.5\textwidth}
  696. \NEG{\INT{\code{8}}}
  697. \end{minipage}
  698. \begin{minipage}{0.25\textwidth}
  699. \begin{equation}
  700. \begin{tikzpicture}
  701. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  702. \node[draw, circle] (8) at (0, -1.2) {$8$};
  703. \draw[->] (minus) to (8);
  704. \end{tikzpicture}
  705. \label{eq:arith-neg8}
  706. \end{equation}
  707. \end{minipage}
  708. \end{center}
  709. The next grammar rule is for addition expressions:
  710. \begin{equation}
  711. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  712. \end{equation}
  713. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  714. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  715. \eqref{eq:arith-read} and we have already categorized
  716. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  717. to show that
  718. \[
  719. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  720. \]
  721. is an $\Exp$ in the \LangInt{} language.
  722. If you have an AST for which the above rules do not apply, then the
  723. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  724. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  725. because there are no rules for the \key{-} operator with two
  726. arguments. Whenever we define a language with a grammar, the language
  727. only includes those programs that are justified by the grammar rules.
  728. {\if\edition\pythonEd
  729. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  730. There is a statement for printing the value of an expression
  731. \[
  732. \Stmt{} ::= \PRINT{\Exp}
  733. \]
  734. and a statement that evaluates an expression but ignores the result.
  735. \[
  736. \Stmt{} ::= \EXPR{\Exp}
  737. \]
  738. \fi}
  739. {\if\edition\racketEd
  740. The last grammar rule for \LangInt{} states that there is a
  741. \code{Program} node to mark the top of the whole program:
  742. \[
  743. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  744. \]
  745. The \code{Program} structure is defined as follows
  746. \begin{lstlisting}
  747. (struct Program (info body))
  748. \end{lstlisting}
  749. where \code{body} is an expression. In later chapters, the \code{info}
  750. part will be used to store auxiliary information but for now it is
  751. just the empty list.
  752. \fi}
  753. {\if\edition\pythonEd
  754. The last grammar rule for \LangInt{} states that there is a
  755. \code{Module} node to mark the top of the whole program:
  756. \[
  757. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  758. \]
  759. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  760. this case, a list of statements.
  761. %
  762. The \code{Module} class is defined as follows
  763. \begin{lstlisting}
  764. class Module:
  765. def __init__(self, body):
  766. self.body = body
  767. \end{lstlisting}
  768. where \code{body} is a list of statements.
  769. \fi}
  770. It is common to have many grammar rules with the same left-hand side
  771. but different right-hand sides, such as the rules for $\Exp$ in the
  772. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  773. combine several right-hand-sides into a single rule.
  774. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  775. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  776. defined in Figure~\ref{fig:r0-concrete-syntax}.
  777. \racket{The \code{read-program} function provided in
  778. \code{utilities.rkt} of the support code reads a program in from a
  779. file (the sequence of characters in the concrete syntax of Racket)
  780. and parses it into an abstract syntax tree. See the description of
  781. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  782. details.}
  783. \python{The \code{parse} function in Python's \code{ast} module
  784. converts the concrete syntax (represented as a string) into an
  785. abstract syntax tree.}
  786. \begin{figure}[tp]
  787. \fbox{
  788. \begin{minipage}{0.96\textwidth}
  789. {\if\edition\racketEd
  790. \[
  791. \begin{array}{rcl}
  792. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  793. \LangInt{} &::=& \Exp
  794. \end{array}
  795. \]
  796. \fi}
  797. {\if\edition\pythonEd
  798. \[
  799. \begin{array}{rcl}
  800. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  801. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  802. \LangInt{} &::=& \Stmt^{*}
  803. \end{array}
  804. \]
  805. \fi}
  806. \end{minipage}
  807. }
  808. \caption{The concrete syntax of \LangInt{}.}
  809. \label{fig:r0-concrete-syntax}
  810. \end{figure}
  811. \begin{figure}[tp]
  812. \fbox{
  813. \begin{minipage}{0.96\textwidth}
  814. {\if\edition\racketEd
  815. \[
  816. \begin{array}{rcl}
  817. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  818. &\MID& \ADD{\Exp}{\Exp} \\
  819. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  820. \end{array}
  821. \]
  822. \fi}
  823. {\if\edition\pythonEd
  824. \[
  825. \begin{array}{rcl}
  826. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  827. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  828. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  829. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  830. \end{array}
  831. \]
  832. \fi}
  833. \end{minipage}
  834. }
  835. \caption{The abstract syntax of \LangInt{}.}
  836. \label{fig:r0-syntax}
  837. \end{figure}
  838. \section{Pattern Matching}
  839. \label{sec:pattern-matching}
  840. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  841. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  842. \texttt{match} feature to access the parts of a value.
  843. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  844. \begin{center}
  845. \begin{minipage}{0.5\textwidth}
  846. {\if\edition\racketEd
  847. \begin{lstlisting}
  848. (match ast1_1
  849. [(Prim op (list child1 child2))
  850. (print op)])
  851. \end{lstlisting}
  852. \fi}
  853. {\if\edition\pythonEd
  854. \begin{lstlisting}
  855. match ast1_1:
  856. case BinOp(child1, op, child2):
  857. print(op)
  858. \end{lstlisting}
  859. \fi}
  860. \end{minipage}
  861. \end{center}
  862. {\if\edition\racketEd
  863. %
  864. In the above example, the \texttt{match} form checks whether the AST
  865. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  866. three pattern variables \texttt{op}, \texttt{child1}, and
  867. \texttt{child2}, and then prints out the operator. In general, a match
  868. clause consists of a \emph{pattern} and a
  869. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  870. to be either a pattern variable, a structure name followed by a
  871. pattern for each of the structure's arguments, or an S-expression
  872. (symbols, lists, etc.). (See Chapter 12 of The Racket
  873. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  874. and Chapter 9 of The Racket
  875. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  876. for a complete description of \code{match}.)
  877. %
  878. The body of a match clause may contain arbitrary Racket code. The
  879. pattern variables can be used in the scope of the body, such as
  880. \code{op} in \code{(print op)}.
  881. %
  882. \fi}
  883. %
  884. %
  885. {\if\edition\pythonEd
  886. %
  887. In the above example, the \texttt{match} form checks whether the AST
  888. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  889. three pattern variables \texttt{child1}, \texttt{op}, and
  890. \texttt{child2}, and then prints out the operator. In general, each
  891. \code{case} consists of a \emph{pattern} and a
  892. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  893. to be either a pattern variable, a class name followed by a pattern
  894. for each of its constructor's arguments, or other literals such as
  895. strings, lists, etc.
  896. %
  897. The body of each \code{case} may contain arbitrary Python code. The
  898. pattern variables can be used in the body, such as \code{op} in
  899. \code{print(op)}.
  900. %
  901. \fi}
  902. A \code{match} form may contain several clauses, as in the following
  903. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  904. the AST. The \code{match} proceeds through the clauses in order,
  905. checking whether the pattern can match the input AST. The body of the
  906. first clause that matches is executed. The output of \code{leaf} for
  907. several ASTs is shown on the right.
  908. \begin{center}
  909. \begin{minipage}{0.6\textwidth}
  910. {\if\edition\racketEd
  911. \begin{lstlisting}
  912. (define (leaf arith)
  913. (match arith
  914. [(Int n) #t]
  915. [(Prim 'read '()) #t]
  916. [(Prim '- (list e1)) #f]
  917. [(Prim '+ (list e1 e2)) #f]))
  918. (leaf (Prim 'read '()))
  919. (leaf (Prim '- (list (Int 8))))
  920. (leaf (Int 8))
  921. \end{lstlisting}
  922. \fi}
  923. {\if\edition\pythonEd
  924. \begin{lstlisting}
  925. def leaf(arith):
  926. match arith:
  927. case Constant(n):
  928. return True
  929. case Call(Name('input_int'), []):
  930. return True
  931. case UnaryOp(USub(), e1):
  932. return False
  933. case BinOp(e1, Add(), e2):
  934. return False
  935. print(leaf(Call(Name('input_int'), [])))
  936. print(leaf(UnaryOp(USub(), eight)))
  937. print(leaf(Constant(8)))
  938. \end{lstlisting}
  939. \fi}
  940. \end{minipage}
  941. \vrule
  942. \begin{minipage}{0.25\textwidth}
  943. {\if\edition\racketEd
  944. \begin{lstlisting}
  945. #t
  946. #f
  947. #t
  948. \end{lstlisting}
  949. \fi}
  950. {\if\edition\pythonEd
  951. \begin{lstlisting}
  952. True
  953. False
  954. True
  955. \end{lstlisting}
  956. \fi}
  957. \end{minipage}
  958. \end{center}
  959. When writing a \code{match}, we refer to the grammar definition to
  960. identify which non-terminal we are expecting to match against, then we
  961. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  962. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  963. corresponding right-hand side of a grammar rule. For the \code{match}
  964. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  965. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  966. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  967. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  968. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  969. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  970. patterns, replace non-terminals such as $\Exp$ with pattern variables
  971. of your choice (e.g. \code{e1} and \code{e2}).
  972. \section{Recursive Functions}
  973. \label{sec:recursion}
  974. \index{subject}{recursive function}
  975. Programs are inherently recursive. For example, an expression is often
  976. made of smaller expressions. Thus, the natural way to process an
  977. entire program is with a recursive function. As a first example of
  978. such a recursive function, we define the function \code{exp} in
  979. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  980. determines whether or not it is an expression in \LangInt{}.
  981. %
  982. We say that a function is defined by \emph{structural recursion} when
  983. it is defined using a sequence of match \racket{clauses}\python{cases}
  984. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  985. makes a recursive call on each
  986. child node.\footnote{This principle of structuring code according to
  987. the data definition is advocated in the book \emph{How to Design
  988. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  989. \python{We define a second function, named \code{stmt}, that recognizes
  990. whether a value is a \LangInt{} statement.}
  991. \python{Finally, }
  992. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Lint}, which
  993. determines whether an AST is a program in \LangInt{}. In general we can
  994. expect to write one recursive function to handle each non-terminal in
  995. a grammar.\index{subject}{structural recursion}
  996. \begin{figure}[tp]
  997. {\if\edition\racketEd
  998. \begin{minipage}{0.7\textwidth}
  999. \begin{lstlisting}
  1000. (define (exp ast)
  1001. (match ast
  1002. [(Int n) #t]
  1003. [(Prim 'read '()) #t]
  1004. [(Prim '- (list e)) (exp e)]
  1005. [(Prim '+ (list e1 e2))
  1006. (and (exp e1) (exp e2))]
  1007. [else #f]))
  1008. (define (Lint ast)
  1009. (match ast
  1010. [(Program '() e) (exp e)]
  1011. [else #f]))
  1012. (Lint (Program '() ast1_1)
  1013. (Lint (Program '()
  1014. (Prim '- (list (Prim 'read '())
  1015. (Prim '+ (list (Num 8)))))))
  1016. \end{lstlisting}
  1017. \end{minipage}
  1018. \vrule
  1019. \begin{minipage}{0.25\textwidth}
  1020. \begin{lstlisting}
  1021. #t
  1022. #f
  1023. \end{lstlisting}
  1024. \end{minipage}
  1025. \fi}
  1026. {\if\edition\pythonEd
  1027. \begin{minipage}{0.7\textwidth}
  1028. \begin{lstlisting}
  1029. def exp(e):
  1030. match e:
  1031. case Constant(n):
  1032. return True
  1033. case Call(Name('input_int'), []):
  1034. return True
  1035. case UnaryOp(USub(), e1):
  1036. return exp(e1)
  1037. case BinOp(e1, Add(), e2):
  1038. return exp(e1) and exp(e2)
  1039. case _:
  1040. return False
  1041. def stmt(s):
  1042. match s:
  1043. case Call(Name('print'), [e]):
  1044. return exp(e)
  1045. case Expr(e):
  1046. return exp(e)
  1047. case _:
  1048. return False
  1049. def Lint(p):
  1050. match p:
  1051. case Module(body):
  1052. return all([stmt(s) for s in body])
  1053. case _:
  1054. return False
  1055. print(Lint(Module([Expr(ast1_1)])))
  1056. print(Lint(Module([Expr(BinOp(read, Sub(),
  1057. UnaryOp(Add(), Constant(8))))])))
  1058. \end{lstlisting}
  1059. \end{minipage}
  1060. \vrule
  1061. \begin{minipage}{0.25\textwidth}
  1062. \begin{lstlisting}
  1063. True
  1064. False
  1065. \end{lstlisting}
  1066. \end{minipage}
  1067. \fi}
  1068. \caption{Example of recursive functions for \LangInt{}. These functions
  1069. recognize whether an AST is in \LangInt{}.}
  1070. \label{fig:exp-predicate}
  1071. \end{figure}
  1072. %% You may be tempted to merge the two functions into one, like this:
  1073. %% \begin{center}
  1074. %% \begin{minipage}{0.5\textwidth}
  1075. %% \begin{lstlisting}
  1076. %% (define (Lint ast)
  1077. %% (match ast
  1078. %% [(Int n) #t]
  1079. %% [(Prim 'read '()) #t]
  1080. %% [(Prim '- (list e)) (Lint e)]
  1081. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1082. %% [(Program '() e) (Lint e)]
  1083. %% [else #f]))
  1084. %% \end{lstlisting}
  1085. %% \end{minipage}
  1086. %% \end{center}
  1087. %% %
  1088. %% Sometimes such a trick will save a few lines of code, especially when
  1089. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1090. %% \emph{not} recommended because it can get you into trouble.
  1091. %% %
  1092. %% For example, the above function is subtly wrong:
  1093. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1094. %% returns true when it should return false.
  1095. \section{Interpreters}
  1096. \label{sec:interp_Lint}
  1097. \index{subject}{interpreter}
  1098. The behavior of a program is defined by the specification of the
  1099. programming language.
  1100. %
  1101. \racket{For example, the Scheme language is defined in the report by
  1102. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1103. reference manual~\citep{plt-tr}.}
  1104. %
  1105. \python{For example, the Python language is defined in the Python
  1106. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1107. %
  1108. In this book we use interpreters
  1109. to specify each language that we consider. An interpreter that is
  1110. designated as the definition of a language is called a
  1111. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1112. \index{subject}{definitional interpreter} We warm up by creating a
  1113. definitional interpreter for the \LangInt{} language, which serves as
  1114. a second example of structural recursion. The \code{interp\_Lint}
  1115. function is defined in Figure~\ref{fig:interp_Lint}.
  1116. %
  1117. \racket{The body of the function is a match on the input program
  1118. followed by a call to the \lstinline{interp_exp} helper function,
  1119. which in turn has one match clause per grammar rule for \LangInt{}
  1120. expressions.}
  1121. %
  1122. \python{The body of the function matches on the \code{Module} AST node
  1123. and then invokes \code{interp\_stmt} on each statement in the
  1124. module. The \code{interp\_stmt} function includes a case for each
  1125. grammar rule of the \Stmt{} non-terminal and it calls
  1126. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1127. function includes a case for each grammar rule of the \Exp{}
  1128. non-terminal.}
  1129. \begin{figure}[tp]
  1130. {\if\edition\racketEd
  1131. \begin{lstlisting}
  1132. (define (interp_exp e)
  1133. (match e
  1134. [(Int n) n]
  1135. [(Prim 'read '())
  1136. (define r (read))
  1137. (cond [(fixnum? r) r]
  1138. [else (error 'interp_exp "read expected an integer" r)])]
  1139. [(Prim '- (list e))
  1140. (define v (interp_exp e))
  1141. (fx- 0 v)]
  1142. [(Prim '+ (list e1 e2))
  1143. (define v1 (interp_exp e1))
  1144. (define v2 (interp_exp e2))
  1145. (fx+ v1 v2)]))
  1146. (define (interp_Lint p)
  1147. (match p
  1148. [(Program '() e) (interp_exp e)]))
  1149. \end{lstlisting}
  1150. \fi}
  1151. {\if\edition\pythonEd
  1152. \begin{lstlisting}
  1153. def interp_exp(e):
  1154. match e:
  1155. case BinOp(left, Add(), right):
  1156. l = interp_exp(left)
  1157. r = interp_exp(right)
  1158. return l + r
  1159. case UnaryOp(USub(), v):
  1160. return - interp_exp(v)
  1161. case Constant(value):
  1162. return value
  1163. case Call(Name('input_int'), []):
  1164. return int(input())
  1165. def interp_stmt(s):
  1166. match s:
  1167. case Expr(Call(Name('print'), [arg])):
  1168. print(interp_exp(arg))
  1169. case Expr(value):
  1170. interp_exp(value)
  1171. def interp_Lint(p):
  1172. match p:
  1173. case Module(body):
  1174. for s in body:
  1175. interp_stmt(s)
  1176. \end{lstlisting}
  1177. \fi}
  1178. \caption{Interpreter for the \LangInt{} language.}
  1179. \label{fig:interp_Lint}
  1180. \end{figure}
  1181. Let us consider the result of interpreting a few \LangInt{} programs. The
  1182. following program adds two integers.
  1183. {\if\edition\racketEd
  1184. \begin{lstlisting}
  1185. (+ 10 32)
  1186. \end{lstlisting}
  1187. \fi}
  1188. {\if\edition\pythonEd
  1189. \begin{lstlisting}
  1190. print(10 + 32)
  1191. \end{lstlisting}
  1192. \fi}
  1193. The result is \key{42}, the answer to life, the universe, and
  1194. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1195. Galaxy} by Douglas Adams.}.
  1196. %
  1197. We wrote the above program in concrete syntax whereas the parsed
  1198. abstract syntax is:
  1199. {\if\edition\racketEd
  1200. \begin{lstlisting}
  1201. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1202. \end{lstlisting}
  1203. \fi}
  1204. {\if\edition\pythonEd
  1205. \begin{lstlisting}
  1206. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1207. \end{lstlisting}
  1208. \fi}
  1209. The next example demonstrates that expressions may be nested within
  1210. each other, in this case nesting several additions and negations.
  1211. {\if\edition\racketEd
  1212. \begin{lstlisting}
  1213. (+ 10 (- (+ 12 20)))
  1214. \end{lstlisting}
  1215. \fi}
  1216. {\if\edition\pythonEd
  1217. \begin{lstlisting}
  1218. print(10 + -(12 + 20))
  1219. \end{lstlisting}
  1220. \fi}
  1221. %
  1222. \noindent What is the result of the above program?
  1223. {\if\edition\racketEd
  1224. As mentioned previously, the \LangInt{} language does not support
  1225. arbitrarily-large integers, but only $63$-bit integers, so we
  1226. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1227. in Racket.
  1228. Suppose
  1229. \[
  1230. n = 999999999999999999
  1231. \]
  1232. which indeed fits in $63$-bits. What happens when we run the
  1233. following program in our interpreter?
  1234. \begin{lstlisting}
  1235. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1236. \end{lstlisting}
  1237. It produces an error:
  1238. \begin{lstlisting}
  1239. fx+: result is not a fixnum
  1240. \end{lstlisting}
  1241. We establish the convention that if running the definitional
  1242. interpreter on a program produces an error then the meaning of that
  1243. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1244. error is a \code{trapped-error}. A compiler for the language is under
  1245. no obligations regarding programs with unspecified behavior; it does
  1246. not have to produce an executable, and if it does, that executable can
  1247. do anything. On the other hand, if the error is a
  1248. \code{trapped-error}, then the compiler must produce an executable and
  1249. it is required to report that an error occurred. To signal an error,
  1250. exit with a return code of \code{255}. The interpreters in chapters
  1251. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1252. \code{trapped-error}.
  1253. \fi}
  1254. % TODO: how to deal with too-large integers in the Python interpreter?
  1255. %% This convention applies to the languages defined in this
  1256. %% book, as a way to simplify the student's task of implementing them,
  1257. %% but this convention is not applicable to all programming languages.
  1258. %%
  1259. Moving on to the last feature of the \LangInt{} language, the
  1260. \READOP{} operation prompts the user of the program for an integer.
  1261. Recall that program \eqref{eq:arith-prog} requests an integer input
  1262. and then subtracts \code{8}. So if we run
  1263. {\if\edition\racketEd
  1264. \begin{lstlisting}
  1265. (interp_Lint (Program '() ast1_1))
  1266. \end{lstlisting}
  1267. \fi}
  1268. {\if\edition\pythonEd
  1269. \begin{lstlisting}
  1270. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1271. \end{lstlisting}
  1272. \fi}
  1273. \noindent and if the input is \code{50}, the result is \code{42}.
  1274. We include the \READOP{} operation in \LangInt{} so a clever student
  1275. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1276. during compilation to obtain the output and then generates the trivial
  1277. code to produce the output.\footnote{Yes, a clever student did this in the
  1278. first instance of this course!}
  1279. The job of a compiler is to translate a program in one language into a
  1280. program in another language so that the output program behaves the
  1281. same way as the input program. This idea is depicted in the
  1282. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1283. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1284. Given a compiler that translates from language $\mathcal{L}_1$ to
  1285. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1286. compiler must translate it into some program $P_2$ such that
  1287. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1288. same input $i$ yields the same output $o$.
  1289. \begin{equation} \label{eq:compile-correct}
  1290. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1291. \node (p1) at (0, 0) {$P_1$};
  1292. \node (p2) at (3, 0) {$P_2$};
  1293. \node (o) at (3, -2.5) {$o$};
  1294. \path[->] (p1) edge [above] node {compile} (p2);
  1295. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1296. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1297. \end{tikzpicture}
  1298. \end{equation}
  1299. In the next section we see our first example of a compiler.
  1300. \section{Example Compiler: a Partial Evaluator}
  1301. \label{sec:partial-evaluation}
  1302. In this section we consider a compiler that translates \LangInt{}
  1303. programs into \LangInt{} programs that may be more efficient. The
  1304. compiler eagerly computes the parts of the program that do not depend
  1305. on any inputs, a process known as \emph{partial
  1306. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1307. For example, given the following program
  1308. {\if\edition\racketEd
  1309. \begin{lstlisting}
  1310. (+ (read) (- (+ 5 3)))
  1311. \end{lstlisting}
  1312. \fi}
  1313. {\if\edition\pythonEd
  1314. \begin{lstlisting}
  1315. print(input_int() + -(5 + 3) )
  1316. \end{lstlisting}
  1317. \fi}
  1318. \noindent our compiler translates it into the program
  1319. {\if\edition\racketEd
  1320. \begin{lstlisting}
  1321. (+ (read) -8)
  1322. \end{lstlisting}
  1323. \fi}
  1324. {\if\edition\pythonEd
  1325. \begin{lstlisting}
  1326. print(input_int() + -8)
  1327. \end{lstlisting}
  1328. \fi}
  1329. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1330. evaluator for the \LangInt{} language. The output of the partial evaluator
  1331. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1332. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1333. whereas the code for partially evaluating the negation and addition
  1334. operations is factored into two auxiliary functions:
  1335. \code{pe\_neg} and \code{pe\_add}. The input to these
  1336. functions is the output of partially evaluating the children.
  1337. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1338. arguments are integers and if they are, perform the appropriate
  1339. arithmetic. Otherwise, they create an AST node for the arithmetic
  1340. operation.
  1341. \begin{figure}[tp]
  1342. {\if\edition\racketEd
  1343. \begin{lstlisting}
  1344. (define (pe_neg r)
  1345. (match r
  1346. [(Int n) (Int (fx- 0 n))]
  1347. [else (Prim '- (list r))]))
  1348. (define (pe_add r1 r2)
  1349. (match* (r1 r2)
  1350. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1351. [(_ _) (Prim '+ (list r1 r2))]))
  1352. (define (pe_exp e)
  1353. (match e
  1354. [(Int n) (Int n)]
  1355. [(Prim 'read '()) (Prim 'read '())]
  1356. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1357. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1358. (define (pe_Lint p)
  1359. (match p
  1360. [(Program '() e) (Program '() (pe_exp e))]))
  1361. \end{lstlisting}
  1362. \fi}
  1363. {\if\edition\pythonEd
  1364. \begin{lstlisting}
  1365. def pe_neg(r):
  1366. match r:
  1367. case Constant(n):
  1368. return Constant(-n)
  1369. case _:
  1370. return UnaryOp(USub(), r)
  1371. def pe_add(r1, r2):
  1372. match (r1, r2):
  1373. case (Constant(n1), Constant(n2)):
  1374. return Constant(n1 + n2)
  1375. case _:
  1376. return BinOp(r1, Add(), r2)
  1377. def pe_exp(e):
  1378. match e:
  1379. case BinOp(left, Add(), right):
  1380. return pe_add(pe_exp(left), pe_exp(right))
  1381. case UnaryOp(USub(), v):
  1382. return pe_neg(pe_exp(v))
  1383. case Constant(value):
  1384. return e
  1385. case Call(Name('input_int'), []):
  1386. return e
  1387. def pe_stmt(s):
  1388. match s:
  1389. case Expr(Call(Name('print'), [arg])):
  1390. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1391. case Expr(value):
  1392. return Expr(pe_exp(value))
  1393. def pe_P_int(p):
  1394. match p:
  1395. case Module(body):
  1396. new_body = [pe_stmt(s) for s in body]
  1397. return Module(new_body)
  1398. \end{lstlisting}
  1399. \fi}
  1400. \caption{A partial evaluator for \LangInt{}.}
  1401. \label{fig:pe-arith}
  1402. \end{figure}
  1403. To gain some confidence that the partial evaluator is correct, we can
  1404. test whether it produces programs that get the same result as the
  1405. input programs. That is, we can test whether it satisfies Diagram
  1406. \ref{eq:compile-correct}.
  1407. %
  1408. {\if\edition\racketEd
  1409. The following code runs the partial evaluator on several examples and
  1410. tests the output program. The \texttt{parse-program} and
  1411. \texttt{assert} functions are defined in
  1412. Appendix~\ref{appendix:utilities}.\\
  1413. \begin{minipage}{1.0\textwidth}
  1414. \begin{lstlisting}
  1415. (define (test_pe p)
  1416. (assert "testing pe_Lint"
  1417. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1418. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1419. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1420. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1421. \end{lstlisting}
  1422. \end{minipage}
  1423. \fi}
  1424. % TODO: python version of testing the PE
  1425. \begin{exercise}\normalfont
  1426. Create three programs in the \LangInt{} language and test whether
  1427. partially evaluating them with \code{pe\_Lint} and then
  1428. interpreting them with \code{interp\_Lint} gives the same result
  1429. as directly interpreting them with \code{interp\_Lint}.
  1430. \end{exercise}
  1431. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1432. \chapter{Integers and Variables}
  1433. \label{ch:Lvar}
  1434. This chapter is about compiling a subset of
  1435. \racket{Racket}\python{Python} to x86-64 assembly
  1436. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1437. integer arithmetic and local variables. We often refer to x86-64
  1438. simply as x86. The chapter begins with a description of the
  1439. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1440. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1441. large so we discuss only the instructions needed for compiling
  1442. \LangVar{}. We introduce more x86 instructions in later chapters.
  1443. After introducing \LangVar{} and x86, we reflect on their differences
  1444. and come up with a plan to break down the translation from \LangVar{}
  1445. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1446. rest of the sections in this chapter give detailed hints regarding
  1447. each step. We hope to give enough hints that the well-prepared
  1448. reader, together with a few friends, can implement a compiler from
  1449. \LangVar{} to x86 in a couple weeks. To give the reader a feeling for
  1450. the scale of this first compiler, the instructor solution for the
  1451. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1452. code.
  1453. \section{The \LangVar{} Language}
  1454. \label{sec:s0}
  1455. \index{subject}{variable}
  1456. The \LangVar{} language extends the \LangInt{} language with
  1457. variables. The concrete syntax of the \LangVar{} language is defined
  1458. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1459. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1460. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1461. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1462. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1463. syntax of \LangVar{} includes the \racket{\key{Program}
  1464. struct}\python{\key{Module} instance} to mark the top of the
  1465. program.
  1466. %% The $\itm{info}$
  1467. %% field of the \key{Program} structure contains an \emph{association
  1468. %% list} (a list of key-value pairs) that is used to communicate
  1469. %% auxiliary data from one compiler pass the next.
  1470. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1471. exhibit several compilation techniques.
  1472. \begin{figure}[tp]
  1473. \centering
  1474. \fbox{
  1475. \begin{minipage}{0.96\textwidth}
  1476. {\if\edition\racketEd
  1477. \[
  1478. \begin{array}{rcl}
  1479. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1480. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1481. \LangVarM{} &::=& \Exp
  1482. \end{array}
  1483. \]
  1484. \fi}
  1485. {\if\edition\pythonEd
  1486. \[
  1487. \begin{array}{rcl}
  1488. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1489. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1490. \LangVarM{} &::=& \Stmt^{*}
  1491. \end{array}
  1492. \]
  1493. \fi}
  1494. \end{minipage}
  1495. }
  1496. \caption{The concrete syntax of \LangVar{}.}
  1497. \label{fig:Lvar-concrete-syntax}
  1498. \end{figure}
  1499. \begin{figure}[tp]
  1500. \centering
  1501. \fbox{
  1502. \begin{minipage}{0.96\textwidth}
  1503. {\if\edition\racketEd
  1504. \[
  1505. \begin{array}{rcl}
  1506. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1507. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1508. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1509. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1510. \end{array}
  1511. \]
  1512. \fi}
  1513. {\if\edition\pythonEd
  1514. \[
  1515. \begin{array}{rcl}
  1516. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1517. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1518. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1519. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1520. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1521. \end{array}
  1522. \]
  1523. \fi}
  1524. \end{minipage}
  1525. }
  1526. \caption{The abstract syntax of \LangVar{}.}
  1527. \label{fig:Lvar-syntax}
  1528. \end{figure}
  1529. {\if\edition\racketEd
  1530. Let us dive further into the syntax and semantics of the \LangVar{}
  1531. language. The \key{let} feature defines a variable for use within its
  1532. body and initializes the variable with the value of an expression.
  1533. The abstract syntax for \key{let} is defined in
  1534. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1535. \begin{lstlisting}
  1536. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1537. \end{lstlisting}
  1538. For example, the following program initializes \code{x} to $32$ and then
  1539. evaluates the body \code{(+ 10 x)}, producing $42$.
  1540. \begin{lstlisting}
  1541. (let ([x (+ 12 20)]) (+ 10 x))
  1542. \end{lstlisting}
  1543. \fi}
  1544. %
  1545. {\if\edition\pythonEd
  1546. %
  1547. The \LangVar{} language includes assignment statements, which define a
  1548. variable for use in later statements and initializes the variable with
  1549. the value of an expression. The abstract syntax for assignment is
  1550. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1551. assignment is
  1552. \begin{lstlisting}
  1553. |$\itm{var}$| = |$\itm{exp}$|
  1554. \end{lstlisting}
  1555. For example, the following program initializes the variable \code{x}
  1556. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1557. \begin{lstlisting}
  1558. x = 12 + 20
  1559. print(10 + x)
  1560. \end{lstlisting}
  1561. \fi}
  1562. {\if\edition\racketEd
  1563. %
  1564. When there are multiple \key{let}'s for the same variable, the closest
  1565. enclosing \key{let} is used. That is, variable definitions overshadow
  1566. prior definitions. Consider the following program with two \key{let}'s
  1567. that define variables named \code{x}. Can you figure out the result?
  1568. \begin{lstlisting}
  1569. (let ([x 32]) (+ (let ([x 10]) x) x))
  1570. \end{lstlisting}
  1571. For the purposes of depicting which variable uses correspond to which
  1572. definitions, the following shows the \code{x}'s annotated with
  1573. subscripts to distinguish them. Double check that your answer for the
  1574. above is the same as your answer for this annotated version of the
  1575. program.
  1576. \begin{lstlisting}
  1577. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1578. \end{lstlisting}
  1579. The initializing expression is always evaluated before the body of the
  1580. \key{let}, so in the following, the \key{read} for \code{x} is
  1581. performed before the \key{read} for \code{y}. Given the input
  1582. $52$ then $10$, the following produces $42$ (not $-42$).
  1583. \begin{lstlisting}
  1584. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1585. \end{lstlisting}
  1586. \fi}
  1587. \subsection{Extensible Interpreters via Method Overriding}
  1588. \label{sec:extensible-interp}
  1589. To prepare for discussing the interpreter for \LangVar{}, we
  1590. explain why we to implement the interpreter using
  1591. object-oriented programming, that is, as a collection of methods
  1592. inside of a class. Throughout this book we define many interpreters,
  1593. one for each of the languages that we study. Because each language
  1594. builds on the prior one, there is a lot of commonality between these
  1595. interpreters. We want to write down the common parts just once
  1596. instead of many times. A naive approach would be to have, for example,
  1597. the interpreter for \LangIf{} handle all of the new features in that
  1598. language and then have a default case that dispatches to the
  1599. interpreter for \LangVar{}. The following code sketches this idea.
  1600. \begin{center}
  1601. {\if\edition\racketEd
  1602. \begin{minipage}{0.45\textwidth}
  1603. \begin{lstlisting}
  1604. (define (interp_Lvar_exp e)
  1605. (match e
  1606. [(Prim '- (list e1))
  1607. (fx- 0 (interp_Lvar_exp e1))]
  1608. ...))
  1609. \end{lstlisting}
  1610. \end{minipage}
  1611. \begin{minipage}{0.45\textwidth}
  1612. \begin{lstlisting}
  1613. (define (interp_Lif_exp e)
  1614. (match e
  1615. [(If cnd thn els)
  1616. (match (interp_Lif_exp cnd)
  1617. [#t (interp_Lif_exp thn)]
  1618. [#f (interp_Lif_exp els)])]
  1619. ...
  1620. [else (interp_Lvar_exp e)]))
  1621. \end{lstlisting}
  1622. \end{minipage}
  1623. \fi}
  1624. {\if\edition\pythonEd
  1625. \begin{minipage}{0.45\textwidth}
  1626. \begin{lstlisting}
  1627. def interp_Lvar_exp(e):
  1628. match e:
  1629. case UnaryOp(USub(), e1):
  1630. return - interp_Lvar_exp(e1)
  1631. ...
  1632. \end{lstlisting}
  1633. \end{minipage}
  1634. \begin{minipage}{0.45\textwidth}
  1635. \begin{lstlisting}
  1636. def interp_Lif_exp(e):
  1637. match e:
  1638. case IfExp(cnd, thn, els):
  1639. match interp_Lif_exp(cnd):
  1640. case True:
  1641. return interp_Lif_exp(thn)
  1642. case False:
  1643. return interp_Lif_exp(els)
  1644. ...
  1645. case _:
  1646. return interp_Lvar_exp(e)
  1647. \end{lstlisting}
  1648. \end{minipage}
  1649. \fi}
  1650. \end{center}
  1651. The problem with this approach is that it does not handle situations
  1652. in which an \LangIf{} feature, such as a conditional expression, is
  1653. nested inside an \LangVar{} feature, like the \code{-} operator, as in
  1654. the following program.
  1655. {\if\edition\racketEd
  1656. \begin{lstlisting}
  1657. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1658. \end{lstlisting}
  1659. \fi}
  1660. {\if\edition\pythonEd
  1661. \begin{lstlisting}
  1662. print(-(42 if True else 0))
  1663. \end{lstlisting}
  1664. \fi}
  1665. %
  1666. If we invoke \code{interp\_Lif\_exp} on this program, it dispatches to
  1667. \code{interp\_Lvar\_exp} to handle the \code{-} operator, but then it
  1668. recursively calls \code{interp\_Lvar\_exp} again on the argument of
  1669. \code{-}, which is an \code{If}. But there is no case for \code{If}
  1670. in \code{interp\_Lvar\_exp} so we get an error!
  1671. To make our interpreters extensible we need something called
  1672. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1673. recursive knot is delayed to when the functions are
  1674. composed. Object-oriented languages provide open recursion via
  1675. method overriding\index{subject}{method overriding}. The
  1676. following code uses method overriding to interpret \LangVar{} and
  1677. \LangIf{} using
  1678. %
  1679. \racket{the
  1680. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1681. \index{subject}{class} feature of Racket}
  1682. %
  1683. \python{a Python \code{class} definition}.
  1684. %
  1685. We define one class for each language and define a method for
  1686. interpreting expressions inside each class. The class for \LangIf{}
  1687. inherits from the class for \LangVar{} and the method
  1688. \code{interp\_exp} in \LangIf{} overrides the \code{interp\_exp} in
  1689. \LangVar{}. Note that the default case of \code{interp\_exp} in
  1690. \LangIf{} uses \code{super} to invoke \code{interp\_exp}, and because
  1691. \LangIf{} inherits from \LangVar{}, that dispatches to the
  1692. \code{interp\_exp} in \LangVar{}.
  1693. \begin{center}
  1694. {\if\edition\racketEd
  1695. \begin{minipage}{0.45\textwidth}
  1696. \begin{lstlisting}
  1697. (define interp_Lvar_class
  1698. (class object%
  1699. (define/public (interp_exp e)
  1700. (match e
  1701. [(Prim '- (list e))
  1702. (fx- 0 (interp_exp e))]
  1703. ...))
  1704. ...))
  1705. \end{lstlisting}
  1706. \end{minipage}
  1707. \begin{minipage}{0.45\textwidth}
  1708. \begin{lstlisting}
  1709. (define interp_Lif_class
  1710. (class interp_Lvar_class
  1711. (define/override (interp_exp e)
  1712. (match e
  1713. [(If cnd thn els)
  1714. (match (interp_exp cnd)
  1715. [#t (interp_exp thn)]
  1716. [#f (interp_exp els)])]
  1717. ...
  1718. [else (super interp_exp e)]))
  1719. ...
  1720. ))
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. \fi}
  1724. {\if\edition\pythonEd
  1725. \begin{minipage}{0.45\textwidth}
  1726. \begin{lstlisting}
  1727. class InterpLvar:
  1728. def interp_exp(e):
  1729. match e:
  1730. case UnaryOp(USub(), e1):
  1731. return -self.interp_exp(e1)
  1732. ...
  1733. ...
  1734. \end{lstlisting}
  1735. \end{minipage}
  1736. \begin{minipage}{0.45\textwidth}
  1737. \begin{lstlisting}
  1738. def InterpLif(InterpRVar):
  1739. def interp_exp(e):
  1740. match e:
  1741. case IfExp(cnd, thn, els):
  1742. match self.interp_exp(cnd):
  1743. case True:
  1744. return self.interp_exp(thn)
  1745. case False:
  1746. return self.interp_exp(els)
  1747. ...
  1748. case _:
  1749. return super().interp_exp(e)
  1750. ...
  1751. \end{lstlisting}
  1752. \end{minipage}
  1753. \fi}
  1754. \end{center}
  1755. Getting back to the troublesome example, repeated here:
  1756. {\if\edition\racketEd
  1757. \begin{lstlisting}
  1758. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1759. \end{lstlisting}
  1760. \fi}
  1761. {\if\edition\pythonEd
  1762. \begin{lstlisting}
  1763. -(42 if True else 0)
  1764. \end{lstlisting}
  1765. \fi}
  1766. \noindent We can invoke the \code{interp\_exp} method for \LangIf{} on this
  1767. expression, call it \code{e0}, by creating an object of the \LangIf{} class
  1768. and calling the \code{interp\_exp} method.
  1769. {\if\edition\racketEd
  1770. \begin{lstlisting}
  1771. (send (new interp_Lif_class) interp_exp e0)
  1772. \end{lstlisting}
  1773. \fi}
  1774. {\if\edition\pythonEd
  1775. \begin{lstlisting}
  1776. InterpLif().interp_exp(e0)
  1777. \end{lstlisting}
  1778. \fi}
  1779. \noindent The default case of \code{interp\_exp} in \LangIf{} handles it by
  1780. dispatching to the \code{interp\_exp} method in \LangVar{}, which
  1781. handles the \code{-} operator. But then for the recursive method call,
  1782. it dispatches back to \code{interp\_exp} in \LangIf{}, where the
  1783. \code{If} is handled correctly. Thus, method overriding gives us the
  1784. open recursion that we need to implement our interpreters in an
  1785. extensible way.
  1786. \subsection{Definitional Interpreter for \LangVar{}}
  1787. {\if\edition\racketEd
  1788. \begin{figure}[tp]
  1789. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1790. \small
  1791. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1792. An \emph{association list} (alist) is a list of key-value pairs.
  1793. For example, we can map people to their ages with an alist.
  1794. \index{subject}{alist}\index{subject}{association list}
  1795. \begin{lstlisting}[basicstyle=\ttfamily]
  1796. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1797. \end{lstlisting}
  1798. The \emph{dictionary} interface is for mapping keys to values.
  1799. Every alist implements this interface. \index{subject}{dictionary} The package
  1800. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1801. provides many functions for working with dictionaries. Here
  1802. are a few of them:
  1803. \begin{description}
  1804. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1805. returns the value associated with the given $\itm{key}$.
  1806. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1807. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1808. but otherwise is the same as $\itm{dict}$.
  1809. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1810. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1811. of keys and values in $\itm{dict}$. For example, the following
  1812. creates a new alist in which the ages are incremented.
  1813. \end{description}
  1814. \vspace{-10pt}
  1815. \begin{lstlisting}[basicstyle=\ttfamily]
  1816. (for/list ([(k v) (in-dict ages)])
  1817. (cons k (add1 v)))
  1818. \end{lstlisting}
  1819. \end{tcolorbox}
  1820. %\end{wrapfigure}
  1821. \caption{Association lists implement the dictionary interface.}
  1822. \label{fig:alist}
  1823. \end{figure}
  1824. \fi}
  1825. Having justified the use of classes and methods to implement
  1826. interpreters, we turn to the definitional interpreter for \LangVar{}
  1827. in Figure~\ref{fig:interp-Lvar}. It is similar to the interpreter for
  1828. \LangInt{} but adds two new \key{match} cases for variables and
  1829. \racket{\key{let}}\python{assignment}. For
  1830. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1831. value bound to a variable to all the uses of the variable. To
  1832. accomplish this, we maintain a mapping from variables to
  1833. values. Throughout the compiler we often need to map variables to
  1834. information about them. We refer to these mappings as
  1835. \emph{environments}\index{subject}{environment}.\footnote{Another
  1836. common term for environment in the compiler literature is \emph{symbol
  1837. table}\index{subject}{symbol table}.}
  1838. %
  1839. We use%
  1840. %
  1841. \racket{an association list (alist)}
  1842. %
  1843. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1844. to represent the environment.
  1845. %
  1846. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1847. and the \code{racket/dict} package.}
  1848. %
  1849. The \code{interp\_exp} function takes the current environment,
  1850. \code{env}, as an extra parameter. When the interpreter encounters a
  1851. variable, it looks up the corresponding value in the dictionary.
  1852. %
  1853. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1854. initializing expression, extends the environment with the result
  1855. value bound to the variable, using \code{dict-set}, then evaluates
  1856. the body of the \key{Let}.}
  1857. %
  1858. \python{When the interpreter encounters an assignment, it evaluates
  1859. the initializing expression and then associates the resulting value
  1860. with the variable in the environment.}
  1861. \begin{figure}[tp]
  1862. {\if\edition\racketEd
  1863. \begin{lstlisting}
  1864. (define interp_Lvar_class
  1865. (class object%
  1866. (super-new)
  1867. (define/public ((interp_exp env) e)
  1868. (match e
  1869. [(Int n) n]
  1870. [(Prim 'read '())
  1871. (define r (read))
  1872. (cond [(fixnum? r) r]
  1873. [else (error 'interp_exp "expected an integer" r)])]
  1874. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1875. [(Prim '+ (list e1 e2))
  1876. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1877. [(Var x) (dict-ref env x)]
  1878. [(Let x e body)
  1879. (define new-env (dict-set env x ((interp_exp env) e)))
  1880. ((interp_exp new-env) body)]))
  1881. (define/public (interp_program p)
  1882. (match p
  1883. [(Program '() e) ((interp_exp '()) e)]))
  1884. ))
  1885. (define (interp_Lvar p)
  1886. (send (new interp_Lvar_class) interp_program p))
  1887. \end{lstlisting}
  1888. \fi}
  1889. {\if\edition\pythonEd
  1890. \begin{lstlisting}
  1891. class InterpLvar:
  1892. def interp_exp(self, e, env):
  1893. match e:
  1894. case BinOp(left, Add(), right):
  1895. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1896. case UnaryOp(USub(), v):
  1897. return - self.interp_exp(v, env)
  1898. case Name(id):
  1899. return env[id]
  1900. case Constant(value):
  1901. return value
  1902. case Call(Name('input_int'), []):
  1903. return int(input())
  1904. def interp_stmts(self, ss, env):
  1905. if len(ss) == 0:
  1906. return
  1907. match ss[0]:
  1908. case Assign([lhs], value):
  1909. env[lhs.id] = self.interp_exp(value, env)
  1910. return self.interp_stmts(ss[1:], env)
  1911. case Expr(Call(Name('print'), [arg])):
  1912. print(self.interp_exp(arg, env), end='')
  1913. return self.interp_stmts(ss[1:], env)
  1914. case Expr(value):
  1915. self.interp_exp(value, env)
  1916. return self.interp_stmts(ss[1:], env)
  1917. def interp_P(self, p):
  1918. match p:
  1919. case Module(body):
  1920. self.interp_stmts(body, {})
  1921. \end{lstlisting}
  1922. \fi}
  1923. \caption{Interpreter for the \LangVar{} language.}
  1924. \label{fig:interp-Lvar}
  1925. \end{figure}
  1926. The goal for this chapter is to implement a compiler that translates
  1927. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1928. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1929. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  1930. That is, they output the same integer $n$. We depict this correctness
  1931. criteria in the following diagram.
  1932. \[
  1933. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1934. \node (p1) at (0, 0) {$P_1$};
  1935. \node (p2) at (4, 0) {$P_2$};
  1936. \node (o) at (4, -2) {$n$};
  1937. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1938. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  1939. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1940. \end{tikzpicture}
  1941. \]
  1942. In the next section we introduce the \LangXInt{} subset of x86 that
  1943. suffices for compiling \LangVar{}.
  1944. \section{The \LangXInt{} Assembly Language}
  1945. \label{sec:x86}
  1946. \index{subject}{x86}
  1947. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1948. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1949. assembler.
  1950. %
  1951. A program begins with a \code{main} label followed by a sequence of
  1952. instructions. The \key{globl} directive says that the \key{main}
  1953. procedure is externally visible, which is necessary so that the
  1954. operating system can call it.
  1955. %
  1956. An x86 program is stored in the computer's memory. For our purposes,
  1957. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1958. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1959. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1960. the address of the next instruction to be executed. For most
  1961. instructions, the program counter is incremented after the instruction
  1962. is executed, so it points to the next instruction in memory. Most x86
  1963. instructions take two operands, where each operand is either an
  1964. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1965. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1966. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  1967. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  1968. && \key{r8} \MID \key{r9} \MID \key{r10}
  1969. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  1970. \MID \key{r14} \MID \key{r15}}
  1971. \begin{figure}[tp]
  1972. \fbox{
  1973. \begin{minipage}{0.96\textwidth}
  1974. {\if\edition\racketEd
  1975. \[
  1976. \begin{array}{lcl}
  1977. \Reg &::=& \allregisters{} \\
  1978. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1979. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  1980. \key{subq} \; \Arg\key{,} \Arg \MID
  1981. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  1982. && \key{callq} \; \mathit{label} \MID
  1983. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  1984. && \itm{label}\key{:}\; \Instr \\
  1985. \LangXIntM{} &::= & \key{.globl main}\\
  1986. & & \key{main:} \; \Instr\ldots
  1987. \end{array}
  1988. \]
  1989. \fi}
  1990. {\if\edition\pythonEd
  1991. \[
  1992. \begin{array}{lcl}
  1993. \Reg &::=& \allregisters{} \\
  1994. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1995. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  1996. \key{subq} \; \Arg\key{,} \Arg \MID
  1997. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  1998. && \key{callq} \; \mathit{label} \MID
  1999. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2000. \LangXIntM{} &::= & \key{.globl main}\\
  2001. & & \key{main:} \; \Instr^{*}
  2002. \end{array}
  2003. \]
  2004. \fi}
  2005. \end{minipage}
  2006. }
  2007. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2008. \label{fig:x86-int-concrete}
  2009. \end{figure}
  2010. A register is a special kind of variable that holds a 64-bit
  2011. value. There are 16 general-purpose registers in the computer and
  2012. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2013. is written with a \key{\%} followed by the register name, such as
  2014. \key{\%rax}.
  2015. An immediate value is written using the notation \key{\$}$n$ where $n$
  2016. is an integer.
  2017. %
  2018. %
  2019. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2020. which obtains the address stored in register $r$ and then adds $n$
  2021. bytes to the address. The resulting address is used to load or store
  2022. to memory depending on whether it occurs as a source or destination
  2023. argument of an instruction.
  2024. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2025. source $s$ and destination $d$, applies the arithmetic operation, then
  2026. writes the result back to the destination $d$. \index{subject}{instruction}
  2027. %
  2028. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2029. stores the result in $d$.
  2030. %
  2031. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2032. specified by the label and $\key{retq}$ returns from a procedure to
  2033. its caller.
  2034. %
  2035. We discuss procedure calls in more detail later in this chapter and in
  2036. Chapter~\ref{ch:Rfun}.
  2037. %
  2038. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2039. counter to the address of the instruction after the specified
  2040. label.}
  2041. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2042. all of the x86 instructions used in this book.
  2043. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2044. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2045. \lstinline{movq $10, %rax}
  2046. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2047. adds $32$ to the $10$ in \key{rax} and
  2048. puts the result, $42$, back into \key{rax}.
  2049. %
  2050. The last instruction, \key{retq}, finishes the \key{main} function by
  2051. returning the integer in \key{rax} to the operating system. The
  2052. operating system interprets this integer as the program's exit
  2053. code. By convention, an exit code of 0 indicates that a program
  2054. completed successfully, and all other exit codes indicate various
  2055. errors.
  2056. %
  2057. \racket{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. We exhibit the use of memory for storing intermediate results in the
  2072. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2073. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2074. uses a region of memory called the \emph{procedure call stack} (or
  2075. \emph{stack} for
  2076. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2077. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2078. for each procedure call. The memory layout for an individual frame is
  2079. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2080. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2081. item at the top of the stack. The stack grows downward in memory, so
  2082. we increase the size of the stack by subtracting from the stack
  2083. pointer. In the context of a procedure call, the \emph{return
  2084. address}\index{subject}{return address} is the instruction after the
  2085. call instruction on the caller side. The function call instruction,
  2086. \code{callq}, pushes the return address onto the stack prior to
  2087. jumping to the procedure. The register \key{rbp} is the \emph{base
  2088. pointer}\index{subject}{base pointer} and is used to access variables
  2089. that are stored in the frame of the current procedure call. The base
  2090. pointer of the caller is store after the return address. In
  2091. Figure~\ref{fig:frame} we number the variables from $1$ to
  2092. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2093. at $-16\key{(\%rbp)}$, etc.
  2094. \begin{figure}[tbp]
  2095. {\if\edition\racketEd
  2096. \begin{lstlisting}
  2097. start:
  2098. movq $10, -8(%rbp)
  2099. negq -8(%rbp)
  2100. movq -8(%rbp), %rax
  2101. addq $52, %rax
  2102. jmp conclusion
  2103. .globl main
  2104. main:
  2105. pushq %rbp
  2106. movq %rsp, %rbp
  2107. subq $16, %rsp
  2108. jmp start
  2109. conclusion:
  2110. addq $16, %rsp
  2111. popq %rbp
  2112. retq
  2113. \end{lstlisting}
  2114. \fi}
  2115. {\if\edition\pythonEd
  2116. \begin{lstlisting}
  2117. .globl main
  2118. main:
  2119. pushq %rbp
  2120. movq %rsp, %rbp
  2121. subq $16, %rsp
  2122. movq $10, -8(%rbp)
  2123. negq -8(%rbp)
  2124. movq -8(%rbp), %rax
  2125. addq $52, %rax
  2126. addq $16, %rsp
  2127. popq %rbp
  2128. retq
  2129. \end{lstlisting}
  2130. \fi}
  2131. \caption{An x86 program that computes
  2132. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2133. \label{fig:p1-x86}
  2134. \end{figure}
  2135. \begin{figure}[tbp]
  2136. \centering
  2137. \begin{tabular}{|r|l|} \hline
  2138. Position & Contents \\ \hline
  2139. 8(\key{\%rbp}) & return address \\
  2140. 0(\key{\%rbp}) & old \key{rbp} \\
  2141. -8(\key{\%rbp}) & variable $1$ \\
  2142. -16(\key{\%rbp}) & variable $2$ \\
  2143. \ldots & \ldots \\
  2144. 0(\key{\%rsp}) & variable $n$\\ \hline
  2145. \end{tabular}
  2146. \caption{Memory layout of a frame.}
  2147. \label{fig:frame}
  2148. \end{figure}
  2149. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2150. control is transferred from the operating system to the \code{main}
  2151. function. The operating system issues a \code{callq main} instruction
  2152. which pushes its return address on the stack and then jumps to
  2153. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2154. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2155. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2156. alignment (because the \code{callq} pushed the return address). The
  2157. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2158. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2159. pointer for the caller onto the stack and subtracts $8$ from the stack
  2160. pointer. The next instruction \code{movq \%rsp, \%rbp} sets the
  2161. base pointer to the current stack pointer, which is pointing at the location
  2162. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2163. pointer down to make enough room for storing variables. This program
  2164. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2165. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2166. functions.
  2167. \racket{The last instruction of the prelude is \code{jmp start},
  2168. which transfers control to the instructions that were generated from
  2169. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2170. \racket{The first instruction under the \code{start} label is}
  2171. %
  2172. \python{The first instruction after the prelude is}
  2173. %
  2174. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2175. %
  2176. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2177. %
  2178. The next instruction moves the $-10$ from variable $1$ into the
  2179. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2180. the value in \code{rax}, updating its contents to $42$.
  2181. \racket{The three instructions under the label \code{conclusion} are the
  2182. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2183. %
  2184. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2185. \code{main} function consists of the last three instructions.}
  2186. %
  2187. The first two restore the \code{rsp} and \code{rbp} registers to the
  2188. state they were in at the beginning of the procedure. In particular,
  2189. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2190. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2191. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2192. \key{retq}, jumps back to the procedure that called this one and adds
  2193. $8$ to the stack pointer.
  2194. Our compiler needs a convenient representation for manipulating x86
  2195. programs, so we define an abstract syntax for x86 in
  2196. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2197. \LangXInt{}.
  2198. %
  2199. {\if\edition\racketEd
  2200. The main difference compared to the concrete syntax of \LangXInt{}
  2201. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2202. front of every instruction. Instead instructions are grouped into
  2203. \emph{blocks}\index{subject}{block} with a
  2204. label associated with every block, which is why the \key{X86Program}
  2205. struct includes an alist mapping labels to blocks. The reason for this
  2206. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2207. introduce conditional branching. The \code{Block} structure includes
  2208. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2209. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2210. $\itm{info}$ field should contain an empty list.
  2211. \fi}
  2212. %
  2213. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2214. node includes an integer for representing the arity of the function,
  2215. i.e., the number of arguments, which is helpful to know during
  2216. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2217. \begin{figure}[tp]
  2218. \fbox{
  2219. \begin{minipage}{0.98\textwidth}
  2220. \small
  2221. {\if\edition\racketEd
  2222. \[
  2223. \begin{array}{lcl}
  2224. \Reg &::=& \allregisters{} \\
  2225. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2226. \MID \DEREF{\Reg}{\Int} \\
  2227. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2228. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2229. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2230. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2231. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2232. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2233. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2234. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2235. \end{array}
  2236. \]
  2237. \fi}
  2238. {\if\edition\pythonEd
  2239. \[
  2240. \begin{array}{lcl}
  2241. \Reg &::=& \allregisters{} \\
  2242. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2243. \MID \DEREF{\Reg}{\Int} \\
  2244. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2245. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2246. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2247. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2248. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2249. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2250. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2251. \end{array}
  2252. \]
  2253. \fi}
  2254. \end{minipage}
  2255. }
  2256. \caption{The abstract syntax of \LangXInt{} assembly.}
  2257. \label{fig:x86-int-ast}
  2258. \end{figure}
  2259. \section{Planning the trip to x86}
  2260. \label{sec:plan-s0-x86}
  2261. To compile one language to another it helps to focus on the
  2262. differences between the two languages because the compiler will need
  2263. to bridge those differences. What are the differences between \LangVar{}
  2264. and x86 assembly? Here are some of the most important ones:
  2265. \begin{enumerate}
  2266. \item x86 arithmetic instructions typically have two arguments
  2267. and update the second argument in place. In contrast, \LangVar{}
  2268. arithmetic operations take two arguments and produce a new value.
  2269. An x86 instruction may have at most one memory-accessing argument.
  2270. Furthermore, some instructions place special restrictions on their
  2271. arguments.
  2272. \item An argument of an \LangVar{} operator can be a deeply-nested
  2273. expression, whereas x86 instructions restrict their arguments to be
  2274. integer constants, registers, and memory locations.
  2275. {\if\edition\racketEd
  2276. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2277. sequence of instructions and jumps to labeled positions, whereas in
  2278. \LangVar{} the order of evaluation is a left-to-right depth-first
  2279. traversal of the abstract syntax tree.
  2280. \fi}
  2281. \item A program in \LangVar{} can have any number of variables
  2282. whereas x86 has 16 registers and the procedure call stack.
  2283. {\if\edition\racketEd
  2284. \item Variables in \LangVar{} can shadow other variables with the
  2285. same name. In x86, registers have unique names and memory locations
  2286. have unique addresses.
  2287. \fi}
  2288. \end{enumerate}
  2289. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2290. the problem into several steps, dealing with the above differences one
  2291. at a time. Each of these steps is called a \emph{pass} of the
  2292. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2293. %
  2294. This terminology comes from the way each step passes over the AST of
  2295. the program.
  2296. %
  2297. We begin by sketching how we might implement each pass, and give them
  2298. names. We then figure out an ordering of the passes and the
  2299. input/output language for each pass. The very first pass has
  2300. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2301. its output language. In between we can choose whichever language is
  2302. most convenient for expressing the output of each pass, whether that
  2303. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2304. our own design. Finally, to implement each pass we write one
  2305. recursive function per non-terminal in the grammar of the input
  2306. language of the pass. \index{subject}{intermediate language}
  2307. \begin{description}
  2308. {\if\edition\racketEd
  2309. \item[\key{uniquify}] deals with the shadowing of variables by
  2310. renaming every variable to a unique name.
  2311. \fi}
  2312. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2313. of a primitive operation or function call is a variable or integer,
  2314. that is, an \emph{atomic} expression. We refer to non-atomic
  2315. expressions as \emph{complex}. This pass introduces temporary
  2316. variables to hold the results of complex
  2317. subexpressions.\index{subject}{atomic
  2318. expression}\index{subject}{complex expression}%
  2319. {\if\edition\racketEd
  2320. \item[\key{explicate\_control}] makes the execution order of the
  2321. program explicit. It convert the abstract syntax tree representation
  2322. into a control-flow graph in which each node contains a sequence of
  2323. statements and the edges between nodes say which nodes contain jumps
  2324. to other nodes.
  2325. \fi}
  2326. \item[\key{select\_instructions}] handles the difference between
  2327. \LangVar{} operations and x86 instructions. This pass converts each
  2328. \LangVar{} operation to a short sequence of instructions that
  2329. accomplishes the same task.
  2330. \item[\key{assign\_homes}] replaces the variables in \LangVar{} with
  2331. registers or stack locations in x86.
  2332. \end{description}
  2333. The next question is: in what order should we apply these passes? This
  2334. question can be challenging because it is difficult to know ahead of
  2335. time which orderings will be better (easier to implement, produce more
  2336. efficient code, etc.) so oftentimes trial-and-error is
  2337. involved. Nevertheless, we can try to plan ahead and make educated
  2338. choices regarding the ordering.
  2339. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2340. \key{uniquify}? The \key{uniquify} pass should come first because
  2341. \key{explicate\_control} changes all the \key{let}-bound variables to
  2342. become local variables whose scope is the entire program, which would
  2343. confuse variables with the same name.}
  2344. %
  2345. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2346. because the later removes the \key{let} form, but it is convenient to
  2347. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2348. %
  2349. \racket{The ordering of \key{uniquify} with respect to
  2350. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2351. \key{uniquify} to come first.}
  2352. The \key{select\_instructions} and \key{assign\_homes} passes are
  2353. intertwined.
  2354. %
  2355. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers are used for
  2356. passing arguments to functions and it is preferable to assign
  2357. parameters to their corresponding registers. This suggests that it
  2358. would be better to start with the \key{select\_instructions} pass,
  2359. which generates the instructions for argument passing, before
  2360. performing register allocation.
  2361. %
  2362. On the other hand, by selecting instructions first we may run into a
  2363. dead end in \key{assign\_homes}. Recall that only one argument of an
  2364. x86 instruction may be a memory access but \key{assign\_homes} might
  2365. be forced to assign both arguments to memory locations.
  2366. %
  2367. A sophisticated approach is to iteratively repeat the two passes until
  2368. a solution is found. However, to reduce implementation complexity we
  2369. recommend a simpler approach in which \key{select\_instructions} comes
  2370. first, followed by the \key{assign\_homes}, then a third pass named
  2371. \key{patch\_instructions} that uses a reserved register to fix
  2372. outstanding problems.
  2373. \begin{figure}[tbp]
  2374. {\if\edition\racketEd
  2375. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2376. \node (Lvar) at (0,2) {\large \LangVar{}};
  2377. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2378. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2379. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2380. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2381. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2382. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2383. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2384. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2385. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2386. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2387. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2388. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2389. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2390. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2391. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print\_x86} (x86-5);
  2392. \end{tikzpicture}
  2393. \fi}
  2394. {\if\edition\pythonEd
  2395. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2396. \node (Lvar) at (0,2) {\large \LangVar{}};
  2397. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2398. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2399. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2400. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2401. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2402. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2403. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2404. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2405. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2406. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  2407. \end{tikzpicture}
  2408. \fi}
  2409. \caption{Diagram of the passes for compiling \LangVar{}. }
  2410. \label{fig:Lvar-passes}
  2411. \end{figure}
  2412. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2413. passes and identifies the input and output language of each pass.
  2414. %
  2415. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2416. language, which extends \LangXInt{} with an unbounded number of
  2417. program-scope variables and removes the restrictions regarding
  2418. instruction arguments.
  2419. %
  2420. The last pass, \key{prelude\_and\_conclusion}, places the program
  2421. instructions inside a \code{main} function with instructions for the
  2422. prelude and conclusion.
  2423. %
  2424. \racket{In the following section we discuss the \LangCVar{}
  2425. intermediate language.}
  2426. %
  2427. The remainder of this chapter provides guidance on the implementation
  2428. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2429. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2430. %% are programs that are still in the \LangVar{} language, though the
  2431. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2432. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2433. %% %
  2434. %% The output of \code{explicate\_control} is in an intermediate language
  2435. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2436. %% syntax, which we introduce in the next section. The
  2437. %% \key{select-instruction} pass translates from \LangCVar{} to
  2438. %% \LangXVar{}. The \key{assign-homes} and
  2439. %% \key{patch-instructions}
  2440. %% passes input and output variants of x86 assembly.
  2441. {\if\edition\racketEd
  2442. \subsection{The \LangCVar{} Intermediate Language}
  2443. The output of \code{explicate\_control} is similar to the $C$
  2444. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2445. categories for expressions and statements, so we name it \LangCVar{}. The
  2446. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2447. \racket{(The concrete syntax for \LangCVar{} is in the Appendix,
  2448. Figure~\ref{fig:c0-concrete-syntax}.)}
  2449. %
  2450. The \LangCVar{} language supports the same operators as \LangVar{} but
  2451. the arguments of operators are restricted to atomic
  2452. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2453. assignment statements which can be executed in sequence using the
  2454. \key{Seq} form. A sequence of statements always ends with
  2455. \key{Return}, a guarantee that is baked into the grammar rules for
  2456. \itm{tail}. The naming of this non-terminal comes from the term
  2457. \emph{tail position}\index{subject}{tail position}, which refers to an
  2458. expression that is the last one to execute within a function.
  2459. A \LangCVar{} program consists of a control-flow graph represented as
  2460. an alist mapping labels to tails. This is more general than necessary
  2461. for the present chapter, as we do not yet introduce \key{goto} for
  2462. jumping to labels, but it saves us from having to change the syntax in
  2463. Chapter~\ref{ch:Lif}. For now there will be just one label,
  2464. \key{start}, and the whole program is its tail.
  2465. %
  2466. The $\itm{info}$ field of the \key{CProgram} form, after the
  2467. \code{explicate\_control} pass, contains a mapping from the symbol
  2468. \key{locals} to a list of variables, that is, a list of all the
  2469. variables used in the program. At the start of the program, these
  2470. variables are uninitialized; they become initialized on their first
  2471. assignment.
  2472. \begin{figure}[tbp]
  2473. \fbox{
  2474. \begin{minipage}{0.96\textwidth}
  2475. \[
  2476. \begin{array}{lcl}
  2477. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2478. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2479. &\MID& \ADD{\Atm}{\Atm}\\
  2480. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2481. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2482. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2483. \end{array}
  2484. \]
  2485. \end{minipage}
  2486. }
  2487. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2488. \label{fig:c0-syntax}
  2489. \end{figure}
  2490. The definitional interpreter for \LangCVar{} is in the support code,
  2491. in the file \code{interp-Cvar.rkt}.
  2492. \fi}
  2493. {\if\edition\racketEd
  2494. \section{Uniquify Variables}
  2495. \label{sec:uniquify-Lvar}
  2496. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2497. programs in which every \key{let} binds a unique variable name. For
  2498. example, the \code{uniquify} pass should translate the program on the
  2499. left into the program on the right.
  2500. \begin{transformation}
  2501. \begin{lstlisting}
  2502. (let ([x 32])
  2503. (+ (let ([x 10]) x) x))
  2504. \end{lstlisting}
  2505. \compilesto
  2506. \begin{lstlisting}
  2507. (let ([x.1 32])
  2508. (+ (let ([x.2 10]) x.2) x.1))
  2509. \end{lstlisting}
  2510. \end{transformation}
  2511. The following is another example translation, this time of a program
  2512. with a \key{let} nested inside the initializing expression of another
  2513. \key{let}.
  2514. \begin{transformation}
  2515. \begin{lstlisting}
  2516. (let ([x (let ([x 4])
  2517. (+ x 1))])
  2518. (+ x 2))
  2519. \end{lstlisting}
  2520. \compilesto
  2521. \begin{lstlisting}
  2522. (let ([x.2 (let ([x.1 4])
  2523. (+ x.1 1))])
  2524. (+ x.2 2))
  2525. \end{lstlisting}
  2526. \end{transformation}
  2527. We recommend implementing \code{uniquify} by creating a structurally
  2528. recursive function named \code{uniquify-exp} that mostly just copies
  2529. an expression. However, when encountering a \key{let}, it should
  2530. generate a unique name for the variable and associate the old name
  2531. with the new name in an alist.\footnote{The Racket function
  2532. \code{gensym} is handy for generating unique variable names.} The
  2533. \code{uniquify-exp} function needs to access this alist when it gets
  2534. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2535. for the alist.
  2536. The skeleton of the \code{uniquify-exp} function is shown in
  2537. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2538. convenient to partially apply it to an alist and then apply it to
  2539. different expressions, as in the last case for primitive operations in
  2540. Figure~\ref{fig:uniquify-Lvar}. The
  2541. %
  2542. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2543. %
  2544. form of Racket is useful for transforming each element of a list to
  2545. produce a new list.\index{subject}{for/list}
  2546. \begin{figure}[tbp]
  2547. \begin{lstlisting}
  2548. (define (uniquify-exp env)
  2549. (lambda (e)
  2550. (match e
  2551. [(Var x) ___]
  2552. [(Int n) (Int n)]
  2553. [(Let x e body) ___]
  2554. [(Prim op es)
  2555. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2556. (define (uniquify p)
  2557. (match p
  2558. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2559. \end{lstlisting}
  2560. \caption{Skeleton for the \key{uniquify} pass.}
  2561. \label{fig:uniquify-Lvar}
  2562. \end{figure}
  2563. \begin{exercise}
  2564. \normalfont % I don't like the italics for exercises. -Jeremy
  2565. Complete the \code{uniquify} pass by filling in the blanks in
  2566. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2567. variables and for the \key{let} form in the file \code{compiler.rkt}
  2568. in the support code.
  2569. \end{exercise}
  2570. \begin{exercise}
  2571. \normalfont % I don't like the italics for exercises. -Jeremy
  2572. \label{ex:Lvar}
  2573. Create five \LangVar{} programs that exercise the most interesting
  2574. parts of the \key{uniquify} pass, that is, the programs should include
  2575. \key{let} forms, variables, and variables that shadow each other.
  2576. The five programs should be placed in the subdirectory named
  2577. \key{tests} and the file names should start with \code{var\_test\_}
  2578. followed by a unique integer and end with the file extension
  2579. \key{.rkt}.
  2580. %
  2581. The \key{run-tests.rkt} script in the support code checks whether the
  2582. output programs produce the same result as the input programs. The
  2583. script uses the \key{interp-tests} function
  2584. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2585. your \key{uniquify} pass on the example programs. The \code{passes}
  2586. parameter of \key{interp-tests} is a list that should have one entry
  2587. for each pass in your compiler. For now, define \code{passes} to
  2588. contain just one entry for \code{uniquify} as shown below.
  2589. \begin{lstlisting}
  2590. (define passes
  2591. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2592. \end{lstlisting}
  2593. Run the \key{run-tests.rkt} script in the support code to check
  2594. whether the output programs produce the same result as the input
  2595. programs.
  2596. \end{exercise}
  2597. \fi}
  2598. \section{Remove Complex Operands}
  2599. \label{sec:remove-complex-opera-Lvar}
  2600. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2601. into a restricted form in which the arguments of operations are atomic
  2602. expressions. Put another way, this pass removes complex
  2603. operands\index{subject}{complex operand}, such as the expression
  2604. \racket{\code{(- 10)}}\python{\code{-10}}
  2605. in the program below. This is accomplished by introducing a new
  2606. temporary variable, assigning the complex operand to the new
  2607. variable, and then using the new variable in place of the complex
  2608. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2609. right.
  2610. {\if\edition\racketEd
  2611. \begin{transformation}
  2612. % var_test_19.rkt
  2613. \begin{lstlisting}
  2614. (let ([x (+ 42 (- 10))])
  2615. (+ x 10))
  2616. \end{lstlisting}
  2617. \compilesto
  2618. \begin{lstlisting}
  2619. (let ([x (let ([tmp.1 (- 10)])
  2620. (+ 42 tmp.1))])
  2621. (+ x 10))
  2622. \end{lstlisting}
  2623. \end{transformation}
  2624. \fi}
  2625. {\if\edition\pythonEd
  2626. \begin{transformation}
  2627. \begin{lstlisting}
  2628. x = 42 + -10
  2629. print(x + 10)
  2630. \end{lstlisting}
  2631. \compilesto
  2632. \begin{lstlisting}
  2633. tmp_0 = -10
  2634. x = 42 + tmp_0
  2635. tmp_1 = x + 10
  2636. print(tmp_1)
  2637. \end{lstlisting}
  2638. \end{transformation}
  2639. \fi}
  2640. \begin{figure}[tp]
  2641. \centering
  2642. \fbox{
  2643. \begin{minipage}{0.96\textwidth}
  2644. {\if\edition\racketEd
  2645. \[
  2646. \begin{array}{rcl}
  2647. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2648. \Exp &::=& \Atm \MID \READ{} \\
  2649. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2650. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2651. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2652. \end{array}
  2653. \]
  2654. \fi}
  2655. {\if\edition\pythonEd
  2656. \[
  2657. \begin{array}{rcl}
  2658. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2659. \Exp{} &::=& \Atm \MID \READ{} \\
  2660. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2661. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2662. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2663. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2664. \end{array}
  2665. \]
  2666. \fi}
  2667. \end{minipage}
  2668. }
  2669. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2670. atomic expressions, like administrative normal form (ANF).}
  2671. \label{fig:Lvar-anf-syntax}
  2672. \end{figure}
  2673. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output of
  2674. this pass, the language \LangVarANF{}. The only difference is that
  2675. operator arguments are restricted to be atomic expressions that are
  2676. defined by the \Atm{} non-terminal. In particular, integer constants
  2677. and variables are atomic. In the literature, restricting arguments to
  2678. be atomic expressions is one of the ideas in \emph{administrative
  2679. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2680. \index{subject}{administrative normal form} \index{subject}{ANF}
  2681. {\if\edition\racketEd
  2682. We recommend implementing this pass with two mutually recursive
  2683. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2684. \code{rco\_atom} to subexpressions that need to become atomic and to
  2685. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2686. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2687. returns an expression. The \code{rco\_atom} function returns two
  2688. things: an atomic expression and an alist mapping temporary variables to
  2689. complex subexpressions. You can return multiple things from a function
  2690. using Racket's \key{values} form and you can receive multiple things
  2691. from a function call using the \key{define-values} form.
  2692. Also, the
  2693. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2694. form is useful for applying a function to each element of a list, in
  2695. the case where the function returns multiple values.
  2696. \index{subject}{for/lists}
  2697. \fi}
  2698. %
  2699. {\if\edition\pythonEd
  2700. %
  2701. We recommend implementing this pass with an auxiliary method named
  2702. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2703. Boolean that specifies whether the expression needs to become atomic
  2704. or not. The \code{rco\_exp} method should return a pair consisting of
  2705. the new expression and a list of pairs, associating new temporary
  2706. variables with their initializing expressions.
  2707. %
  2708. \fi}
  2709. {\if\edition\racketEd
  2710. Returning to the example program with the expression \code{(+ 42 (-
  2711. 10))}, the subexpression \code{(- 10)} should be processed using the
  2712. \code{rco\_atom} function because it is an argument of the \code{+} and
  2713. therefore needs to become atomic. The output of \code{rco\_atom}
  2714. applied to \code{(- 10)} is as follows.
  2715. \begin{transformation}
  2716. \begin{lstlisting}
  2717. (- 10)
  2718. \end{lstlisting}
  2719. \compilesto
  2720. \begin{lstlisting}
  2721. tmp.1
  2722. ((tmp.1 . (- 10)))
  2723. \end{lstlisting}
  2724. \end{transformation}
  2725. \fi}
  2726. %
  2727. {\if\edition\pythonEd
  2728. %
  2729. Returning to the example program with the expression \code{42 + -10},
  2730. the subexpression \code{-10} should be processed using the
  2731. \code{rco\_exp} function with \code{True} as the second argument
  2732. because \code{-10} is an argument of the \code{+} operator and
  2733. therefore needs to become atomic. The output of \code{rco\_exp}
  2734. applied to \code{-10} is as follows.
  2735. \begin{transformation}
  2736. \begin{lstlisting}
  2737. -10
  2738. \end{lstlisting}
  2739. \compilesto
  2740. \begin{lstlisting}
  2741. tmp_1
  2742. [(tmp_1, -10)]
  2743. \end{lstlisting}
  2744. \end{transformation}
  2745. %
  2746. \fi}
  2747. Take special care of programs such as the following that
  2748. %
  2749. \racket{bind a variable to an atomic expression}
  2750. %
  2751. \python{assign an atomic expression to a variable}.
  2752. %
  2753. You should leave such \racket{variable bindings}\python{assignments}
  2754. unchanged, as shown in the program on the right\\
  2755. %
  2756. {\if\edition\racketEd
  2757. \begin{transformation}
  2758. % var_test_20.rkt
  2759. \begin{lstlisting}
  2760. (let ([a 42])
  2761. (let ([b a])
  2762. b))
  2763. \end{lstlisting}
  2764. \compilesto
  2765. \begin{lstlisting}
  2766. (let ([a 42])
  2767. (let ([b a])
  2768. b))
  2769. \end{lstlisting}
  2770. \end{transformation}
  2771. \fi}
  2772. {\if\edition\pythonEd
  2773. \begin{transformation}
  2774. \begin{lstlisting}
  2775. a = 42
  2776. b = a
  2777. print(b)
  2778. \end{lstlisting}
  2779. \compilesto
  2780. \begin{lstlisting}
  2781. a = 42
  2782. b = a
  2783. print(b)
  2784. \end{lstlisting}
  2785. \end{transformation}
  2786. \fi}
  2787. %
  2788. \noindent A careless implementation might produce the following output with
  2789. unnecessary temporary variables.
  2790. \begin{center}
  2791. \begin{minipage}{0.4\textwidth}
  2792. {\if\edition\racketEd
  2793. \begin{lstlisting}
  2794. (let ([tmp.1 42])
  2795. (let ([a tmp.1])
  2796. (let ([tmp.2 a])
  2797. (let ([b tmp.2])
  2798. b))))
  2799. \end{lstlisting}
  2800. \fi}
  2801. {\if\edition\pythonEd
  2802. \begin{lstlisting}
  2803. tmp_1 = 42
  2804. a = tmp_1
  2805. tmp_2 = a
  2806. b = tmp_2
  2807. print(b)
  2808. \end{lstlisting}
  2809. \fi}
  2810. \end{minipage}
  2811. \end{center}
  2812. \begin{exercise}
  2813. \normalfont
  2814. {\if\edition\racketEd
  2815. Implement the \code{remove\_complex\_operands} function in
  2816. \code{compiler.rkt}.
  2817. %
  2818. Create three new \LangVar{} programs that exercise the interesting
  2819. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2820. regarding file names described in Exercise~\ref{ex:Lvar}.
  2821. %
  2822. In the \code{run-tests.rkt} script, add the following entry to the
  2823. list of \code{passes} and then run the script to test your compiler.
  2824. \begin{lstlisting}
  2825. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  2826. \end{lstlisting}
  2827. While debugging your compiler, it is often useful to see the
  2828. intermediate programs that are output from each pass. To print the
  2829. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2830. \code{interp-tests} in \code{run-tests.rkt}.
  2831. \fi}
  2832. %
  2833. {\if\edition\pythonEd
  2834. Implement the \code{remove\_complex\_operands} pass in
  2835. \code{compiler.py}, creating auxiliary functions for each
  2836. non-terminal in the grammar, i.e., \code{rco\_exp}
  2837. and \code{rco\_stmt}.
  2838. \fi}
  2839. \end{exercise}
  2840. {\if\edition\pythonEd
  2841. \begin{exercise}
  2842. \normalfont % I don't like the italics for exercises. -Jeremy
  2843. \label{ex:Lvar}
  2844. Create five \LangVar{} programs that exercise the most interesting
  2845. parts of the \code{remove\_complex\_operands} pass. The five programs
  2846. should be placed in the subdirectory named \key{tests} and the file
  2847. names should start with \code{var\_test\_} followed by a unique
  2848. integer and end with the file extension \key{.py}.
  2849. %% The \key{run-tests.rkt} script in the support code checks whether the
  2850. %% output programs produce the same result as the input programs. The
  2851. %% script uses the \key{interp-tests} function
  2852. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2853. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2854. %% parameter of \key{interp-tests} is a list that should have one entry
  2855. %% for each pass in your compiler. For now, define \code{passes} to
  2856. %% contain just one entry for \code{uniquify} as shown below.
  2857. %% \begin{lstlisting}
  2858. %% (define passes
  2859. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2860. %% \end{lstlisting}
  2861. Run the \key{run-tests.py} script in the support code to check
  2862. whether the output programs produce the same result as the input
  2863. programs.
  2864. \end{exercise}
  2865. \fi}
  2866. {\if\edition\racketEd
  2867. \section{Explicate Control}
  2868. \label{sec:explicate-control-Lvar}
  2869. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  2870. programs that make the order of execution explicit in their
  2871. syntax. For now this amounts to flattening \key{let} constructs into a
  2872. sequence of assignment statements. For example, consider the following
  2873. \LangVar{} program.\\
  2874. % var_test_11.rkt
  2875. \begin{minipage}{0.96\textwidth}
  2876. \begin{lstlisting}
  2877. (let ([y (let ([x 20])
  2878. (+ x (let ([x 22]) x)))])
  2879. y)
  2880. \end{lstlisting}
  2881. \end{minipage}\\
  2882. %
  2883. The output of the previous pass and of \code{explicate\_control} is
  2884. shown below. Recall that the right-hand-side of a \key{let} executes
  2885. before its body, so the order of evaluation for this program is to
  2886. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2887. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2888. output of \code{explicate\_control} makes this ordering explicit.
  2889. \begin{transformation}
  2890. \begin{lstlisting}
  2891. (let ([y (let ([x.1 20])
  2892. (let ([x.2 22])
  2893. (+ x.1 x.2)))])
  2894. y)
  2895. \end{lstlisting}
  2896. \compilesto
  2897. \begin{lstlisting}[language=C]
  2898. start:
  2899. x.1 = 20;
  2900. x.2 = 22;
  2901. y = (+ x.1 x.2);
  2902. return y;
  2903. \end{lstlisting}
  2904. \end{transformation}
  2905. \begin{figure}[tbp]
  2906. \begin{lstlisting}
  2907. (define (explicate_tail e)
  2908. (match e
  2909. [(Var x) ___]
  2910. [(Int n) (Return (Int n))]
  2911. [(Let x rhs body) ___]
  2912. [(Prim op es) ___]
  2913. [else (error "explicate_tail unhandled case" e)]))
  2914. (define (explicate_assign e x cont)
  2915. (match e
  2916. [(Var x) ___]
  2917. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2918. [(Let y rhs body) ___]
  2919. [(Prim op es) ___]
  2920. [else (error "explicate_assign unhandled case" e)]))
  2921. (define (explicate_control p)
  2922. (match p
  2923. [(Program info body) ___]))
  2924. \end{lstlisting}
  2925. \caption{Skeleton for the \code{explicate\_control} pass.}
  2926. \label{fig:explicate-control-Lvar}
  2927. \end{figure}
  2928. The organization of this pass depends on the notion of tail position
  2929. that we have alluded to earlier.
  2930. \begin{definition}
  2931. The following rules define when an expression is in \textbf{\emph{tail
  2932. position}}\index{subject}{tail position} for the language \LangVar{}.
  2933. \begin{enumerate}
  2934. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2935. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2936. \end{enumerate}
  2937. \end{definition}
  2938. We recommend implementing \code{explicate\_control} using two mutually
  2939. recursive functions, \code{explicate\_tail} and
  2940. \code{explicate\_assign}, as suggested in the skeleton code in
  2941. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  2942. function should be applied to expressions in tail position whereas the
  2943. \code{explicate\_assign} should be applied to expressions that occur on
  2944. the right-hand-side of a \key{let}.
  2945. %
  2946. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  2947. input and produces a \Tail{} in \LangCVar{} (see
  2948. Figure~\ref{fig:c0-syntax}).
  2949. %
  2950. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  2951. the variable that it is to be assigned to, and a \Tail{} in
  2952. \LangCVar{} for the code that comes after the assignment. The
  2953. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  2954. The \code{explicate\_assign} function is in accumulator-passing style:
  2955. the \code{cont} parameter is used for accumulating the output. This
  2956. accumulator-passing style plays an important role in how we generate
  2957. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  2958. \begin{exercise}\normalfont
  2959. %
  2960. Implement the \code{explicate\_control} function in
  2961. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2962. exercise the code in \code{explicate\_control}.
  2963. %
  2964. In the \code{run-tests.rkt} script, add the following entry to the
  2965. list of \code{passes} and then run the script to test your compiler.
  2966. \begin{lstlisting}
  2967. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  2968. \end{lstlisting}
  2969. \end{exercise}
  2970. \fi}
  2971. \section{Select Instructions}
  2972. \label{sec:select-Lvar}
  2973. \index{subject}{instruction selection}
  2974. In the \code{select\_instructions} pass we begin the work of
  2975. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  2976. language of this pass is a variant of x86 that still uses variables,
  2977. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  2978. non-terminal of the \LangXInt{} abstract syntax
  2979. (Figure~\ref{fig:x86-int-ast}).
  2980. \racket{We recommend implementing the
  2981. \code{select\_instructions} with three auxiliary functions, one for
  2982. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  2983. $\Tail$.}
  2984. \python{We recommend implementing an auxiliary function
  2985. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  2986. \racket{
  2987. The cases for $\Atm$ are straightforward; variables stay
  2988. the same and integer constants change to immediates:
  2989. $\INT{n}$ changes to $\IMM{n}$.}
  2990. We consider the cases for the $\Stmt$ non-terminal, starting with
  2991. arithmetic operations. For example, consider the addition operation
  2992. below, on the left side. There is an \key{addq} instruction in x86,
  2993. but it performs an in-place update. So we could move $\Arg_1$
  2994. into the left-hand side \itm{var} and then add $\Arg_2$ to
  2995. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  2996. $\Atm_1$ and $\Atm_2$ respectively.
  2997. \begin{transformation}
  2998. {\if\edition\racketEd
  2999. \begin{lstlisting}
  3000. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3001. \end{lstlisting}
  3002. \fi}
  3003. {\if\edition\pythonEd
  3004. \begin{lstlisting}
  3005. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3006. \end{lstlisting}
  3007. \fi}
  3008. \compilesto
  3009. \begin{lstlisting}
  3010. movq |$\Arg_1$|, |$\itm{var}$|
  3011. addq |$\Arg_2$|, |$\itm{var}$|
  3012. \end{lstlisting}
  3013. \end{transformation}
  3014. There are also cases that require special care to avoid generating
  3015. needlessly complicated code. For example, if one of the arguments of
  3016. the addition is the same variable as the left-hand side of the
  3017. assignment, as shown below, then there is no need for the extra move
  3018. instruction. The assignment statement can be translated into a single
  3019. \key{addq} instruction as follows.
  3020. \begin{transformation}
  3021. {\if\edition\racketEd
  3022. \begin{lstlisting}
  3023. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3024. \end{lstlisting}
  3025. \fi}
  3026. {\if\edition\pythonEd
  3027. \begin{lstlisting}
  3028. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3029. \end{lstlisting}
  3030. \fi}
  3031. \compilesto
  3032. \begin{lstlisting}
  3033. addq |$\Arg_1$|, |$\itm{var}$|
  3034. \end{lstlisting}
  3035. \end{transformation}
  3036. The \READOP{} operation does not have a direct counterpart in x86
  3037. assembly, so we provide this functionality with the function
  3038. \code{read\_int} in the file \code{runtime.c}, written in
  3039. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3040. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3041. system}, or simply the \emph{runtime} for short. When compiling your
  3042. generated x86 assembly code, you need to compile \code{runtime.c} to
  3043. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3044. \code{-c}) and link it into the executable. For our purposes of code
  3045. generation, all you need to do is translate an assignment of
  3046. \READOP{} into a call to the \code{read\_int} function followed by a
  3047. move from \code{rax} to the left-hand-side variable. (Recall that the
  3048. return value of a function goes into \code{rax}.)
  3049. \begin{transformation}
  3050. {\if\edition\racketEd
  3051. \begin{lstlisting}
  3052. |$\itm{var}$| = (read);
  3053. \end{lstlisting}
  3054. \fi}
  3055. {\if\edition\pythonEd
  3056. \begin{lstlisting}
  3057. |$\itm{var}$| = input_int();
  3058. \end{lstlisting}
  3059. \fi}
  3060. \compilesto
  3061. \begin{lstlisting}
  3062. callq read_int
  3063. movq %rax, |$\itm{var}$|
  3064. \end{lstlisting}
  3065. \end{transformation}
  3066. {\if\edition\pythonEd
  3067. %
  3068. Similarly, we translate the \code{print} operation, shown below, into
  3069. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3070. In x86, the first six arguments to functions are passed in registers,
  3071. with the first argument passed in register \code{rdi}. So we move the
  3072. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3073. \code{callq} instruction.
  3074. \begin{transformation}
  3075. \begin{lstlisting}
  3076. print(|$\Atm$|)
  3077. \end{lstlisting}
  3078. \compilesto
  3079. \begin{lstlisting}
  3080. movq |$\Arg$|, %rdi
  3081. callq print_int
  3082. \end{lstlisting}
  3083. \end{transformation}
  3084. %
  3085. \fi}
  3086. {\if\edition\racketEd
  3087. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3088. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3089. assignment to the \key{rax} register followed by a jump to the
  3090. conclusion of the program (so the conclusion needs to be labeled).
  3091. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3092. recursively and then append the resulting instructions.
  3093. \fi}
  3094. \begin{exercise}
  3095. \normalfont
  3096. {\if\edition\racketEd
  3097. Implement the \code{select\_instructions} pass in
  3098. \code{compiler.rkt}. Create three new example programs that are
  3099. designed to exercise all of the interesting cases in this pass.
  3100. %
  3101. In the \code{run-tests.rkt} script, add the following entry to the
  3102. list of \code{passes} and then run the script to test your compiler.
  3103. \begin{lstlisting}
  3104. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3105. \end{lstlisting}
  3106. \fi}
  3107. {\if\edition\pythonEd
  3108. Implement the \key{select\_instructions} pass in
  3109. \code{compiler.py}. Create three new example programs that are
  3110. designed to exercise all of the interesting cases in this pass.
  3111. Run the \code{run-tests.py} script to to check
  3112. whether the output programs produce the same result as the input
  3113. programs.
  3114. \fi}
  3115. \end{exercise}
  3116. \section{Assign Homes}
  3117. \label{sec:assign-Lvar}
  3118. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3119. \LangXVar{} programs that no longer use program variables.
  3120. Thus, the \key{assign-homes} pass is responsible for placing all of
  3121. the program variables in registers or on the stack. For runtime
  3122. efficiency, it is better to place variables in registers, but as there
  3123. are only 16 registers, some programs must necessarily resort to
  3124. placing some variables on the stack. In this chapter we focus on the
  3125. mechanics of placing variables on the stack. We study an algorithm for
  3126. placing variables in registers in
  3127. Chapter~\ref{ch:register-allocation-Lvar}.
  3128. Consider again the following \LangVar{} program from
  3129. Section~\ref{sec:remove-complex-opera-Lvar}.
  3130. % var_test_20.rkt
  3131. {\if\edition\racketEd
  3132. \begin{lstlisting}
  3133. (let ([a 42])
  3134. (let ([b a])
  3135. b))
  3136. \end{lstlisting}
  3137. \fi}
  3138. {\if\edition\pythonEd
  3139. \begin{lstlisting}
  3140. a = 42
  3141. b = a
  3142. print(b)
  3143. \end{lstlisting}
  3144. \fi}
  3145. %
  3146. The output of \code{select\_instructions} is shown below, on the left,
  3147. and the output of \code{assign\_homes} is on the right. In this
  3148. example, we assign variable \code{a} to stack location
  3149. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3150. \begin{transformation}
  3151. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3152. movq $42, a
  3153. movq a, b
  3154. movq b, %rax
  3155. \end{lstlisting}
  3156. \compilesto
  3157. %stack-space: 16
  3158. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3159. movq $42, -8(%rbp)
  3160. movq -8(%rbp), -16(%rbp)
  3161. movq -16(%rbp), %rax
  3162. \end{lstlisting}
  3163. \end{transformation}
  3164. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3165. \code{X86Program} node is an alist mapping all the variables in the
  3166. program to their types (for now just \code{Integer}). The
  3167. \code{assign\_homes} pass should replace all uses of those variables
  3168. with stack locations. As an aside, the \code{locals-types} entry is
  3169. computed by \code{type-check-Cvar} in the support code, which
  3170. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3171. which should be propagated to the \code{X86Program} node.}
  3172. %
  3173. \python{The \code{assign\_homes} pass should replace all uses of
  3174. variables with stack locations.}
  3175. %
  3176. In the process of assigning variables to stack locations, it is
  3177. convenient for you to compute and store the size of the frame (in
  3178. bytes) in%
  3179. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3180. %
  3181. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3182. which is needed later to generate the conclusion of the \code{main}
  3183. procedure. The x86-64 standard requires the frame size to be a
  3184. multiple of 16 bytes.\index{subject}{frame}
  3185. % TODO: store the number of variables instead? -Jeremy
  3186. \begin{exercise}\normalfont
  3187. Implement the \key{assign\_homes} pass in
  3188. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3189. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3190. grammar. We recommend that the auxiliary functions take an extra
  3191. parameter that maps variable names to homes (stack locations for now).
  3192. %
  3193. {\if\edition\racketEd
  3194. In the \code{run-tests.rkt} script, add the following entry to the
  3195. list of \code{passes} and then run the script to test your compiler.
  3196. \begin{lstlisting}
  3197. (list "assign homes" assign-homes interp_x86-0)
  3198. \end{lstlisting}
  3199. \fi}
  3200. {\if\edition\pythonEd
  3201. Run the \code{run-tests.py} script to to check
  3202. whether the output programs produce the same result as the input
  3203. programs.
  3204. \fi}
  3205. \end{exercise}
  3206. \section{Patch Instructions}
  3207. \label{sec:patch-s0}
  3208. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3209. \LangXInt{} by making sure that each instruction adheres to the
  3210. restriction that at most one argument of an instruction may be a
  3211. memory reference.
  3212. We return to the following example.\\
  3213. \begin{minipage}{0.5\textwidth}
  3214. % var_test_20.rkt
  3215. {\if\edition\racketEd
  3216. \begin{lstlisting}
  3217. (let ([a 42])
  3218. (let ([b a])
  3219. b))
  3220. \end{lstlisting}
  3221. \fi}
  3222. {\if\edition\pythonEd
  3223. \begin{lstlisting}
  3224. a = 42
  3225. b = a
  3226. print(b)
  3227. \end{lstlisting}
  3228. \fi}
  3229. \end{minipage}\\
  3230. The \key{assign\_homes} pass produces the following translation. \\
  3231. \begin{minipage}{0.5\textwidth}
  3232. {\if\edition\racketEd
  3233. \begin{lstlisting}
  3234. movq $42, -8(%rbp)
  3235. movq -8(%rbp), -16(%rbp)
  3236. movq -16(%rbp), %rax
  3237. \end{lstlisting}
  3238. \fi}
  3239. {\if\edition\pythonEd
  3240. \begin{lstlisting}
  3241. movq 42, -8(%rbp)
  3242. movq -8(%rbp), -16(%rbp)
  3243. movq -16(%rbp), %rdi
  3244. callq print_int
  3245. \end{lstlisting}
  3246. \fi}
  3247. \end{minipage}\\
  3248. The second \key{movq} instruction is problematic because both
  3249. arguments are stack locations. We suggest fixing this problem by
  3250. moving from the source location to the register \key{rax} and then
  3251. from \key{rax} to the destination location, as follows.
  3252. \begin{lstlisting}
  3253. movq -8(%rbp), %rax
  3254. movq %rax, -16(%rbp)
  3255. \end{lstlisting}
  3256. \begin{exercise}
  3257. \normalfont Implement the \key{patch\_instructions} pass in
  3258. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3259. Create three new example programs that are
  3260. designed to exercise all of the interesting cases in this pass.
  3261. %
  3262. {\if\edition\racketEd
  3263. In the \code{run-tests.rkt} script, add the following entry to the
  3264. list of \code{passes} and then run the script to test your compiler.
  3265. \begin{lstlisting}
  3266. (list "patch instructions" patch_instructions interp_x86-0)
  3267. \end{lstlisting}
  3268. \fi}
  3269. {\if\edition\pythonEd
  3270. Run the \code{run-tests.py} script to to check
  3271. whether the output programs produce the same result as the input
  3272. programs.
  3273. \fi}
  3274. \end{exercise}
  3275. \section{Generate Prelude and Conclusion}
  3276. \label{sec:print-x86}
  3277. \index{subject}{prelude}\index{subject}{conclusion}
  3278. The last step of the compiler from \LangVar{} to x86 is to generate
  3279. the \code{main} function with a prelude and conclusion wrapped around
  3280. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3281. discussed in Section~\ref{sec:x86}.
  3282. When running on Mac OS X, your compiler should prefix an underscore to
  3283. all labels, e.g., changing \key{main} to \key{\_main}.
  3284. %
  3285. \racket{The Racket call \code{(system-type 'os)} is useful for
  3286. determining which operating system the compiler is running on. It
  3287. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3288. %
  3289. \python{The Python \code{platform} library includes a \code{system()}
  3290. function that returns \code{'Linux'}, \code{'Windows'}, or
  3291. \code{'Darwin'} (for Mac).}
  3292. \begin{exercise}\normalfont
  3293. %
  3294. Implement the \key{prelude\_and\_conclusion} pass in
  3295. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3296. %
  3297. {\if\edition\racketEd
  3298. In the \code{run-tests.rkt} script, add the following entry to the
  3299. list of \code{passes} and then run the script to test your compiler.
  3300. \begin{lstlisting}
  3301. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3302. \end{lstlisting}
  3303. %
  3304. Uncomment the call to the \key{compiler-tests} function
  3305. (Appendix~\ref{appendix:utilities}), which tests your complete
  3306. compiler by executing the generated x86 code. It translates the x86
  3307. AST that you produce into a string by invoking the \code{print-x86}
  3308. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3309. the provided \key{runtime.c} file to \key{runtime.o} using
  3310. \key{gcc}. Run the script to test your compiler.
  3311. %
  3312. \fi}
  3313. {\if\edition\pythonEd
  3314. %
  3315. Run the \code{run-tests.py} script to to check whether the output
  3316. programs produce the same result as the input programs. That script
  3317. translates the x86 AST that you produce into a string by invoking the
  3318. \code{repr} method that is implemented by the x86 AST classes in
  3319. \code{x86\_ast.py}.
  3320. %
  3321. \fi}
  3322. \end{exercise}
  3323. \section{Challenge: Partial Evaluator for \LangVar{}}
  3324. \label{sec:pe-Lvar}
  3325. \index{subject}{partial evaluation}
  3326. This section describes two optional challenge exercises that involve
  3327. adapting and improving the partial evaluator for \LangInt{} that was
  3328. introduced in Section~\ref{sec:partial-evaluation}.
  3329. \begin{exercise}\label{ex:pe-Lvar}
  3330. \normalfont
  3331. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3332. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3333. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3334. %
  3335. \racket{\key{let} binding}\python{assignment}
  3336. %
  3337. to the \LangInt{} language, so you will need to add cases for them in
  3338. the \code{pe\_exp}
  3339. %
  3340. \racket{function}
  3341. %
  3342. \python{and \code{pe\_stmt} functions}.
  3343. %
  3344. Once complete, add the partial evaluation pass to the front of your
  3345. compiler and make sure that your compiler still passes all of the
  3346. tests.
  3347. \end{exercise}
  3348. \begin{exercise}
  3349. \normalfont
  3350. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3351. \code{pe\_add} auxiliary functions with functions that know more about
  3352. arithmetic. For example, your partial evaluator should translate
  3353. {\if\edition\racketEd
  3354. \[
  3355. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3356. \code{(+ 2 (read))}
  3357. \]
  3358. \fi}
  3359. {\if\edition\pythonEd
  3360. \[
  3361. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3362. \code{2 + input\_int()}
  3363. \]
  3364. \fi}
  3365. To accomplish this, the \code{pe\_exp} function should produce output
  3366. in the form of the $\itm{residual}$ non-terminal of the following
  3367. grammar. The idea is that when processing an addition expression, we
  3368. can always produce either 1) an integer constant, 2) an addition
  3369. expression with an integer constant on the left-hand side but not the
  3370. right-hand side, or 3) or an addition expression in which neither
  3371. subexpression is a constant.
  3372. {\if\edition\racketEd
  3373. \[
  3374. \begin{array}{lcl}
  3375. \itm{inert} &::=& \Var
  3376. \MID \LP\key{read}\RP
  3377. \MID \LP\key{-} ~\Var\RP
  3378. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3379. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3380. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3381. \itm{residual} &::=& \Int
  3382. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3383. \MID \itm{inert}
  3384. \end{array}
  3385. \]
  3386. \fi}
  3387. {\if\edition\pythonEd
  3388. \[
  3389. \begin{array}{lcl}
  3390. \itm{inert} &::=& \Var
  3391. \MID \key{input\_int}\LP\RP
  3392. \MID \key{-} \Var
  3393. \MID \key{-} \key{input\_int}\LP\RP
  3394. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3395. \itm{residual} &::=& \Int
  3396. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3397. \MID \itm{inert}
  3398. \end{array}
  3399. \]
  3400. \fi}
  3401. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3402. inputs are $\itm{residual}$ expressions and they should return
  3403. $\itm{residual}$ expressions. Once the improvements are complete,
  3404. make sure that your compiler still passes all of the tests. After
  3405. all, fast code is useless if it produces incorrect results!
  3406. \end{exercise}
  3407. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3408. \chapter{Register Allocation}
  3409. \label{ch:register-allocation-Lvar}
  3410. \index{subject}{register allocation}
  3411. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3412. stack. In this chapter we learn how to improve the performance of the
  3413. generated code by assigning some variables to registers. The CPU can
  3414. access a register in a single cycle, whereas accessing the stack can
  3415. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3416. serves as a running example. The source program is on the left and the
  3417. output of instruction selection is on the right. The program is almost
  3418. in the x86 assembly language but it still uses variables.
  3419. \begin{figure}
  3420. \begin{minipage}{0.45\textwidth}
  3421. Example \LangVar{} program:
  3422. % var_test_28.rkt
  3423. {\if\edition\racketEd
  3424. \begin{lstlisting}
  3425. (let ([v 1])
  3426. (let ([w 42])
  3427. (let ([x (+ v 7)])
  3428. (let ([y x])
  3429. (let ([z (+ x w)])
  3430. (+ z (- y)))))))
  3431. \end{lstlisting}
  3432. \fi}
  3433. {\if\edition\pythonEd
  3434. \begin{lstlisting}
  3435. v = 1
  3436. w = 42
  3437. x = v + 7
  3438. y = x
  3439. z = x + w
  3440. print(z + (- y))
  3441. \end{lstlisting}
  3442. \fi}
  3443. \end{minipage}
  3444. \begin{minipage}{0.45\textwidth}
  3445. After instruction selection:
  3446. {\if\edition\racketEd
  3447. \begin{lstlisting}
  3448. locals-types:
  3449. x : Integer, y : Integer,
  3450. z : Integer, t : Integer,
  3451. v : Integer, w : Integer
  3452. start:
  3453. movq $1, v
  3454. movq $42, w
  3455. movq v, x
  3456. addq $7, x
  3457. movq x, y
  3458. movq x, z
  3459. addq w, z
  3460. movq y, t
  3461. negq t
  3462. movq z, %rax
  3463. addq t, %rax
  3464. jmp conclusion
  3465. \end{lstlisting}
  3466. \fi}
  3467. {\if\edition\pythonEd
  3468. \begin{lstlisting}
  3469. movq $1, v
  3470. movq $42, w
  3471. movq v, x
  3472. addq $7, x
  3473. movq x, y
  3474. movq x, z
  3475. addq w, z
  3476. movq y, tmp_0
  3477. negq tmp_0
  3478. movq z, tmp_1
  3479. addq tmp_0, tmp_1
  3480. movq tmp_1, %rdi
  3481. callq print_int
  3482. \end{lstlisting}
  3483. \fi}
  3484. \end{minipage}
  3485. \caption{A running example for register allocation.}
  3486. \label{fig:reg-eg}
  3487. \end{figure}
  3488. The goal of register allocation is to fit as many variables into
  3489. registers as possible. Some programs have more variables than
  3490. registers so we cannot always map each variable to a different
  3491. register. Fortunately, it is common for different variables to be
  3492. needed during different periods of time during program execution, and
  3493. in such cases several variables can be mapped to the same register.
  3494. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3495. After the variable \code{x} is moved to \code{z} it is no longer
  3496. needed. Variable \code{z}, on the other hand, is used only after this
  3497. point, so \code{x} and \code{z} could share the same register. The
  3498. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3499. where a variable is needed. Once we have that information, we compute
  3500. which variables are needed at the same time, i.e., which ones
  3501. \emph{interfere} with each other, and represent this relation as an
  3502. undirected graph whose vertices are variables and edges indicate when
  3503. two variables interfere (Section~\ref{sec:build-interference}). We
  3504. then model register allocation as a graph coloring problem
  3505. (Section~\ref{sec:graph-coloring}).
  3506. If we run out of registers despite these efforts, we place the
  3507. remaining variables on the stack, similar to what we did in
  3508. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3509. assigning a variable to a stack location. The decision to spill a
  3510. variable is handled as part of the graph coloring process.
  3511. We make the simplifying assumption that each variable is assigned to
  3512. one location (a register or stack address). A more sophisticated
  3513. approach is to assign a variable to one or more locations in different
  3514. regions of the program. For example, if a variable is used many times
  3515. in short sequence and then only used again after many other
  3516. instructions, it could be more efficient to assign the variable to a
  3517. register during the initial sequence and then move it to the stack for
  3518. the rest of its lifetime. We refer the interested reader to
  3519. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3520. approach.
  3521. % discuss prioritizing variables based on how much they are used.
  3522. \section{Registers and Calling Conventions}
  3523. \label{sec:calling-conventions}
  3524. \index{subject}{calling conventions}
  3525. As we perform register allocation, we need to be aware of the
  3526. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3527. functions calls are performed in x86.
  3528. %
  3529. Even though \LangVar{} does not include programmer-defined functions,
  3530. our generated code includes a \code{main} function that is called by
  3531. the operating system and our generated code contains calls to the
  3532. \code{read\_int} function.
  3533. Function calls require coordination between two pieces of code that
  3534. may be written by different programmers or generated by different
  3535. compilers. Here we follow the System V calling conventions that are
  3536. used by the GNU C compiler on Linux and
  3537. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3538. %
  3539. The calling conventions include rules about how functions share the
  3540. use of registers. In particular, the caller is responsible for freeing
  3541. up some registers prior to the function call for use by the callee.
  3542. These are called the \emph{caller-saved registers}
  3543. \index{subject}{caller-saved registers}
  3544. and they are
  3545. \begin{lstlisting}
  3546. rax rcx rdx rsi rdi r8 r9 r10 r11
  3547. \end{lstlisting}
  3548. On the other hand, the callee is responsible for preserving the values
  3549. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3550. which are
  3551. \begin{lstlisting}
  3552. rsp rbp rbx r12 r13 r14 r15
  3553. \end{lstlisting}
  3554. We can think about this caller/callee convention from two points of
  3555. view, the caller view and the callee view:
  3556. \begin{itemize}
  3557. \item The caller should assume that all the caller-saved registers get
  3558. overwritten with arbitrary values by the callee. On the other hand,
  3559. the caller can safely assume that all the callee-saved registers
  3560. contain the same values after the call that they did before the
  3561. call.
  3562. \item The callee can freely use any of the caller-saved registers.
  3563. However, if the callee wants to use a callee-saved register, the
  3564. callee must arrange to put the original value back in the register
  3565. prior to returning to the caller. This can be accomplished by saving
  3566. the value to the stack in the prelude of the function and restoring
  3567. the value in the conclusion of the function.
  3568. \end{itemize}
  3569. In x86, registers are also used for passing arguments to a function
  3570. and for the return value. In particular, the first six arguments to a
  3571. function are passed in the following six registers, in this order.
  3572. \begin{lstlisting}
  3573. rdi rsi rdx rcx r8 r9
  3574. \end{lstlisting}
  3575. If there are more than six arguments, then the convention is to use
  3576. space on the frame of the caller for the rest of the
  3577. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3578. need more than six arguments.
  3579. %
  3580. \racket{For now, the only function we care about is \code{read\_int}
  3581. and it takes zero arguments.}
  3582. %
  3583. \python{For now, the only functions we care about are \code{read\_int}
  3584. and \code{print\_int}, which take zero and one argument, respectively.}
  3585. %
  3586. The register \code{rax} is used for the return value of a function.
  3587. The next question is how these calling conventions impact register
  3588. allocation. Consider the \LangVar{} program in
  3589. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3590. example from the caller point of view and then from the callee point
  3591. of view.
  3592. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3593. is in use during the second call to \READOP{}, so we need to make sure
  3594. that the value in \code{x} does not get accidentally wiped out by the
  3595. call to \READOP{}. One obvious approach is to save all the values in
  3596. caller-saved registers to the stack prior to each function call, and
  3597. restore them after each call. That way, if the register allocator
  3598. chooses to assign \code{x} to a caller-saved register, its value will
  3599. be preserved across the call to \READOP{}. However, saving and
  3600. restoring to the stack is relatively slow. If \code{x} is not used
  3601. many times, it may be better to assign \code{x} to a stack location in
  3602. the first place. Or better yet, if we can arrange for \code{x} to be
  3603. placed in a callee-saved register, then it won't need to be saved and
  3604. restored during function calls.
  3605. The approach that we recommend for variables that are in use during a
  3606. function call is to either assign them to callee-saved registers or to
  3607. spill them to the stack. On the other hand, for variables that are not
  3608. in use during a function call, we try the following alternatives in
  3609. order 1) look for an available caller-saved register (to leave room
  3610. for other variables in the callee-saved register), 2) look for a
  3611. callee-saved register, and 3) spill the variable to the stack.
  3612. It is straightforward to implement this approach in a graph coloring
  3613. register allocator. First, we know which variables are in use during
  3614. every function call because we compute that information for every
  3615. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3616. we build the interference graph
  3617. (Section~\ref{sec:build-interference}), we can place an edge between
  3618. each of these call-live variables and the caller-saved registers in
  3619. the interference graph. This will prevent the graph coloring algorithm
  3620. from assigning them to caller-saved registers.
  3621. Returning to the example in
  3622. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3623. generated x86 code on the right-hand side. Notice that variable
  3624. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3625. is already in a safe place during the second call to
  3626. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3627. \code{rcx}, a caller-saved register, because there are no function
  3628. calls in the remainder of the block.
  3629. Next we analyze the example from the callee point of view, focusing on
  3630. the prelude and conclusion of the \code{main} function. As usual the
  3631. prelude begins with saving the \code{rbp} register to the stack and
  3632. setting the \code{rbp} to the current stack pointer. We now know why
  3633. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3634. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3635. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3636. (\code{x}). The other callee-saved registers are not saved in the
  3637. prelude because they are not used. The prelude subtracts 8 bytes from
  3638. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3639. conclusion, we see that \code{rbx} is restored from the stack with a
  3640. \code{popq} instruction.
  3641. \index{subject}{prelude}\index{subject}{conclusion}
  3642. \begin{figure}[tp]
  3643. \begin{minipage}{0.45\textwidth}
  3644. Example \LangVar{} program:
  3645. %var_test_14.rkt
  3646. {\if\edition\racketEd
  3647. \begin{lstlisting}
  3648. (let ([x (read)])
  3649. (let ([y (read)])
  3650. (+ (+ x y) 42)))
  3651. \end{lstlisting}
  3652. \fi}
  3653. {\if\edition\pythonEd
  3654. \begin{lstlisting}
  3655. x = input_int()
  3656. y = input_int()
  3657. print((x + y) + 42)
  3658. \end{lstlisting}
  3659. \fi}
  3660. \end{minipage}
  3661. \begin{minipage}{0.45\textwidth}
  3662. Generated x86 assembly:
  3663. {\if\edition\racketEd
  3664. \begin{lstlisting}
  3665. start:
  3666. callq read_int
  3667. movq %rax, %rbx
  3668. callq read_int
  3669. movq %rax, %rcx
  3670. addq %rcx, %rbx
  3671. movq %rbx, %rax
  3672. addq $42, %rax
  3673. jmp _conclusion
  3674. .globl main
  3675. main:
  3676. pushq %rbp
  3677. movq %rsp, %rbp
  3678. pushq %rbx
  3679. subq $8, %rsp
  3680. jmp start
  3681. conclusion:
  3682. addq $8, %rsp
  3683. popq %rbx
  3684. popq %rbp
  3685. retq
  3686. \end{lstlisting}
  3687. \fi}
  3688. {\if\edition\pythonEd
  3689. \begin{lstlisting}
  3690. .globl main
  3691. main:
  3692. pushq %rbp
  3693. movq %rsp, %rbp
  3694. pushq %rbx
  3695. subq $8, %rsp
  3696. callq read_int
  3697. movq %rax, %rbx
  3698. callq read_int
  3699. movq %rax, %rcx
  3700. movq %rbx, %rdx
  3701. addq %rcx, %rdx
  3702. movq %rdx, %rcx
  3703. addq $42, %rcx
  3704. movq %rcx, %rdi
  3705. callq print_int
  3706. addq $8, %rsp
  3707. popq %rbx
  3708. popq %rbp
  3709. retq
  3710. \end{lstlisting}
  3711. \fi}
  3712. \end{minipage}
  3713. \caption{An example with function calls.}
  3714. \label{fig:example-calling-conventions}
  3715. \end{figure}
  3716. %\clearpage
  3717. \section{Liveness Analysis}
  3718. \label{sec:liveness-analysis-Lvar}
  3719. \index{subject}{liveness analysis}
  3720. The \code{uncover\_live} \racket{pass}\python{function}
  3721. performs \emph{liveness analysis}, that
  3722. is, it discovers which variables are in-use in different regions of a
  3723. program.
  3724. %
  3725. A variable or register is \emph{live} at a program point if its
  3726. current value is used at some later point in the program. We refer to
  3727. variables, stack locations, and registers collectively as
  3728. \emph{locations}.
  3729. %
  3730. Consider the following code fragment in which there are two writes to
  3731. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3732. \begin{center}
  3733. \begin{minipage}{0.96\textwidth}
  3734. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3735. movq $5, a
  3736. movq $30, b
  3737. movq a, c
  3738. movq $10, b
  3739. addq b, c
  3740. \end{lstlisting}
  3741. \end{minipage}
  3742. \end{center}
  3743. The answer is no because \code{a} is live from line 1 to 3 and
  3744. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3745. line 2 is never used because it is overwritten (line 4) before the
  3746. next read (line 5).
  3747. The live locations can be computed by traversing the instruction
  3748. sequence back to front (i.e., backwards in execution order). Let
  3749. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3750. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3751. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3752. locations before instruction $I_k$.
  3753. \racket{We recommend representing these
  3754. sets with the Racket \code{set} data structure described in
  3755. Figure~\ref{fig:set}.}
  3756. \python{We recommend representing these sets with the Python
  3757. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3758. data structure.}
  3759. {\if\edition\racketEd
  3760. \begin{figure}[tp]
  3761. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3762. \small
  3763. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3764. A \emph{set} is an unordered collection of elements without duplicates.
  3765. Here are some of the operations defined on sets.
  3766. \index{subject}{set}
  3767. \begin{description}
  3768. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3769. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3770. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3771. difference of the two sets.
  3772. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3773. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3774. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3775. \end{description}
  3776. \end{tcolorbox}
  3777. %\end{wrapfigure}
  3778. \caption{The \code{set} data structure.}
  3779. \label{fig:set}
  3780. \end{figure}
  3781. \fi}
  3782. The live locations after an instruction are always the same as the
  3783. live locations before the next instruction.
  3784. \index{subject}{live-after} \index{subject}{live-before}
  3785. \begin{equation} \label{eq:live-after-before-next}
  3786. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3787. \end{equation}
  3788. To start things off, there are no live locations after the last
  3789. instruction, so
  3790. \begin{equation}\label{eq:live-last-empty}
  3791. L_{\mathsf{after}}(n) = \emptyset
  3792. \end{equation}
  3793. We then apply the following rule repeatedly, traversing the
  3794. instruction sequence back to front.
  3795. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3796. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3797. \end{equation}
  3798. where $W(k)$ are the locations written to by instruction $I_k$ and
  3799. $R(k)$ are the locations read by instruction $I_k$.
  3800. {\if\edition\racketEd
  3801. There is a special case for \code{jmp} instructions. The locations
  3802. that are live before a \code{jmp} should be the locations in
  3803. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3804. maintaining an alist named \code{label->live} that maps each label to
  3805. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3806. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3807. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3808. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3809. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3810. \fi}
  3811. Let us walk through the above example, applying these formulas
  3812. starting with the instruction on line 5. We collect the answers in
  3813. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3814. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3815. instruction (formula~\ref{eq:live-last-empty}). The
  3816. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3817. because it reads from variables \code{b} and \code{c}
  3818. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3819. \[
  3820. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3821. \]
  3822. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3823. the live-before set from line 5 to be the live-after set for this
  3824. instruction (formula~\ref{eq:live-after-before-next}).
  3825. \[
  3826. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3827. \]
  3828. This move instruction writes to \code{b} and does not read from any
  3829. variables, so we have the following live-before set
  3830. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3831. \[
  3832. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3833. \]
  3834. The live-before for instruction \code{movq a, c}
  3835. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3836. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3837. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3838. variable that is not live and does not read from a variable.
  3839. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3840. because it writes to variable \code{a}.
  3841. \begin{figure}[tbp]
  3842. \begin{minipage}{0.45\textwidth}
  3843. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3844. movq $5, a
  3845. movq $30, b
  3846. movq a, c
  3847. movq $10, b
  3848. addq b, c
  3849. \end{lstlisting}
  3850. \end{minipage}
  3851. \vrule\hspace{10pt}
  3852. \begin{minipage}{0.45\textwidth}
  3853. \begin{align*}
  3854. L_{\mathsf{before}}(1)= \emptyset,
  3855. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3856. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3857. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3858. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3859. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3860. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3861. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3862. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3863. L_{\mathsf{after}}(5)= \emptyset
  3864. \end{align*}
  3865. \end{minipage}
  3866. \caption{Example output of liveness analysis on a short example.}
  3867. \label{fig:liveness-example-0}
  3868. \end{figure}
  3869. \begin{exercise}\normalfont
  3870. Perform liveness analysis on the running example in
  3871. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3872. sets for each instruction. Compare your answers to the solution
  3873. shown in Figure~\ref{fig:live-eg}.
  3874. \end{exercise}
  3875. \begin{figure}[tp]
  3876. \hspace{20pt}
  3877. \begin{minipage}{0.45\textwidth}
  3878. {\if\edition\racketEd
  3879. \begin{lstlisting}
  3880. |$\{\ttm{rsp}\}$|
  3881. movq $1, v
  3882. |$\{\ttm{v},\ttm{rsp}\}$|
  3883. movq $42, w
  3884. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3885. movq v, x
  3886. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3887. addq $7, x
  3888. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3889. movq x, y
  3890. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3891. movq x, z
  3892. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3893. addq w, z
  3894. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3895. movq y, t
  3896. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3897. negq t
  3898. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3899. movq z, %rax
  3900. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3901. addq t, %rax
  3902. |$\{\ttm{rax},\ttm{rsp}\}$|
  3903. jmp conclusion
  3904. \end{lstlisting}
  3905. \fi}
  3906. {\if\edition\pythonEd
  3907. \begin{lstlisting}
  3908. movq $1, v
  3909. |$\{\ttm{v}\}$|
  3910. movq $42, w
  3911. |$\{\ttm{w}, \ttm{v}\}$|
  3912. movq v, x
  3913. |$\{\ttm{w}, \ttm{x}\}$|
  3914. addq $7, x
  3915. |$\{\ttm{w}, \ttm{x}\}$|
  3916. movq x, y
  3917. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  3918. movq x, z
  3919. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  3920. addq w, z
  3921. |$\{\ttm{y}, \ttm{z}\}$|
  3922. movq y, tmp_0
  3923. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3924. negq tmp_0
  3925. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3926. movq z, tmp_1
  3927. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  3928. addq tmp_0, tmp_1
  3929. |$\{\ttm{tmp\_1}\}$|
  3930. movq tmp_1, %rdi
  3931. |$\{\ttm{rdi}\}$|
  3932. callq print_int
  3933. |$\{\}$|
  3934. \end{lstlisting}
  3935. \fi}
  3936. \end{minipage}
  3937. \caption{The running example annotated with live-after sets.}
  3938. \label{fig:live-eg}
  3939. \end{figure}
  3940. \begin{exercise}\normalfont
  3941. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  3942. %
  3943. \racket{Store the sequence of live-after sets in the $\itm{info}$
  3944. field of the \code{Block} structure.}
  3945. %
  3946. \python{Return a dictionary that maps each instruction to its
  3947. live-after set.}
  3948. %
  3949. \racket{We recommend creating an auxiliary function that takes a list
  3950. of instructions and an initial live-after set (typically empty) and
  3951. returns the list of live-after sets.}
  3952. %
  3953. We recommend creating auxiliary functions to 1) compute the set
  3954. of locations that appear in an \Arg{}, 2) compute the locations read
  3955. by an instruction (the $R$ function), and 3) the locations written by
  3956. an instruction (the $W$ function). The \code{callq} instruction should
  3957. include all of the caller-saved registers in its write-set $W$ because
  3958. the calling convention says that those registers may be written to
  3959. during the function call. Likewise, the \code{callq} instruction
  3960. should include the appropriate argument-passing registers in its
  3961. read-set $R$, depending on the arity of the function being
  3962. called. (This is why the abstract syntax for \code{callq} includes the
  3963. arity.)
  3964. \end{exercise}
  3965. %\clearpage
  3966. \section{Build the Interference Graph}
  3967. \label{sec:build-interference}
  3968. {\if\edition\racketEd
  3969. \begin{figure}[tp]
  3970. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3971. \small
  3972. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3973. A \emph{graph} is a collection of vertices and edges where each
  3974. edge connects two vertices. A graph is \emph{directed} if each
  3975. edge points from a source to a target. Otherwise the graph is
  3976. \emph{undirected}.
  3977. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3978. \begin{description}
  3979. %% We currently don't use directed graphs. We instead use
  3980. %% directed multi-graphs. -Jeremy
  3981. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3982. directed graph from a list of edges. Each edge is a list
  3983. containing the source and target vertex.
  3984. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3985. undirected graph from a list of edges. Each edge is represented by
  3986. a list containing two vertices.
  3987. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3988. inserts a vertex into the graph.
  3989. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3990. inserts an edge between the two vertices.
  3991. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3992. returns a sequence of vertices adjacent to the vertex.
  3993. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3994. returns a sequence of all vertices in the graph.
  3995. \end{description}
  3996. \end{tcolorbox}
  3997. %\end{wrapfigure}
  3998. \caption{The Racket \code{graph} package.}
  3999. \label{fig:graph}
  4000. \end{figure}
  4001. \fi}
  4002. Based on the liveness analysis, we know where each location is live.
  4003. However, during register allocation, we need to answer questions of
  4004. the specific form: are locations $u$ and $v$ live at the same time?
  4005. (And therefore cannot be assigned to the same register.) To make this
  4006. question more efficient to answer, we create an explicit data
  4007. structure, an \emph{interference graph}\index{subject}{interference
  4008. graph}. An interference graph is an undirected graph that has an
  4009. edge between two locations if they are live at the same time, that is,
  4010. if they interfere with each other.
  4011. %
  4012. \racket{We recommend using the Racket \code{graph} package
  4013. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4014. %
  4015. \python{We provide implementations of directed and undirected graph
  4016. data structures in the file \code{graph.py} of the support code.}
  4017. A straightforward way to compute the interference graph is to look at
  4018. the set of live locations between each instruction and add an edge to
  4019. the graph for every pair of variables in the same set. This approach
  4020. is less than ideal for two reasons. First, it can be expensive because
  4021. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4022. locations. Second, in the special case where two locations hold the
  4023. same value (because one was assigned to the other), they can be live
  4024. at the same time without interfering with each other.
  4025. A better way to compute the interference graph is to focus on
  4026. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4027. must not overwrite something in a live location. So for each
  4028. instruction, we create an edge between the locations being written to
  4029. and the live locations. (Except that one should not create self
  4030. edges.) Note that for the \key{callq} instruction, we consider all of
  4031. the caller-saved registers as being written to, so an edge is added
  4032. between every live variable and every caller-saved register. Also, for
  4033. \key{movq} there is the above-mentioned special case to deal with. If
  4034. a live variable $v$ is the same as the source of the \key{movq}, then
  4035. there is no need to add an edge between $v$ and the destination,
  4036. because they both hold the same value.
  4037. %
  4038. So we have the following two rules.
  4039. \begin{enumerate}
  4040. \item If instruction $I_k$ is a move instruction, \key{movq} $s$\key{,}
  4041. $d$, then add the edge $(d,v)$ for every $v \in
  4042. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  4043. \item For any other instruction $I_k$, for every $d \in W(k)$
  4044. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  4045. %% \item If instruction $I_k$ is an arithmetic instruction such as
  4046. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  4047. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  4048. %% \item If instruction $I_k$ is of the form \key{callq}
  4049. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  4050. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  4051. \end{enumerate}
  4052. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4053. the above rules to each instruction. We highlight a few of the
  4054. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4055. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4056. so \code{v} interferes with \code{rsp}.}
  4057. %
  4058. \python{The first instruction is \lstinline{movq $1, v} and the
  4059. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4060. no interference because $\ttm{v}$ is the destination of the move.}
  4061. %
  4062. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4063. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4064. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4065. %
  4066. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4067. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4068. $\ttm{x}$ interferes with \ttm{w}.}
  4069. %
  4070. \racket{The next instruction is \lstinline{movq x, y} and the
  4071. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4072. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4073. \ttm{x} because \ttm{x} is the source of the move and therefore
  4074. \ttm{x} and \ttm{y} hold the same value.}
  4075. %
  4076. \python{The next instruction is \lstinline{movq x, y} and the
  4077. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4078. applies, so \ttm{y} interferes with \ttm{w} but not
  4079. \ttm{x} because \ttm{x} is the source of the move and therefore
  4080. \ttm{x} and \ttm{y} hold the same value.}
  4081. %
  4082. Figure~\ref{fig:interference-results} lists the interference results
  4083. for all of the instructions and the resulting interference graph is
  4084. shown in Figure~\ref{fig:interfere}.
  4085. \begin{figure}[tbp]
  4086. \begin{quote}
  4087. {\if\edition\racketEd
  4088. \begin{tabular}{ll}
  4089. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4090. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4091. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4092. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4093. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4094. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4095. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4096. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4097. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4098. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4099. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4100. \lstinline!jmp conclusion!& no interference.
  4101. \end{tabular}
  4102. \fi}
  4103. {\if\edition\pythonEd
  4104. \begin{tabular}{ll}
  4105. \lstinline!movq $1, v!& no interference\\
  4106. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4107. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4108. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4109. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4110. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4111. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4112. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4113. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4114. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4115. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4116. \lstinline!movq tmp_1, %rdi! & no interference \\
  4117. \lstinline!callq print_int!& no interference.
  4118. \end{tabular}
  4119. \fi}
  4120. \end{quote}
  4121. \caption{Interference results for the running example.}
  4122. \label{fig:interference-results}
  4123. \end{figure}
  4124. \begin{figure}[tbp]
  4125. \large
  4126. {\if\edition\racketEd
  4127. \[
  4128. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4129. \node (rax) at (0,0) {$\ttm{rax}$};
  4130. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4131. \node (t1) at (0,2) {$\ttm{t}$};
  4132. \node (z) at (3,2) {$\ttm{z}$};
  4133. \node (x) at (6,2) {$\ttm{x}$};
  4134. \node (y) at (3,0) {$\ttm{y}$};
  4135. \node (w) at (6,0) {$\ttm{w}$};
  4136. \node (v) at (9,0) {$\ttm{v}$};
  4137. \draw (t1) to (rax);
  4138. \draw (t1) to (z);
  4139. \draw (z) to (y);
  4140. \draw (z) to (w);
  4141. \draw (x) to (w);
  4142. \draw (y) to (w);
  4143. \draw (v) to (w);
  4144. \draw (v) to (rsp);
  4145. \draw (w) to (rsp);
  4146. \draw (x) to (rsp);
  4147. \draw (y) to (rsp);
  4148. \path[-.,bend left=15] (z) edge node {} (rsp);
  4149. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4150. \draw (rax) to (rsp);
  4151. \end{tikzpicture}
  4152. \]
  4153. \fi}
  4154. {\if\edition\pythonEd
  4155. \[
  4156. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4157. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4158. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4159. \node (z) at (3,2) {$\ttm{z}$};
  4160. \node (x) at (6,2) {$\ttm{x}$};
  4161. \node (y) at (3,0) {$\ttm{y}$};
  4162. \node (w) at (6,0) {$\ttm{w}$};
  4163. \node (v) at (9,0) {$\ttm{v}$};
  4164. \draw (t0) to (t1);
  4165. \draw (t0) to (z);
  4166. \draw (z) to (y);
  4167. \draw (z) to (w);
  4168. \draw (x) to (w);
  4169. \draw (y) to (w);
  4170. \draw (v) to (w);
  4171. \end{tikzpicture}
  4172. \]
  4173. \fi}
  4174. \caption{The interference graph of the example program.}
  4175. \label{fig:interfere}
  4176. \end{figure}
  4177. %% Our next concern is to choose a data structure for representing the
  4178. %% interference graph. There are many choices for how to represent a
  4179. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4180. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4181. %% data structure is to study the algorithm that uses the data structure,
  4182. %% determine what operations need to be performed, and then choose the
  4183. %% data structure that provide the most efficient implementations of
  4184. %% those operations. Often times the choice of data structure can have an
  4185. %% effect on the time complexity of the algorithm, as it does here. If
  4186. %% you skim the next section, you will see that the register allocation
  4187. %% algorithm needs to ask the graph for all of its vertices and, given a
  4188. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4189. %% correct choice of graph representation is that of an adjacency
  4190. %% list. There are helper functions in \code{utilities.rkt} for
  4191. %% representing graphs using the adjacency list representation:
  4192. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4193. %% (Appendix~\ref{appendix:utilities}).
  4194. %% %
  4195. %% \margincomment{\footnotesize To do: change to use the
  4196. %% Racket graph library. \\ --Jeremy}
  4197. %% %
  4198. %% In particular, those functions use a hash table to map each vertex to
  4199. %% the set of adjacent vertices, and the sets are represented using
  4200. %% Racket's \key{set}, which is also a hash table.
  4201. \begin{exercise}\normalfont
  4202. \racket{Implement the compiler pass named \code{build\_interference} according
  4203. to the algorithm suggested above. We recommend using the Racket
  4204. \code{graph} package to create and inspect the interference graph.
  4205. The output graph of this pass should be stored in the $\itm{info}$ field of
  4206. the program, under the key \code{conflicts}.}
  4207. %
  4208. \python{Implement a function named \code{build\_interference}
  4209. according to the algorithm suggested above that
  4210. returns the interference graph.}
  4211. \end{exercise}
  4212. \section{Graph Coloring via Sudoku}
  4213. \label{sec:graph-coloring}
  4214. \index{subject}{graph coloring}
  4215. \index{subject}{Sudoku}
  4216. \index{subject}{color}
  4217. We come to the main event, mapping variables to registers and stack
  4218. locations. Variables that interfere with each other must be mapped to
  4219. different locations. In terms of the interference graph, this means
  4220. that adjacent vertices must be mapped to different locations. If we
  4221. think of locations as colors, the register allocation problem becomes
  4222. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4223. The reader may be more familiar with the graph coloring problem than he
  4224. or she realizes; the popular game of Sudoku is an instance of the
  4225. graph coloring problem. The following describes how to build a graph
  4226. out of an initial Sudoku board.
  4227. \begin{itemize}
  4228. \item There is one vertex in the graph for each Sudoku square.
  4229. \item There is an edge between two vertices if the corresponding squares
  4230. are in the same row, in the same column, or if the squares are in
  4231. the same $3\times 3$ region.
  4232. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4233. \item Based on the initial assignment of numbers to squares in the
  4234. Sudoku board, assign the corresponding colors to the corresponding
  4235. vertices in the graph.
  4236. \end{itemize}
  4237. If you can color the remaining vertices in the graph with the nine
  4238. colors, then you have also solved the corresponding game of Sudoku.
  4239. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4240. the corresponding graph with colored vertices. We map the Sudoku
  4241. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4242. sampling of the vertices (the colored ones) because showing edges for
  4243. all of the vertices would make the graph unreadable.
  4244. \begin{figure}[tbp]
  4245. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4246. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4247. \caption{A Sudoku game board and the corresponding colored graph.}
  4248. \label{fig:sudoku-graph}
  4249. \end{figure}
  4250. Some techniques for playing Sudoku correspond to heuristics used in
  4251. graph coloring algorithms. For example, one of the basic techniques
  4252. for Sudoku is called Pencil Marks. The idea is to use a process of
  4253. elimination to determine what numbers are no longer available for a
  4254. square and write down those numbers in the square (writing very
  4255. small). For example, if the number $1$ is assigned to a square, then
  4256. write the pencil mark $1$ in all the squares in the same row, column,
  4257. and region to indicate that $1$ is no longer an option for those other
  4258. squares.
  4259. %
  4260. The Pencil Marks technique corresponds to the notion of
  4261. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4262. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4263. are no longer available. In graph terminology, we have the following
  4264. definition:
  4265. \begin{equation*}
  4266. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4267. \text{ and } \mathrm{color}(v) = c \}
  4268. \end{equation*}
  4269. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4270. edge with $u$.
  4271. The Pencil Marks technique leads to a simple strategy for filling in
  4272. numbers: if there is a square with only one possible number left, then
  4273. choose that number! But what if there are no squares with only one
  4274. possibility left? One brute-force approach is to try them all: choose
  4275. the first one and if that ultimately leads to a solution, great. If
  4276. not, backtrack and choose the next possibility. One good thing about
  4277. Pencil Marks is that it reduces the degree of branching in the search
  4278. tree. Nevertheless, backtracking can be terribly time consuming. One
  4279. way to reduce the amount of backtracking is to use the
  4280. most-constrained-first heuristic (aka. minimum remaining
  4281. values)~\citep{Russell2003}. That is, when choosing a square, always
  4282. choose one with the fewest possibilities left (the vertex with the
  4283. highest saturation). The idea is that choosing highly constrained
  4284. squares earlier rather than later is better because later on there may
  4285. not be any possibilities left in the highly saturated squares.
  4286. However, register allocation is easier than Sudoku because the
  4287. register allocator can fall back to assigning variables to stack
  4288. locations when the registers run out. Thus, it makes sense to replace
  4289. backtracking with greedy search: make the best choice at the time and
  4290. keep going. We still wish to minimize the number of colors needed, so
  4291. we use the most-constrained-first heuristic in the greedy search.
  4292. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4293. algorithm for register allocation based on saturation and the
  4294. most-constrained-first heuristic. It is roughly equivalent to the
  4295. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4296. %,Gebremedhin:1999fk,Omari:2006uq
  4297. Just as in Sudoku, the algorithm represents colors with integers. The
  4298. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4299. for register allocation. The integers $k$ and larger correspond to
  4300. stack locations. The registers that are not used for register
  4301. allocation, such as \code{rax}, are assigned to negative integers. In
  4302. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4303. %% One might wonder why we include registers at all in the liveness
  4304. %% analysis and interference graph. For example, we never allocate a
  4305. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4306. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  4307. %% to use register for passing arguments to functions, it will be
  4308. %% necessary for those registers to appear in the interference graph
  4309. %% because those registers will also be assigned to variables, and we
  4310. %% don't want those two uses to encroach on each other. Regarding
  4311. %% registers such as \code{rax} and \code{rsp} that are not used for
  4312. %% variables, we could omit them from the interference graph but that
  4313. %% would require adding special cases to our algorithm, which would
  4314. %% complicate the logic for little gain.
  4315. \begin{figure}[btp]
  4316. \centering
  4317. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4318. Algorithm: DSATUR
  4319. Input: a graph |$G$|
  4320. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4321. |$W \gets \mathrm{vertices}(G)$|
  4322. while |$W \neq \emptyset$| do
  4323. pick a vertex |$u$| from |$W$| with the highest saturation,
  4324. breaking ties randomly
  4325. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4326. |$\mathrm{color}[u] \gets c$|
  4327. |$W \gets W - \{u\}$|
  4328. \end{lstlisting}
  4329. \caption{The saturation-based greedy graph coloring algorithm.}
  4330. \label{fig:satur-algo}
  4331. \end{figure}
  4332. {\if\edition\racketEd
  4333. With the DSATUR algorithm in hand, let us return to the running
  4334. example and consider how to color the interference graph in
  4335. Figure~\ref{fig:interfere}.
  4336. %
  4337. We start by assigning the register nodes to their own color. For
  4338. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4339. assigned $-2$. The variables are not yet colored, so they are
  4340. annotated with a dash. We then update the saturation for vertices that
  4341. are adjacent to a register, obtaining the following annotated
  4342. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4343. it interferes with both \code{rax} and \code{rsp}.
  4344. \[
  4345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4346. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4347. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4348. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4349. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4350. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4351. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4352. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4353. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4354. \draw (t1) to (rax);
  4355. \draw (t1) to (z);
  4356. \draw (z) to (y);
  4357. \draw (z) to (w);
  4358. \draw (x) to (w);
  4359. \draw (y) to (w);
  4360. \draw (v) to (w);
  4361. \draw (v) to (rsp);
  4362. \draw (w) to (rsp);
  4363. \draw (x) to (rsp);
  4364. \draw (y) to (rsp);
  4365. \path[-.,bend left=15] (z) edge node {} (rsp);
  4366. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4367. \draw (rax) to (rsp);
  4368. \end{tikzpicture}
  4369. \]
  4370. The algorithm says to select a maximally saturated vertex. So we pick
  4371. $\ttm{t}$ and color it with the first available integer, which is
  4372. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4373. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4374. \[
  4375. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4376. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4377. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4378. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4379. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4380. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4381. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4382. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4383. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4384. \draw (t1) to (rax);
  4385. \draw (t1) to (z);
  4386. \draw (z) to (y);
  4387. \draw (z) to (w);
  4388. \draw (x) to (w);
  4389. \draw (y) to (w);
  4390. \draw (v) to (w);
  4391. \draw (v) to (rsp);
  4392. \draw (w) to (rsp);
  4393. \draw (x) to (rsp);
  4394. \draw (y) to (rsp);
  4395. \path[-.,bend left=15] (z) edge node {} (rsp);
  4396. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4397. \draw (rax) to (rsp);
  4398. \end{tikzpicture}
  4399. \]
  4400. We repeat the process, selecting a maximally saturated vertex,
  4401. choosing is \code{z}, and color it with the first available number, which
  4402. is $1$. We add $1$ to the saturation for the neighboring vertices
  4403. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4404. \[
  4405. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4406. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4407. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4408. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4409. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4410. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4411. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4412. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4413. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4414. \draw (t1) to (rax);
  4415. \draw (t1) to (z);
  4416. \draw (z) to (y);
  4417. \draw (z) to (w);
  4418. \draw (x) to (w);
  4419. \draw (y) to (w);
  4420. \draw (v) to (w);
  4421. \draw (v) to (rsp);
  4422. \draw (w) to (rsp);
  4423. \draw (x) to (rsp);
  4424. \draw (y) to (rsp);
  4425. \path[-.,bend left=15] (z) edge node {} (rsp);
  4426. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4427. \draw (rax) to (rsp);
  4428. \end{tikzpicture}
  4429. \]
  4430. The most saturated vertices are now \code{w} and \code{y}. We color
  4431. \code{w} with the first available color, which is $0$.
  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\}$};
  4436. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4437. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4438. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4439. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4440. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4441. \node (v) at (10,0) {$\ttm{v}:-,\{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. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4459. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4460. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4461. and \code{z}, whose colors are $0$ and $1$ respectively.
  4462. \[
  4463. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4464. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4465. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4466. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4467. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4468. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4469. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4470. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4471. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4472. \draw (t1) to (rax);
  4473. \draw (t1) to (z);
  4474. \draw (z) to (y);
  4475. \draw (z) to (w);
  4476. \draw (x) to (w);
  4477. \draw (y) to (w);
  4478. \draw (v) to (w);
  4479. \draw (v) to (rsp);
  4480. \draw (w) to (rsp);
  4481. \draw (x) to (rsp);
  4482. \draw (y) to (rsp);
  4483. \path[-.,bend left=15] (z) edge node {} (rsp);
  4484. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4485. \draw (rax) to (rsp);
  4486. \end{tikzpicture}
  4487. \]
  4488. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4489. \[
  4490. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4491. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4492. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4493. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4494. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4495. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4496. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4497. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4498. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4499. \draw (t1) to (rax);
  4500. \draw (t1) to (z);
  4501. \draw (z) to (y);
  4502. \draw (z) to (w);
  4503. \draw (x) to (w);
  4504. \draw (y) to (w);
  4505. \draw (v) to (w);
  4506. \draw (v) to (rsp);
  4507. \draw (w) to (rsp);
  4508. \draw (x) to (rsp);
  4509. \draw (y) to (rsp);
  4510. \path[-.,bend left=15] (z) edge node {} (rsp);
  4511. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4512. \draw (rax) to (rsp);
  4513. \end{tikzpicture}
  4514. \]
  4515. In the last step of the algorithm, we color \code{x} with $1$.
  4516. \[
  4517. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4518. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4519. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4520. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4521. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4522. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4523. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4524. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4525. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4526. \draw (t1) to (rax);
  4527. \draw (t1) to (z);
  4528. \draw (z) to (y);
  4529. \draw (z) to (w);
  4530. \draw (x) to (w);
  4531. \draw (y) to (w);
  4532. \draw (v) to (w);
  4533. \draw (v) to (rsp);
  4534. \draw (w) to (rsp);
  4535. \draw (x) to (rsp);
  4536. \draw (y) to (rsp);
  4537. \path[-.,bend left=15] (z) edge node {} (rsp);
  4538. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4539. \draw (rax) to (rsp);
  4540. \end{tikzpicture}
  4541. \]
  4542. So we obtain the following coloring:
  4543. \[
  4544. \{
  4545. \ttm{rax} \mapsto -1,
  4546. \ttm{rsp} \mapsto -2,
  4547. \ttm{t} \mapsto 0,
  4548. \ttm{z} \mapsto 1,
  4549. \ttm{x} \mapsto 1,
  4550. \ttm{y} \mapsto 2,
  4551. \ttm{w} \mapsto 0,
  4552. \ttm{v} \mapsto 1
  4553. \}
  4554. \]
  4555. \fi}
  4556. %
  4557. {\if\edition\pythonEd
  4558. %
  4559. With the DSATUR algorithm in hand, let us return to the running
  4560. example and consider how to color the interference graph in
  4561. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4562. to indicate that it has not yet been assigned a color. The saturation
  4563. sets are also shown for each node; all of them start as the empty set.
  4564. (We do not include the register nodes in the graph below because there
  4565. were no interference edges involving registers in this program, but in
  4566. general there can be.)
  4567. %
  4568. \[
  4569. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4570. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4571. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4572. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4573. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4574. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4575. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4576. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4577. \draw (t0) to (t1);
  4578. \draw (t0) to (z);
  4579. \draw (z) to (y);
  4580. \draw (z) to (w);
  4581. \draw (x) to (w);
  4582. \draw (y) to (w);
  4583. \draw (v) to (w);
  4584. \end{tikzpicture}
  4585. \]
  4586. The algorithm says to select a maximally saturated vertex, but they
  4587. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4588. then color it with the first available integer, which is $0$. We mark
  4589. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4590. they interfere with $\ttm{tmp\_0}$.
  4591. \[
  4592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4593. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4594. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4595. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4596. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4597. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4598. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4599. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4600. \draw (t0) to (t1);
  4601. \draw (t0) to (z);
  4602. \draw (z) to (y);
  4603. \draw (z) to (w);
  4604. \draw (x) to (w);
  4605. \draw (y) to (w);
  4606. \draw (v) to (w);
  4607. \end{tikzpicture}
  4608. \]
  4609. We repeat the process. The most saturated vertices are \code{z} and
  4610. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4611. available number, which is $1$. We add $1$ to the saturation for the
  4612. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4613. \[
  4614. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4615. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4616. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4617. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4618. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4619. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4620. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4621. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4622. \draw (t0) to (t1);
  4623. \draw (t0) to (z);
  4624. \draw (z) to (y);
  4625. \draw (z) to (w);
  4626. \draw (x) to (w);
  4627. \draw (y) to (w);
  4628. \draw (v) to (w);
  4629. \end{tikzpicture}
  4630. \]
  4631. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4632. \code{y}. We color \code{w} with the first available color, which
  4633. is $0$.
  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}: -, \{0\}$};
  4638. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4639. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4640. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4641. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4642. \node (v) at (9,0) {$\ttm{v}: -, \{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. Now \code{y} is the most saturated, so we color it with $2$.
  4653. \[
  4654. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4655. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4656. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4657. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4658. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4659. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4660. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4661. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4662. \draw (t0) to (t1);
  4663. \draw (t0) to (z);
  4664. \draw (z) to (y);
  4665. \draw (z) to (w);
  4666. \draw (x) to (w);
  4667. \draw (y) to (w);
  4668. \draw (v) to (w);
  4669. \end{tikzpicture}
  4670. \]
  4671. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4672. We choose to color \code{v} with $1$.
  4673. \[
  4674. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4675. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4676. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4677. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4678. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4679. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4680. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4681. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4682. \draw (t0) to (t1);
  4683. \draw (t0) to (z);
  4684. \draw (z) to (y);
  4685. \draw (z) to (w);
  4686. \draw (x) to (w);
  4687. \draw (y) to (w);
  4688. \draw (v) to (w);
  4689. \end{tikzpicture}
  4690. \]
  4691. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4692. \[
  4693. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4694. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4695. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4696. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4697. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4698. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4699. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4700. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4701. \draw (t0) to (t1);
  4702. \draw (t0) to (z);
  4703. \draw (z) to (y);
  4704. \draw (z) to (w);
  4705. \draw (x) to (w);
  4706. \draw (y) to (w);
  4707. \draw (v) to (w);
  4708. \end{tikzpicture}
  4709. \]
  4710. So we obtain the following coloring:
  4711. \[
  4712. \{ \ttm{tmp\_0} \mapsto 0,
  4713. \ttm{tmp\_1} \mapsto 1,
  4714. \ttm{z} \mapsto 1,
  4715. \ttm{x} \mapsto 1,
  4716. \ttm{y} \mapsto 2,
  4717. \ttm{w} \mapsto 0,
  4718. \ttm{v} \mapsto 1 \}
  4719. \]
  4720. \fi}
  4721. We recommend creating an auxiliary function named \code{color\_graph}
  4722. that takes an interference graph and a list of all the variables in
  4723. the program. This function should return a mapping of variables to
  4724. their colors (represented as natural numbers). By creating this helper
  4725. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4726. when we add support for functions.
  4727. To prioritize the processing of highly saturated nodes inside the
  4728. \code{color\_graph} function, we recommend using the priority queue
  4729. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4730. addition, you will need to maintain a mapping from variables to their
  4731. ``handles'' in the priority queue so that you can notify the priority
  4732. queue when their saturation changes.}
  4733. {\if\edition\racketEd
  4734. \begin{figure}[tp]
  4735. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4736. \small
  4737. \begin{tcolorbox}[title=Priority Queue]
  4738. A \emph{priority queue} is a collection of items in which the
  4739. removal of items is governed by priority. In a ``min'' queue,
  4740. lower priority items are removed first. An implementation is in
  4741. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4742. queue} \index{subject}{minimum priority queue}
  4743. \begin{description}
  4744. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4745. priority queue that uses the $\itm{cmp}$ predicate to determine
  4746. whether its first argument has lower or equal priority to its
  4747. second argument.
  4748. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4749. items in the queue.
  4750. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4751. the item into the queue and returns a handle for the item in the
  4752. queue.
  4753. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4754. the lowest priority.
  4755. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4756. notifies the queue that the priority has decreased for the item
  4757. associated with the given handle.
  4758. \end{description}
  4759. \end{tcolorbox}
  4760. %\end{wrapfigure}
  4761. \caption{The priority queue data structure.}
  4762. \label{fig:priority-queue}
  4763. \end{figure}
  4764. \fi}
  4765. With the coloring complete, we finalize the assignment of variables to
  4766. registers and stack locations. We map the first $k$ colors to the $k$
  4767. registers and the rest of the colors to stack locations. Suppose for
  4768. the moment that we have just one register to use for register
  4769. allocation, \key{rcx}. Then we have the following map from colors to
  4770. locations.
  4771. \[
  4772. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4773. \]
  4774. Composing this mapping with the coloring, we arrive at the following
  4775. assignment of variables to locations.
  4776. {\if\edition\racketEd
  4777. \begin{gather*}
  4778. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4779. \ttm{w} \mapsto \key{\%rcx}, \,
  4780. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4781. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4782. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4783. \ttm{t} \mapsto \key{\%rcx} \}
  4784. \end{gather*}
  4785. \fi}
  4786. {\if\edition\pythonEd
  4787. \begin{gather*}
  4788. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4789. \ttm{w} \mapsto \key{\%rcx}, \,
  4790. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4791. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4792. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4793. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4794. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4795. \end{gather*}
  4796. \fi}
  4797. Adapt the code from the \code{assign\_homes} pass
  4798. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4799. assigned location. Applying the above assignment to our running
  4800. example, on the left, yields the program on the right.
  4801. % why frame size of 32? -JGS
  4802. \begin{center}
  4803. {\if\edition\racketEd
  4804. \begin{minipage}{0.3\textwidth}
  4805. \begin{lstlisting}
  4806. movq $1, v
  4807. movq $42, w
  4808. movq v, x
  4809. addq $7, x
  4810. movq x, y
  4811. movq x, z
  4812. addq w, z
  4813. movq y, t
  4814. negq t
  4815. movq z, %rax
  4816. addq t, %rax
  4817. jmp conclusion
  4818. \end{lstlisting}
  4819. \end{minipage}
  4820. $\Rightarrow\qquad$
  4821. \begin{minipage}{0.45\textwidth}
  4822. \begin{lstlisting}
  4823. movq $1, -8(%rbp)
  4824. movq $42, %rcx
  4825. movq -8(%rbp), -8(%rbp)
  4826. addq $7, -8(%rbp)
  4827. movq -8(%rbp), -16(%rbp)
  4828. movq -8(%rbp), -8(%rbp)
  4829. addq %rcx, -8(%rbp)
  4830. movq -16(%rbp), %rcx
  4831. negq %rcx
  4832. movq -8(%rbp), %rax
  4833. addq %rcx, %rax
  4834. jmp conclusion
  4835. \end{lstlisting}
  4836. \end{minipage}
  4837. \fi}
  4838. {\if\edition\pythonEd
  4839. \begin{minipage}{0.3\textwidth}
  4840. \begin{lstlisting}
  4841. movq $1, v
  4842. movq $42, w
  4843. movq v, x
  4844. addq $7, x
  4845. movq x, y
  4846. movq x, z
  4847. addq w, z
  4848. movq y, tmp_0
  4849. negq tmp_0
  4850. movq z, tmp_1
  4851. addq tmp_0, tmp_1
  4852. movq tmp_1, %rdi
  4853. callq print_int
  4854. \end{lstlisting}
  4855. \end{minipage}
  4856. $\Rightarrow\qquad$
  4857. \begin{minipage}{0.45\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), -8(%rbp)
  4869. addq %rcx, -8(%rbp)
  4870. movq -8(%rbp), %rdi
  4871. callq print_int
  4872. \end{lstlisting}
  4873. \end{minipage}
  4874. \fi}
  4875. \end{center}
  4876. \begin{exercise}\normalfont
  4877. %
  4878. Implement the compiler pass \code{allocate\_registers}.
  4879. %
  4880. Create five programs that exercise all aspects of the register
  4881. allocation algorithm, including spilling variables to the stack.
  4882. %
  4883. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4884. \code{run-tests.rkt} script with the three new passes:
  4885. \code{uncover\_live}, \code{build\_interference}, and
  4886. \code{allocate\_registers}.
  4887. %
  4888. Temporarily remove the \code{print\_x86} pass from the list of passes
  4889. and the call to \code{compiler-tests}.
  4890. Run the script to test the register allocator.
  4891. }
  4892. %
  4893. \python{Run the \code{run-tests.py} script to to check whether the
  4894. output programs produce the same result as the input programs.}
  4895. \end{exercise}
  4896. \section{Patch Instructions}
  4897. \label{sec:patch-instructions}
  4898. The remaining step in the compilation to x86 is to ensure that the
  4899. instructions have at most one argument that is a memory access.
  4900. %
  4901. In the running example, the instruction \code{movq -8(\%rbp),
  4902. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4903. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4904. then move \code{rax} into \code{-16(\%rbp)}.
  4905. %
  4906. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4907. problematic, but they can simply be deleted. In general, we recommend
  4908. deleting all the trivial moves whose source and destination are the
  4909. same location.
  4910. %
  4911. The following is the output of \code{patch\_instructions} on the
  4912. running example.
  4913. \begin{center}
  4914. {\if\edition\racketEd
  4915. \begin{minipage}{0.4\textwidth}
  4916. \begin{lstlisting}
  4917. movq $1, -8(%rbp)
  4918. movq $42, %rcx
  4919. movq -8(%rbp), -8(%rbp)
  4920. addq $7, -8(%rbp)
  4921. movq -8(%rbp), -16(%rbp)
  4922. movq -8(%rbp), -8(%rbp)
  4923. addq %rcx, -8(%rbp)
  4924. movq -16(%rbp), %rcx
  4925. negq %rcx
  4926. movq -8(%rbp), %rax
  4927. addq %rcx, %rax
  4928. jmp conclusion
  4929. \end{lstlisting}
  4930. \end{minipage}
  4931. $\Rightarrow\qquad$
  4932. \begin{minipage}{0.45\textwidth}
  4933. \begin{lstlisting}
  4934. movq $1, -8(%rbp)
  4935. movq $42, %rcx
  4936. addq $7, -8(%rbp)
  4937. movq -8(%rbp), %rax
  4938. movq %rax, -16(%rbp)
  4939. addq %rcx, -8(%rbp)
  4940. movq -16(%rbp), %rcx
  4941. negq %rcx
  4942. movq -8(%rbp), %rax
  4943. addq %rcx, %rax
  4944. jmp conclusion
  4945. \end{lstlisting}
  4946. \end{minipage}
  4947. \fi}
  4948. {\if\edition\pythonEd
  4949. \begin{minipage}{0.4\textwidth}
  4950. \begin{lstlisting}
  4951. movq $1, -8(%rbp)
  4952. movq $42, %rcx
  4953. movq -8(%rbp), -8(%rbp)
  4954. addq $7, -8(%rbp)
  4955. movq -8(%rbp), -16(%rbp)
  4956. movq -8(%rbp), -8(%rbp)
  4957. addq %rcx, -8(%rbp)
  4958. movq -16(%rbp), %rcx
  4959. negq %rcx
  4960. movq -8(%rbp), -8(%rbp)
  4961. addq %rcx, -8(%rbp)
  4962. movq -8(%rbp), %rdi
  4963. callq print_int
  4964. \end{lstlisting}
  4965. \end{minipage}
  4966. $\Rightarrow\qquad$
  4967. \begin{minipage}{0.45\textwidth}
  4968. \begin{lstlisting}
  4969. movq $1, -8(%rbp)
  4970. movq $42, %rcx
  4971. addq $7, -8(%rbp)
  4972. movq -8(%rbp), %rax
  4973. movq %rax, -16(%rbp)
  4974. addq %rcx, -8(%rbp)
  4975. movq -16(%rbp), %rcx
  4976. negq %rcx
  4977. addq %rcx, -8(%rbp)
  4978. movq -8(%rbp), %rdi
  4979. callq print_int
  4980. \end{lstlisting}
  4981. \end{minipage}
  4982. \fi}
  4983. \end{center}
  4984. \begin{exercise}\normalfont
  4985. %
  4986. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  4987. %
  4988. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  4989. %in the \code{run-tests.rkt} script.
  4990. %
  4991. Run the script to test the \code{patch\_instructions} pass.
  4992. \end{exercise}
  4993. \section{Print x86}
  4994. \label{sec:print-x86-reg-alloc}
  4995. \index{subject}{calling conventions}
  4996. \index{subject}{prelude}\index{subject}{conclusion}
  4997. Recall that the \code{print\_x86} pass generates the prelude and
  4998. conclusion instructions to satisfy the x86 calling conventions
  4999. (Section~\ref{sec:calling-conventions}). With the addition of the
  5000. register allocator, the callee-saved registers used by the register
  5001. allocator must be saved in the prelude and restored in the conclusion.
  5002. In the \code{allocate\_registers} pass,
  5003. %
  5004. \racket{add an entry to the \itm{info}
  5005. of \code{X86Program} named \code{used\_callee}}
  5006. %
  5007. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5008. %
  5009. that stores the set of
  5010. callee-saved registers that were assigned to variables. The
  5011. \code{print\_x86} pass can then access this information to decide which
  5012. callee-saved registers need to be saved and restored.
  5013. %
  5014. When calculating the size of the frame to adjust the \code{rsp} in the
  5015. prelude, make sure to take into account the space used for saving the
  5016. callee-saved registers. Also, don't forget that the frame needs to be
  5017. a multiple of 16 bytes!
  5018. \racket{An overview of all of the passes involved in register
  5019. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5020. {\if\edition\racketEd
  5021. \begin{figure}[tbp]
  5022. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5023. \node (Lvar) at (0,2) {\large \LangVar{}};
  5024. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5025. \node (Lvar-3) at (6,2) {\large \LangVar{}};
  5026. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5027. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5028. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5029. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5030. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5031. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5032. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5033. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5034. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5035. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5036. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5037. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5038. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5039. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5040. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5041. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  5042. \end{tikzpicture}
  5043. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5044. \label{fig:reg-alloc-passes}
  5045. \end{figure}
  5046. \fi}
  5047. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5048. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5049. use of registers and the stack, we limit the register allocator for
  5050. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5051. the prelude\index{subject}{prelude} of the \code{main} function, we
  5052. push \code{rbx} onto the stack because it is a callee-saved register
  5053. and it was assigned to variable by the register allocator. We
  5054. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5055. reserve space for the one spilled variable. After that subtraction,
  5056. the \code{rsp} is aligned to 16 bytes.
  5057. Moving on to the program proper, we see how the registers were
  5058. allocated.
  5059. %
  5060. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5061. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5062. %
  5063. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5064. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5065. were assigned to \code{rbx}.}
  5066. %
  5067. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5068. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5069. callee-save register \code{rbx} onto the stack. The spilled variables
  5070. must be placed lower on the stack than the saved callee-save
  5071. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5072. \code{-16(\%rbp)}.
  5073. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5074. done in the prelude. We move the stack pointer up by \code{8} bytes
  5075. (the room for spilled variables), then we pop the old values of
  5076. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5077. \code{retq} to return control to the operating system.
  5078. \begin{figure}[tbp]
  5079. % var_test_28.rkt
  5080. % (use-minimal-set-of-registers! #t)
  5081. % and only rbx rcx
  5082. % tmp 0 rbx
  5083. % z 1 rcx
  5084. % y 0 rbx
  5085. % w 2 16(%rbp)
  5086. % v 0 rbx
  5087. % x 0 rbx
  5088. {\if\edition\racketEd
  5089. \begin{lstlisting}
  5090. start:
  5091. movq $1, %rbx
  5092. movq $42, -16(%rbp)
  5093. addq $7, %rbx
  5094. movq %rbx, %rcx
  5095. addq -16(%rbp), %rcx
  5096. negq %rbx
  5097. movq %rcx, %rax
  5098. addq %rbx, %rax
  5099. jmp conclusion
  5100. .globl main
  5101. main:
  5102. pushq %rbp
  5103. movq %rsp, %rbp
  5104. pushq %rbx
  5105. subq $8, %rsp
  5106. jmp start
  5107. conclusion:
  5108. addq $8, %rsp
  5109. popq %rbx
  5110. popq %rbp
  5111. retq
  5112. \end{lstlisting}
  5113. \fi}
  5114. {\if\edition\pythonEd
  5115. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5116. \begin{lstlisting}
  5117. .globl main
  5118. main:
  5119. pushq %rbp
  5120. movq %rsp, %rbp
  5121. pushq %rbx
  5122. subq $8, %rsp
  5123. movq $1, %rcx
  5124. movq $42, %rbx
  5125. addq $7, %rcx
  5126. movq %rcx, -16(%rbp)
  5127. addq %rbx, -16(%rbp)
  5128. negq %rcx
  5129. movq -16(%rbp), %rbx
  5130. addq %rcx, %rbx
  5131. movq %rbx, %rdi
  5132. callq print_int
  5133. addq $8, %rsp
  5134. popq %rbx
  5135. popq %rbp
  5136. retq
  5137. \end{lstlisting}
  5138. \fi}
  5139. \caption{The x86 output from the running example
  5140. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5141. and \code{rcx}.}
  5142. \label{fig:running-example-x86}
  5143. \end{figure}
  5144. \begin{exercise}\normalfont
  5145. Update the \code{print\_x86} pass as described in this section.
  5146. %
  5147. \racket{
  5148. In the \code{run-tests.rkt} script, reinstate \code{print\_x86} in the
  5149. list of passes and the call to \code{compiler-tests}.}
  5150. %
  5151. Run the script to test the complete compiler for \LangVar{} that
  5152. performs register allocation.
  5153. \end{exercise}
  5154. \section{Challenge: Move Biasing}
  5155. \label{sec:move-biasing}
  5156. \index{subject}{move biasing}
  5157. This section describes an enhancement to the register allocator,
  5158. called move biasing, for students who are looking for an extra
  5159. challenge.
  5160. {\if\edition\racketEd
  5161. To motivate the need for move biasing we return to the running example
  5162. but this time use all of the general purpose registers. So we have
  5163. the following mapping of color numbers to registers.
  5164. \[
  5165. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5166. \]
  5167. Using the same assignment of variables to color numbers that was
  5168. produced by the register allocator described in the last section, we
  5169. get the following program.
  5170. \begin{center}
  5171. \begin{minipage}{0.3\textwidth}
  5172. \begin{lstlisting}
  5173. movq $1, v
  5174. movq $42, w
  5175. movq v, x
  5176. addq $7, x
  5177. movq x, y
  5178. movq x, z
  5179. addq w, z
  5180. movq y, t
  5181. negq t
  5182. movq z, %rax
  5183. addq t, %rax
  5184. jmp conclusion
  5185. \end{lstlisting}
  5186. \end{minipage}
  5187. $\Rightarrow\qquad$
  5188. \begin{minipage}{0.45\textwidth}
  5189. \begin{lstlisting}
  5190. movq $1, %rdx
  5191. movq $42, %rcx
  5192. movq %rdx, %rdx
  5193. addq $7, %rdx
  5194. movq %rdx, %rsi
  5195. movq %rdx, %rdx
  5196. addq %rcx, %rdx
  5197. movq %rsi, %rcx
  5198. negq %rcx
  5199. movq %rdx, %rax
  5200. addq %rcx, %rax
  5201. jmp conclusion
  5202. \end{lstlisting}
  5203. \end{minipage}
  5204. \end{center}
  5205. In the above output code there are two \key{movq} instructions that
  5206. can be removed because their source and target are the same. However,
  5207. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5208. register, we could instead remove three \key{movq} instructions. We
  5209. can accomplish this by taking into account which variables appear in
  5210. \key{movq} instructions with which other variables.
  5211. \fi}
  5212. {\if\edition\pythonEd
  5213. %
  5214. To motivate the need for move biasing we return to the running example
  5215. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5216. remove three trivial move instructions from the running
  5217. example. However, we could remove another trivial move if we were able
  5218. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5219. We say that two variables $p$ and $q$ are \emph{move
  5220. related}\index{subject}{move related} if they participate together in
  5221. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5222. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5223. when there are multiple variables with the same saturation, prefer
  5224. variables that can be assigned to a color that is the same as the
  5225. color of a move related variable. Furthermore, when the register
  5226. allocator chooses a color for a variable, it should prefer a color
  5227. that has already been used for a move-related variable (assuming that
  5228. they do not interfere). Of course, this preference should not override
  5229. the preference for registers over stack locations. So this preference
  5230. should be used as a tie breaker when choosing between registers or
  5231. when choosing between stack locations.
  5232. We recommend representing the move relationships in a graph, similar
  5233. to how we represented interference. The following is the \emph{move
  5234. graph} for our running example.
  5235. {\if\edition\racketEd
  5236. \[
  5237. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5238. \node (rax) at (0,0) {$\ttm{rax}$};
  5239. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5240. \node (t) at (0,2) {$\ttm{t}$};
  5241. \node (z) at (3,2) {$\ttm{z}$};
  5242. \node (x) at (6,2) {$\ttm{x}$};
  5243. \node (y) at (3,0) {$\ttm{y}$};
  5244. \node (w) at (6,0) {$\ttm{w}$};
  5245. \node (v) at (9,0) {$\ttm{v}$};
  5246. \draw (v) to (x);
  5247. \draw (x) to (y);
  5248. \draw (x) to (z);
  5249. \draw (y) to (t);
  5250. \end{tikzpicture}
  5251. \]
  5252. \fi}
  5253. %
  5254. {\if\edition\pythonEd
  5255. \[
  5256. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5257. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5258. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5259. \node (z) at (3,2) {$\ttm{z}$};
  5260. \node (x) at (6,2) {$\ttm{x}$};
  5261. \node (y) at (3,0) {$\ttm{y}$};
  5262. \node (w) at (6,0) {$\ttm{w}$};
  5263. \node (v) at (9,0) {$\ttm{v}$};
  5264. \draw (y) to (t0);
  5265. \draw (z) to (x);
  5266. \draw (z) to (t1);
  5267. \draw (x) to (y);
  5268. \draw (x) to (v);
  5269. \end{tikzpicture}
  5270. \]
  5271. \fi}
  5272. {\if\edition\racketEd
  5273. Now we replay the graph coloring, pausing to see the coloring of
  5274. \code{y}. Recall the following configuration. The most saturated vertices
  5275. were \code{w} and \code{y}.
  5276. \[
  5277. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5278. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5279. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5280. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5281. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5282. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5283. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5284. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5285. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5286. \draw (t1) to (rax);
  5287. \draw (t1) to (z);
  5288. \draw (z) to (y);
  5289. \draw (z) to (w);
  5290. \draw (x) to (w);
  5291. \draw (y) to (w);
  5292. \draw (v) to (w);
  5293. \draw (v) to (rsp);
  5294. \draw (w) to (rsp);
  5295. \draw (x) to (rsp);
  5296. \draw (y) to (rsp);
  5297. \path[-.,bend left=15] (z) edge node {} (rsp);
  5298. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5299. \draw (rax) to (rsp);
  5300. \end{tikzpicture}
  5301. \]
  5302. %
  5303. Last time we chose to color \code{w} with $0$. But this time we see
  5304. that \code{w} is not move related to any vertex, but \code{y} is move
  5305. related to \code{t}. So we choose to color \code{y} the same color as
  5306. \code{t}, $0$.
  5307. \[
  5308. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5309. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5310. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5311. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5312. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5313. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5314. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5315. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5316. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5317. \draw (t1) to (rax);
  5318. \draw (t1) to (z);
  5319. \draw (z) to (y);
  5320. \draw (z) to (w);
  5321. \draw (x) to (w);
  5322. \draw (y) to (w);
  5323. \draw (v) to (w);
  5324. \draw (v) to (rsp);
  5325. \draw (w) to (rsp);
  5326. \draw (x) to (rsp);
  5327. \draw (y) to (rsp);
  5328. \path[-.,bend left=15] (z) edge node {} (rsp);
  5329. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5330. \draw (rax) to (rsp);
  5331. \end{tikzpicture}
  5332. \]
  5333. Now \code{w} is the most saturated, so we color it $2$.
  5334. \[
  5335. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5336. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5337. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5338. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5339. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5340. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5341. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5342. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5343. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5344. \draw (t1) to (rax);
  5345. \draw (t1) to (z);
  5346. \draw (z) to (y);
  5347. \draw (z) to (w);
  5348. \draw (x) to (w);
  5349. \draw (y) to (w);
  5350. \draw (v) to (w);
  5351. \draw (v) to (rsp);
  5352. \draw (w) to (rsp);
  5353. \draw (x) to (rsp);
  5354. \draw (y) to (rsp);
  5355. \path[-.,bend left=15] (z) edge node {} (rsp);
  5356. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5357. \draw (rax) to (rsp);
  5358. \end{tikzpicture}
  5359. \]
  5360. At this point, vertices \code{x} and \code{v} are most saturated, but
  5361. \code{x} is move related to \code{y} and \code{z}, so we color
  5362. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5363. \[
  5364. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5365. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5366. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5367. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5368. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5369. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5370. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5371. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5372. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5373. \draw (t1) to (rax);
  5374. \draw (t) to (z);
  5375. \draw (z) to (y);
  5376. \draw (z) to (w);
  5377. \draw (x) to (w);
  5378. \draw (y) to (w);
  5379. \draw (v) to (w);
  5380. \draw (v) to (rsp);
  5381. \draw (w) to (rsp);
  5382. \draw (x) to (rsp);
  5383. \draw (y) to (rsp);
  5384. \path[-.,bend left=15] (z) edge node {} (rsp);
  5385. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5386. \draw (rax) to (rsp);
  5387. \end{tikzpicture}
  5388. \]
  5389. \fi}
  5390. %
  5391. {\if\edition\pythonEd
  5392. Now we replay the graph coloring, pausing before the coloring of
  5393. \code{w}. Recall the following configuration. The most saturated vertices
  5394. were \code{tmp\_1}, \code{w}, and \code{y}.
  5395. \[
  5396. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5397. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5398. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5399. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5400. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5401. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5402. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5403. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5404. \draw (t0) to (t1);
  5405. \draw (t0) to (z);
  5406. \draw (z) to (y);
  5407. \draw (z) to (w);
  5408. \draw (x) to (w);
  5409. \draw (y) to (w);
  5410. \draw (v) to (w);
  5411. \end{tikzpicture}
  5412. \]
  5413. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5414. or \code{y}, but note that \code{w} is not move related to any
  5415. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5416. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5417. \code{y} and color it $0$, we can delete another move instruction.
  5418. \[
  5419. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5420. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5421. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5422. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5423. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5424. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5425. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5426. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5427. \draw (t0) to (t1);
  5428. \draw (t0) to (z);
  5429. \draw (z) to (y);
  5430. \draw (z) to (w);
  5431. \draw (x) to (w);
  5432. \draw (y) to (w);
  5433. \draw (v) to (w);
  5434. \end{tikzpicture}
  5435. \]
  5436. Now \code{w} is the most saturated, so we color it $2$.
  5437. \[
  5438. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5439. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5440. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5441. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5442. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5443. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5444. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5445. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5446. \draw (t0) to (t1);
  5447. \draw (t0) to (z);
  5448. \draw (z) to (y);
  5449. \draw (z) to (w);
  5450. \draw (x) to (w);
  5451. \draw (y) to (w);
  5452. \draw (v) to (w);
  5453. \end{tikzpicture}
  5454. \]
  5455. To finish the coloring, \code{x} and \code{v} get $0$ and
  5456. \code{tmp\_1} gets $1$.
  5457. \[
  5458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5459. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5460. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5461. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5462. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5463. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5464. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5465. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5466. \draw (t0) to (t1);
  5467. \draw (t0) to (z);
  5468. \draw (z) to (y);
  5469. \draw (z) to (w);
  5470. \draw (x) to (w);
  5471. \draw (y) to (w);
  5472. \draw (v) to (w);
  5473. \end{tikzpicture}
  5474. \]
  5475. \fi}
  5476. So we have the following assignment of variables to registers.
  5477. {\if\edition\racketEd
  5478. \begin{gather*}
  5479. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5480. \ttm{w} \mapsto \key{\%rsi}, \,
  5481. \ttm{x} \mapsto \key{\%rcx}, \,
  5482. \ttm{y} \mapsto \key{\%rcx}, \,
  5483. \ttm{z} \mapsto \key{\%rdx}, \,
  5484. \ttm{t} \mapsto \key{\%rcx} \}
  5485. \end{gather*}
  5486. \fi}
  5487. {\if\edition\pythonEd
  5488. \begin{gather*}
  5489. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5490. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5491. \ttm{x} \mapsto \key{\%rcx}, \,
  5492. \ttm{y} \mapsto \key{\%rcx}, \\
  5493. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5494. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5495. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5496. \end{gather*}
  5497. \fi}
  5498. We apply this register assignment to the running example, on the left,
  5499. to obtain the code in the middle. The \code{patch\_instructions} then
  5500. deletes the trivial moves to obtain the code on the right.
  5501. {\if\edition\racketEd
  5502. \begin{minipage}{0.25\textwidth}
  5503. \begin{lstlisting}
  5504. movq $1, v
  5505. movq $42, w
  5506. movq v, x
  5507. addq $7, x
  5508. movq x, y
  5509. movq x, z
  5510. addq w, z
  5511. movq y, t
  5512. negq t
  5513. movq z, %rax
  5514. addq t, %rax
  5515. jmp conclusion
  5516. \end{lstlisting}
  5517. \end{minipage}
  5518. $\Rightarrow\qquad$
  5519. \begin{minipage}{0.25\textwidth}
  5520. \begin{lstlisting}
  5521. movq $1, %rcx
  5522. movq $42, %rsi
  5523. movq %rcx, %rcx
  5524. addq $7, %rcx
  5525. movq %rcx, %rcx
  5526. movq %rcx, %rdx
  5527. addq %rsi, %rdx
  5528. movq %rcx, %rcx
  5529. negq %rcx
  5530. movq %rdx, %rax
  5531. addq %rcx, %rax
  5532. jmp conclusion
  5533. \end{lstlisting}
  5534. \end{minipage}
  5535. $\Rightarrow\qquad$
  5536. \begin{minipage}{0.25\textwidth}
  5537. \begin{lstlisting}
  5538. movq $1, %rcx
  5539. movq $42, %rsi
  5540. addq $7, %rcx
  5541. movq %rcx, %rdx
  5542. addq %rsi, %rdx
  5543. negq %rcx
  5544. movq %rdx, %rax
  5545. addq %rcx, %rax
  5546. jmp conclusion
  5547. \end{lstlisting}
  5548. \end{minipage}
  5549. \fi}
  5550. {\if\edition\pythonEd
  5551. \begin{minipage}{0.20\textwidth}
  5552. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5553. movq $1, v
  5554. movq $42, w
  5555. movq v, x
  5556. addq $7, x
  5557. movq x, y
  5558. movq x, z
  5559. addq w, z
  5560. movq y, tmp_0
  5561. negq tmp_0
  5562. movq z, tmp_1
  5563. addq tmp_0, tmp_1
  5564. movq tmp_1, %rdi
  5565. callq _print_int
  5566. \end{lstlisting}
  5567. \end{minipage}
  5568. ${\Rightarrow\qquad}$
  5569. \begin{minipage}{0.30\textwidth}
  5570. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5571. movq $1, %rcx
  5572. movq $42, -16(%rbp)
  5573. movq %rcx, %rcx
  5574. addq $7, %rcx
  5575. movq %rcx, %rcx
  5576. movq %rcx, -8(%rbp)
  5577. addq -16(%rbp), -8(%rbp)
  5578. movq %rcx, %rcx
  5579. negq %rcx
  5580. movq -8(%rbp), -8(%rbp)
  5581. addq %rcx, -8(%rbp)
  5582. movq -8(%rbp), %rdi
  5583. callq _print_int
  5584. \end{lstlisting}
  5585. \end{minipage}
  5586. ${\Rightarrow\qquad}$
  5587. \begin{minipage}{0.20\textwidth}
  5588. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5589. movq $1, %rcx
  5590. movq $42, -16(%rbp)
  5591. addq $7, %rcx
  5592. movq %rcx, -8(%rbp)
  5593. movq -16(%rbp), %rax
  5594. addq %rax, -8(%rbp)
  5595. negq %rcx
  5596. addq %rcx, -8(%rbp)
  5597. movq -8(%rbp), %rdi
  5598. callq print_int
  5599. \end{lstlisting}
  5600. \end{minipage}
  5601. \fi}
  5602. \begin{exercise}\normalfont
  5603. Change your implementation of \code{allocate\_registers} to take move
  5604. biasing into account. Create two new tests that include at least one
  5605. opportunity for move biasing and visually inspect the output x86
  5606. programs to make sure that your move biasing is working properly. Make
  5607. sure that your compiler still passes all of the tests.
  5608. \end{exercise}
  5609. %To do: another neat challenge would be to do
  5610. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5611. %% \subsection{Output of the Running Example}
  5612. %% \label{sec:reg-alloc-output}
  5613. % challenge: prioritize variables based on execution frequencies
  5614. % and the number of uses of a variable
  5615. % challenge: enhance the coloring algorithm using Chaitin's
  5616. % approach of prioritizing high-degree variables
  5617. % by removing low-degree variables (coloring them later)
  5618. % from the interference graph
  5619. \section{Further Reading}
  5620. \label{sec:register-allocation-further-reading}
  5621. Early register allocation algorithms were developed for Fortran
  5622. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5623. of graph coloring began in the late 1970s and early 1980s with the
  5624. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5625. algorithm is based on the following observation of
  5626. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5627. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5628. $v$ removed is also $k$ colorable. To see why, suppose that the
  5629. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5630. different colors, but since there are less than $k$ neighbors, there
  5631. will be one or more colors left over to use for coloring $v$ in $G$.
  5632. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5633. less than $k$ from the graph and recursively colors the rest of the
  5634. graph. Upon returning from the recursion, it colors $v$ with one of
  5635. the available colors and returns. \citet{Chaitin:1982vn} augments
  5636. this algorithm to handle spilling as follows. If there are no vertices
  5637. of degree lower than $k$ then pick a vertex at random, spill it,
  5638. remove it from the graph, and proceed recursively to color the rest of
  5639. the graph.
  5640. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5641. move-related and that don't interfere with each other, a process
  5642. called \emph{coalescing}. While coalescing decreases the number of
  5643. moves, it can make the graph more difficult to
  5644. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5645. which two variables are merged only if they have fewer than $k$
  5646. neighbors of high degree. \citet{George:1996aa} observe that
  5647. conservative coalescing is sometimes too conservative and make it more
  5648. aggressive by iterating the coalescing with the removal of low-degree
  5649. vertices.
  5650. %
  5651. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5652. also propose \emph{biased coloring} in which a variable is assigned to
  5653. the same color as another move-related variable if possible, as
  5654. discussed in Section~\ref{sec:move-biasing}.
  5655. %
  5656. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5657. performs coalescing, graph coloring, and spill code insertion until
  5658. all variables have been assigned a location.
  5659. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5660. spills variables that don't have to be: a high-degree variable can be
  5661. colorable if many of its neighbors are assigned the same color.
  5662. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5663. high-degree vertex is not immediately spilled. Instead the decision is
  5664. deferred until after the recursive call, at which point it is apparent
  5665. whether there is actually an available color or not. We observe that
  5666. this algorithm is equivalent to the smallest-last ordering
  5667. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5668. be registers and the rest to be stack locations.
  5669. %% biased coloring
  5670. Earlier editions of the compiler course at Indiana University
  5671. \citep{Dybvig:2010aa} were based on the algorithm of
  5672. \citet{Briggs:1994kx}.
  5673. The smallest-last ordering algorithm is one of many \emph{greedy}
  5674. coloring algorithms. A greedy coloring algorithm visits all the
  5675. vertices in a particular order and assigns each one the first
  5676. available color. An \emph{offline} greedy algorithm chooses the
  5677. ordering up-front, prior to assigning colors. The algorithm of
  5678. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5679. ordering does not depend on the colors assigned. Other orderings are
  5680. possible. For example, \citet{Chow:1984ys} order variables according
  5681. to an estimate of runtime cost.
  5682. An \emph{online} greedy coloring algorithm uses information about the
  5683. current assignment of colors to influence the order in which the
  5684. remaining vertices are colored. The saturation-based algorithm
  5685. described in this chapter is one such algorithm. We choose to use
  5686. saturation-based coloring because it is fun to introduce graph
  5687. coloring via Sudoku!
  5688. A register allocator may choose to map each variable to just one
  5689. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5690. variable to one or more locations. The later can be achieved by
  5691. \emph{live range splitting}, where a variable is replaced by several
  5692. variables that each handle part of its live
  5693. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5694. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5695. %% replacement algorithm, bottom-up local
  5696. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5697. %% Cooper: top-down (priority bassed), bottom-up
  5698. %% top-down
  5699. %% order variables by priority (estimated cost)
  5700. %% caveat: split variables into two groups:
  5701. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5702. %% color the constrained ones first
  5703. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5704. %% cite J. Cocke for an algorithm that colors variables
  5705. %% in a high-degree first ordering
  5706. %Register Allocation via Usage Counts, Freiburghouse CACM
  5707. \citet{Palsberg:2007si} observe that many of the interference graphs
  5708. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5709. that is, every cycle with four or more edges has an edge which is not
  5710. part of the cycle but which connects two vertices on the cycle. Such
  5711. graphs can be optimally colored by the greedy algorithm with a vertex
  5712. ordering determined by maximum cardinality search.
  5713. In situations where compile time is of utmost importance, such as in
  5714. just-in-time compilers, graph coloring algorithms can be too expensive
  5715. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5716. appropriate.
  5717. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5718. \chapter{Booleans and Conditionals}
  5719. \label{ch:Lif}
  5720. \index{subject}{Boolean}
  5721. \index{subject}{control flow}
  5722. \index{subject}{conditional expression}
  5723. The \LangInt{} and \LangVar{} languages only have a single kind of
  5724. value, the integers. In this chapter we add a second kind of value,
  5725. the Booleans, to create the \LangIf{} language. The Boolean values
  5726. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5727. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5728. language includes several operations that involve Booleans (\key{and},
  5729. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5730. \key{if} expression \python{and statement}. With the addition of
  5731. \key{if}, programs can have non-trivial control flow which
  5732. %
  5733. \racket{impacts \code{explicate\_control} and liveness analysis}
  5734. %
  5735. \python{impacts liveness analysis and motivates a new pass named
  5736. \code{explicate\_control}}.
  5737. %
  5738. Also, because we now have two kinds of values, we need to handle
  5739. programs that apply an operation to the wrong kind of value, such as
  5740. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5741. There are two language design options for such situations. One option
  5742. is to signal an error and the other is to provide a wider
  5743. interpretation of the operation. \racket{The Racket
  5744. language}\python{Python} uses a mixture of these two options,
  5745. depending on the operation and the kind of value. For example, the
  5746. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5747. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5748. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5749. %
  5750. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5751. in Racket because \code{car} expects a pair.}
  5752. %
  5753. \python{On the other hand, \code{1[0]} results in a run-time error
  5754. in Python because an ``\code{int} object is not subscriptable''.}
  5755. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5756. design choices as \racket{Racket}\python{Python}, except much of the
  5757. error detection happens at compile time instead of run
  5758. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5759. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5760. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5761. Racket}\python{MyPy} reports a compile-time error
  5762. %
  5763. \racket{because Racket expects the type of the argument to be of the form
  5764. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5765. %
  5766. \python{stating that a ``value of type \code{int} is not indexable''.}
  5767. The \LangIf{} language performs type checking during compilation like
  5768. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5769. alternative choice, that is, a dynamically typed language like
  5770. \racket{Racket}\python{Python}.
  5771. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5772. for some operations we are more restrictive, for example, rejecting
  5773. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5774. This chapter is organized as follows. We begin by defining the syntax
  5775. and interpreter for the \LangIf{} language
  5776. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5777. checking and define a type checker for \LangIf{}
  5778. (Section~\ref{sec:type-check-Lif}).
  5779. %
  5780. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5781. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5782. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5783. %
  5784. The remaining sections of this chapter discuss how the addition of
  5785. Booleans and conditional control flow to the language requires changes
  5786. to the existing compiler passes and the addition of new ones. In
  5787. particular, we introduce the \code{shrink} pass to translates some
  5788. operators into others, thereby reducing the number of operators that
  5789. need to be handled in later passes.
  5790. %
  5791. The main event of this chapter is the \code{explicate\_control} pass
  5792. that is responsible for translating \code{if}'s into conditional
  5793. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5794. %
  5795. Regarding register allocation, there is the interesting question of
  5796. how to handle conditional \code{goto}'s during liveness analysis.
  5797. \section{The \LangIf{} Language}
  5798. \label{sec:lang-if}
  5799. The concrete syntax of the \LangIf{} language is defined in
  5800. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5801. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5802. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5803. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5804. operators to include
  5805. \begin{enumerate}
  5806. \item subtraction on integers,
  5807. \item the logical operators \key{and}, \key{or} and \key{not},
  5808. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5809. for comparing integers or Booleans for equality, and
  5810. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5811. comparing integers.
  5812. \end{enumerate}
  5813. \racket{We reorganize the abstract syntax for the primitive
  5814. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5815. rule for all of them. This means that the grammar no longer checks
  5816. whether the arity of an operators matches the number of
  5817. arguments. That responsibility is moved to the type checker for
  5818. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5819. \begin{figure}[tp]
  5820. \centering
  5821. \fbox{
  5822. \begin{minipage}{0.96\textwidth}
  5823. {\if\edition\racketEd
  5824. \[
  5825. \begin{array}{lcl}
  5826. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5827. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5828. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5829. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5830. &\MID& \itm{bool}
  5831. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5832. \MID (\key{not}\;\Exp) \\
  5833. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5834. \LangIfM{} &::=& \Exp
  5835. \end{array}
  5836. \]
  5837. \fi}
  5838. {\if\edition\pythonEd
  5839. \[
  5840. \begin{array}{rcl}
  5841. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5842. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  5843. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{uniop}}{\Exp} \MID \CBINOP{\itm{binop}}{\Exp}{\Exp} \MID \Var{} \\
  5844. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5845. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  5846. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  5847. \LangVarM{} &::=& \Stmt^{*}
  5848. \end{array}
  5849. \]
  5850. \fi}
  5851. \end{minipage}
  5852. }
  5853. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5854. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  5855. \label{fig:Lif-concrete-syntax}
  5856. \end{figure}
  5857. \begin{figure}[tp]
  5858. \centering
  5859. \fbox{
  5860. \begin{minipage}{0.96\textwidth}
  5861. {\if\edition\racketEd
  5862. \[
  5863. \begin{array}{lcl}
  5864. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5865. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5866. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5867. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5868. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5869. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5870. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5871. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5872. \end{array}
  5873. \]
  5874. \fi}
  5875. {\if\edition\pythonEd
  5876. \[
  5877. \begin{array}{lcl}
  5878. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  5879. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  5880. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5881. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5882. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5883. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  5884. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  5885. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  5886. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  5887. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  5888. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5889. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  5890. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  5891. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  5892. \end{array}
  5893. \]
  5894. \fi}
  5895. \end{minipage}
  5896. }
  5897. \caption{The abstract syntax of \LangIf{}.}
  5898. \label{fig:Lif-syntax}
  5899. \end{figure}
  5900. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  5901. which inherits from the interpreter for \LangVar{}
  5902. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  5903. evaluate to the corresponding Boolean values. The conditional
  5904. expression $(\CIF{e_1}{e_2}{\itm{e_3}})$ evaluates expression $e_1$
  5905. and then either evaluates $e_2$ or $e_3$ depending on whether
  5906. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  5907. \code{and}, \code{or}, and \code{not} behave as you might expect, but
  5908. note that the \code{and} and \code{or} operations are
  5909. short-circuiting.
  5910. %
  5911. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  5912. is not evaluated if $e_1$ evaluates to \FALSE{}.
  5913. %
  5914. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  5915. evaluated if $e_1$ evaluates to \TRUE{}.
  5916. \racket{With the increase in the number of primitive operations, the
  5917. interpreter would become repetitive without some care. We refactor
  5918. the case for \code{Prim}, moving the code that differs with each
  5919. operation into the \code{interp\_op} method shown in in
  5920. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} operation
  5921. separately because of its short-circuiting behavior.}
  5922. \begin{figure}[tbp]
  5923. {\if\edition\racketEd
  5924. \begin{lstlisting}
  5925. (define interp_Lif_class
  5926. (class interp_Lvar_class
  5927. (super-new)
  5928. (define/public (interp_op op) ...)
  5929. (define/override ((interp_exp env) e)
  5930. (define recur (interp_exp env))
  5931. (match e
  5932. [(Bool b) b]
  5933. [(If cnd thn els)
  5934. (match (recur cnd)
  5935. [#t (recur thn)]
  5936. [#f (recur els)])]
  5937. [(Prim 'and (list e1 e2))
  5938. (match (recur e1)
  5939. [#t (match (recur e2) [#t #t] [#f #f])]
  5940. [#f #f])]
  5941. [(Prim op args)
  5942. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  5943. [else ((super interp_exp env) e)]))
  5944. ))
  5945. (define (interp_Lif p)
  5946. (send (new interp_Lif_class) interp_program p))
  5947. \end{lstlisting}
  5948. \fi}
  5949. {\if\edition\pythonEd
  5950. \begin{lstlisting}
  5951. class InterpLif(InterpLvar):
  5952. def interp_exp(self, e, env):
  5953. match e:
  5954. case IfExp(test, body, orelse):
  5955. if self.interp_exp(test, env):
  5956. return self.interp_exp(body, env)
  5957. else:
  5958. return self.interp_exp(orelse, env)
  5959. case BinOp(left, Sub(), right):
  5960. return self.interp_exp(left, env) - self.interp_exp(right, env)
  5961. case UnaryOp(Not(), v):
  5962. return not self.interp_exp(v, env)
  5963. case BoolOp(And(), values):
  5964. if self.interp_exp(values[0], env):
  5965. return self.interp_exp(values[0], env)
  5966. else:
  5967. return False
  5968. case BoolOp(Or(), values):
  5969. if self.interp_exp(values[0], env):
  5970. return True
  5971. else:
  5972. return self.interp_exp(values[1], env)
  5973. case Compare(left, [cmp], [right]):
  5974. l = self.interp_exp(left, env)
  5975. r = self.interp_exp(right, env)
  5976. return self.interp_cmp(cmp)(l, r)
  5977. case _:
  5978. return super().interp_exp(e, env)
  5979. def interp_stmts(self, ss, env):
  5980. if len(ss) == 0:
  5981. return
  5982. match ss[0]:
  5983. case If(test, body, orelse):
  5984. if self.interp_exp(test, env):
  5985. return self.interp_stmts(body + ss[1:], env)
  5986. else:
  5987. return self.interp_stmts(orelse + ss[1:], env)
  5988. case _:
  5989. return super().interp_stmts(ss, env)
  5990. ...
  5991. \end{lstlisting}
  5992. \fi}
  5993. \caption{Interpreter for the \LangIf{} language. \racket{(See
  5994. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  5995. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  5996. \label{fig:interp-Lif}
  5997. \end{figure}
  5998. {\if\edition\racketEd
  5999. \begin{figure}[tbp]
  6000. \begin{lstlisting}
  6001. (define/public (interp_op op)
  6002. (match op
  6003. ['+ fx+]
  6004. ['- fx-]
  6005. ['read read-fixnum]
  6006. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6007. ['or (lambda (v1 v2)
  6008. (cond [(and (boolean? v1) (boolean? v2))
  6009. (or v1 v2)]))]
  6010. ['eq? (lambda (v1 v2)
  6011. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6012. (and (boolean? v1) (boolean? v2))
  6013. (and (vector? v1) (vector? v2)))
  6014. (eq? v1 v2)]))]
  6015. ['< (lambda (v1 v2)
  6016. (cond [(and (fixnum? v1) (fixnum? v2))
  6017. (< v1 v2)]))]
  6018. ['<= (lambda (v1 v2)
  6019. (cond [(and (fixnum? v1) (fixnum? v2))
  6020. (<= v1 v2)]))]
  6021. ['> (lambda (v1 v2)
  6022. (cond [(and (fixnum? v1) (fixnum? v2))
  6023. (> v1 v2)]))]
  6024. ['>= (lambda (v1 v2)
  6025. (cond [(and (fixnum? v1) (fixnum? v2))
  6026. (>= v1 v2)]))]
  6027. [else (error 'interp_op "unknown operator")]))
  6028. \end{lstlisting}
  6029. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6030. \label{fig:interp-op-Lif}
  6031. \end{figure}
  6032. \fi}
  6033. {\if\edition\pythonEd
  6034. \begin{figure}
  6035. \begin{lstlisting}
  6036. class InterpLif(InterpLvar):
  6037. ...
  6038. def interp_cmp(self, cmp):
  6039. match cmp:
  6040. case Lt():
  6041. return lambda x, y: x < y
  6042. case LtE():
  6043. return lambda x, y: x <= y
  6044. case Gt():
  6045. return lambda x, y: x > y
  6046. case GtE():
  6047. return lambda x, y: x >= y
  6048. case Eq():
  6049. return lambda x, y: x == y
  6050. case NotEq():
  6051. return lambda x, y: x != y
  6052. \end{lstlisting}
  6053. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6054. \label{fig:interp-cmp-Lif}
  6055. \end{figure}
  6056. \fi}
  6057. \section{Type Checking \LangIf{} Programs}
  6058. \label{sec:type-check-Lif}
  6059. \index{subject}{type checking}
  6060. \index{subject}{semantic analysis}
  6061. It is helpful to think about type checking in two complementary
  6062. ways. A type checker predicts the type of value that will be produced
  6063. by each expression in the program. For \LangIf{}, we have just two types,
  6064. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6065. {\if\edition\racketEd
  6066. \begin{lstlisting}
  6067. (+ 10 (- (+ 12 20)))
  6068. \end{lstlisting}
  6069. \fi}
  6070. {\if\edition\pythonEd
  6071. \begin{lstlisting}
  6072. 10 + -(12 + 20)
  6073. \end{lstlisting}
  6074. \fi}
  6075. \noindent produces a value of type \INTTY{} while
  6076. {\if\edition\racketEd
  6077. \begin{lstlisting}
  6078. (and (not #f) #t)
  6079. \end{lstlisting}
  6080. \fi}
  6081. {\if\edition\pythonEd
  6082. \begin{lstlisting}
  6083. (not False) and True
  6084. \end{lstlisting}
  6085. \fi}
  6086. \noindent produces a value of type \BOOLTY{}.
  6087. A second way to think about type checking is that it enforces a set of
  6088. rules about which operators can be applied to which kinds of
  6089. values. For example, our type checker for \LangIf{} signals an error
  6090. for the below expression {\if\edition\racketEd
  6091. \begin{lstlisting}
  6092. (not (+ 10 (- (+ 12 20))))
  6093. \end{lstlisting}
  6094. \fi}
  6095. {\if\edition\pythonEd
  6096. \begin{lstlisting}
  6097. not (10 + -(12 + 20))
  6098. \end{lstlisting}
  6099. \fi}
  6100. The subexpression
  6101. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6102. has type \INTTY{} but the type checker enforces the rule that the argument of
  6103. \code{not} must be an expression of type \BOOLTY{}.
  6104. We implement type checking using classes and methods because they
  6105. provide the open recursion needed to reuse code as we extend the type
  6106. checker in later chapters, analogous to the use of classes and methods
  6107. for the interpreters (Section~\ref{sec:extensible-interp}).
  6108. We separate the type checker for the \LangVar{} subset into its own
  6109. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6110. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6111. from the type checker for \LangVar{}. These type checkers are in the
  6112. files
  6113. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6114. and
  6115. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6116. of the support code.
  6117. %
  6118. Each type checker is a structurally recursive function over the AST.
  6119. Given an input expression \code{e}, the type checker either signals an
  6120. error or returns \racket{an expression and} its type (\INTTY{} or
  6121. \BOOLTY{}).
  6122. %
  6123. \racket{It returns an expression because there are situations in which
  6124. we want to change or update the expression.}
  6125. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6126. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6127. \INTTY{}. To handle variables, the type checker uses the environment
  6128. \code{env} to map variables to types.
  6129. %
  6130. \racket{Consider the case for \key{let}. We type check the
  6131. initializing expression to obtain its type \key{T} and then
  6132. associate type \code{T} with the variable \code{x} in the
  6133. environment used to type check the body of the \key{let}. Thus,
  6134. when the type checker encounters a use of variable \code{x}, it can
  6135. find its type in the environment.}
  6136. %
  6137. \python{Consider the case for assignment. We type check the
  6138. initializing expression to obtain its type \key{t}. If the variable
  6139. \code{lhs.id} is already in the environment because there was a
  6140. prior assignment, we check that this initializer has the same type
  6141. as the prior one. If this is the first assignment to the variable,
  6142. we associate type \code{t} with the variable \code{lhs.id} in the
  6143. environment. Thus, when the type checker encounters a use of
  6144. variable \code{x}, it can find its type in the environment.}
  6145. %
  6146. \racket{Regarding primitive operators, we recursively analyze the
  6147. arguments and then invoke \code{type\_check\_op} to check whether
  6148. the argument types are allowed.}
  6149. %
  6150. \python{Regarding addition and negation, we recursively analyze the
  6151. arguments, check that they have type \INT{}, and return \INT{}.}
  6152. \racket{Several auxiliary methods are used in the type checker. The
  6153. method \code{operator-types} defines a dictionary that maps the
  6154. operator names to their parameter and return types. The
  6155. \code{type-equal?} method determines whether two types are equal,
  6156. which for now simply dispatches to \code{equal?} (deep
  6157. equality). The \code{check-type-equal?} method triggers an error if
  6158. the two types are not equal. The \code{type-check-op} method looks
  6159. up the operator in the \code{operator-types} dictionary and then
  6160. checks whether the argument types are equal to the parameter types.
  6161. The result is the return type of the operator.}
  6162. %
  6163. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6164. an error if the two types are not equal.}
  6165. \begin{figure}[tbp]
  6166. {\if\edition\racketEd
  6167. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6168. (define type-check-Lvar_class
  6169. (class object%
  6170. (super-new)
  6171. (define/public (operator-types)
  6172. '((+ . ((Integer Integer) . Integer))
  6173. (- . ((Integer) . Integer))
  6174. (read . (() . Integer))))
  6175. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6176. (define/public (check-type-equal? t1 t2 e)
  6177. (unless (type-equal? t1 t2)
  6178. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6179. (define/public (type-check-op op arg-types e)
  6180. (match (dict-ref (operator-types) op)
  6181. [`(,param-types . ,return-type)
  6182. (for ([at arg-types] [pt param-types])
  6183. (check-type-equal? at pt e))
  6184. return-type]
  6185. [else (error 'type-check-op "unrecognized ~a" op)]))
  6186. (define/public (type-check-exp env)
  6187. (lambda (e)
  6188. (match e
  6189. [(Int n) (values (Int n) 'Integer)]
  6190. [(Var x) (values (Var x) (dict-ref env x))]
  6191. [(Let x e body)
  6192. (define-values (e^ Te) ((type-check-exp env) e))
  6193. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6194. (values (Let x e^ b) Tb)]
  6195. [(Prim op es)
  6196. (define-values (new-es ts)
  6197. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6198. (values (Prim op new-es) (type-check-op op ts e))]
  6199. [else (error 'type-check-exp "couldn't match" e)])))
  6200. (define/public (type-check-program e)
  6201. (match e
  6202. [(Program info body)
  6203. (define-values (body^ Tb) ((type-check-exp '()) body))
  6204. (check-type-equal? Tb 'Integer body)
  6205. (Program info body^)]
  6206. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6207. ))
  6208. (define (type-check-Lvar p)
  6209. (send (new type-check-Lvar_class) type-check-program p))
  6210. \end{lstlisting}
  6211. \fi}
  6212. {\if\edition\pythonEd
  6213. \begin{lstlisting}
  6214. class TypeCheckLvar:
  6215. def check_type_equal(self, t1, t2, e):
  6216. if t1 != t2:
  6217. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6218. raise Exception(msg)
  6219. def type_check_exp(self, e, env):
  6220. match e:
  6221. case BinOp(left, Add(), right):
  6222. l = self.type_check_exp(left, env)
  6223. check_type_equal(l, int, left)
  6224. r = self.type_check_exp(right, env)
  6225. check_type_equal(r, int, right)
  6226. return int
  6227. case UnaryOp(USub(), v):
  6228. t = self.type_check_exp(v, env)
  6229. check_type_equal(t, int, v)
  6230. return int
  6231. case Name(id):
  6232. return env[id]
  6233. case Constant(value) if isinstance(value, int):
  6234. return int
  6235. case Call(Name('input_int'), []):
  6236. return int
  6237. def type_check_stmts(self, ss, env):
  6238. if len(ss) == 0:
  6239. return
  6240. match ss[0]:
  6241. case Assign([lhs], value):
  6242. t = self.type_check_exp(value, env)
  6243. if lhs.id in env:
  6244. check_type_equal(env[lhs.id], t, value)
  6245. else:
  6246. env[lhs.id] = t
  6247. return self.type_check_stmts(ss[1:], env)
  6248. case Expr(Call(Name('print'), [arg])):
  6249. t = self.type_check_exp(arg, env)
  6250. check_type_equal(t, int, arg)
  6251. return self.type_check_stmts(ss[1:], env)
  6252. case Expr(value):
  6253. self.type_check_exp(value, env)
  6254. return self.type_check_stmts(ss[1:], env)
  6255. def type_check_P(self, p):
  6256. match p:
  6257. case Module(body):
  6258. self.type_check_stmts(body, {})
  6259. \end{lstlisting}
  6260. \fi}
  6261. \caption{Type checker for the \LangVar{} language.}
  6262. \label{fig:type-check-Lvar}
  6263. \end{figure}
  6264. \begin{figure}[tbp]
  6265. {\if\edition\racketEd
  6266. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6267. (define type-check-Lif_class
  6268. (class type-check-Lvar_class
  6269. (super-new)
  6270. (inherit check-type-equal?)
  6271. (define/override (operator-types)
  6272. (append '((- . ((Integer Integer) . Integer))
  6273. (and . ((Boolean Boolean) . Boolean))
  6274. (or . ((Boolean Boolean) . Boolean))
  6275. (< . ((Integer Integer) . Boolean))
  6276. (<= . ((Integer Integer) . Boolean))
  6277. (> . ((Integer Integer) . Boolean))
  6278. (>= . ((Integer Integer) . Boolean))
  6279. (not . ((Boolean) . Boolean))
  6280. )
  6281. (super operator-types)))
  6282. (define/override (type-check-exp env)
  6283. (lambda (e)
  6284. (match e
  6285. [(Bool b) (values (Bool b) 'Boolean)]
  6286. [(Prim 'eq? (list e1 e2))
  6287. (define-values (e1^ T1) ((type-check-exp env) e1))
  6288. (define-values (e2^ T2) ((type-check-exp env) e2))
  6289. (check-type-equal? T1 T2 e)
  6290. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6291. [(If cnd thn els)
  6292. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6293. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6294. (define-values (els^ Te) ((type-check-exp env) els))
  6295. (check-type-equal? Tc 'Boolean e)
  6296. (check-type-equal? Tt Te e)
  6297. (values (If cnd^ thn^ els^) Te)]
  6298. [else ((super type-check-exp env) e)])))
  6299. ))
  6300. (define (type-check-Lif p)
  6301. (send (new type-check-Lif_class) type-check-program p))
  6302. \end{lstlisting}
  6303. \fi}
  6304. {\if\edition\pythonEd
  6305. \begin{lstlisting}
  6306. class TypeCheckLif(TypeCheckLvar):
  6307. def type_check_exp(self, e, env):
  6308. match e:
  6309. case Constant(value) if isinstance(value, bool):
  6310. return bool
  6311. case BinOp(left, Sub(), right):
  6312. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6313. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6314. return int
  6315. case UnaryOp(Not(), v):
  6316. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6317. return bool
  6318. case BoolOp(op, values):
  6319. left = values[0] ; right = values[1]
  6320. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6321. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6322. return bool
  6323. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6324. or isinstance(cmp, NotEq):
  6325. l = self.type_check_exp(left, env)
  6326. r = self.type_check_exp(right, env)
  6327. check_type_equal(l, r, e)
  6328. return bool
  6329. case Compare(left, [cmp], [right]):
  6330. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6331. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6332. return bool
  6333. case IfExp(test, body, orelse):
  6334. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6335. b = self.type_check_exp(body, env)
  6336. o = self.type_check_exp(orelse, env)
  6337. check_type_equal(b, o, e)
  6338. return b
  6339. case _:
  6340. return super().type_check_exp(e, env)
  6341. def type_check_stmts(self, ss, env):
  6342. if len(ss) == 0:
  6343. return
  6344. match ss[0]:
  6345. case If(test, body, orelse):
  6346. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6347. b = self.type_check_stmts(body, env)
  6348. o = self.type_check_stmts(orelse, env)
  6349. check_type_equal(b, o, ss[0])
  6350. return self.type_check_stmts(ss[1:], env)
  6351. case _:
  6352. return super().type_check_stmts(ss, env)
  6353. \end{lstlisting}
  6354. \fi}
  6355. \caption{Type checker for the \LangIf{} language.}
  6356. \label{fig:type-check-Lif}
  6357. \end{figure}
  6358. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6359. checker for \LangIf{}.
  6360. %
  6361. The type of a Boolean constant is \BOOLTY{}.
  6362. %
  6363. \racket{The \code{operator-types} function adds dictionary entries for
  6364. the other new operators.}
  6365. %
  6366. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6367. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6368. produces a \BOOLTY{}. Similarly for logical-and and logical-or. }
  6369. %
  6370. The equality operators requires the two arguments to have the same
  6371. type.
  6372. %
  6373. \python{The other comparisons (less-than, etc.) require their
  6374. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6375. %
  6376. The condition of an \code{if} must
  6377. be of \BOOLTY{} type and the two branches must have the same type.
  6378. \begin{exercise}\normalfont
  6379. Create 10 new test programs in \LangIf{}. Half of the programs should
  6380. have a type error. For those programs, create an empty file with the
  6381. same base name but with file extension \code{.tyerr}. For example, if
  6382. the test
  6383. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6384. is expected to error, then create
  6385. an empty file named \code{cond\_test\_14.tyerr}.
  6386. %
  6387. \racket{This indicates to \code{interp-tests} and
  6388. \code{compiler-tests} that a type error is expected. }
  6389. %
  6390. \racket{This indicates to the \code{run-tests.py} scripts that a type
  6391. error is expected.}
  6392. %
  6393. The other half of the test programs should not have type errors.
  6394. %
  6395. \racket{In the \code{run-tests.rkt} script, change the second argument
  6396. of \code{interp-tests} and \code{compiler-tests} to
  6397. \code{type-check-Lif}, which causes the type checker to run prior to
  6398. the compiler passes. Temporarily change the \code{passes} to an
  6399. empty list and run the script, thereby checking that the new test
  6400. programs either type check or not as intended.}
  6401. %
  6402. Run the test script to check that these test programs type check as
  6403. expected.
  6404. \end{exercise}
  6405. \clearpage
  6406. \section{The \LangCIf{} Intermediate Language}
  6407. \label{sec:Cif}
  6408. \racket{
  6409. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  6410. \LangCIf{} intermediate language. (The concrete syntax is in the
  6411. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  6412. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  6413. operators to the \Exp{} non-terminal and the literals \TRUE{} and
  6414. \FALSE{} to the \Arg{} non-terminal.
  6415. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6416. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6417. statement is a comparison operation and the branches are \code{goto}
  6418. statements, making it straightforward to compile \code{if} statements
  6419. to x86.
  6420. }
  6421. %
  6422. {\if\edition\pythonEd
  6423. %
  6424. The output of \key{explicate\_control} is a language similar to the
  6425. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6426. \code{goto} statements, so we name it \LangCIf{}. The abstract syntax
  6427. for \LangCIf{} is defined in Figure~\ref{fig:c1-syntax}.
  6428. \racket{(The concrete syntax for \LangCIf{} is in the Appendix,
  6429. Figure~\ref{fig:c1-concrete-syntax}.)}
  6430. %
  6431. The \LangCIf{} language supports the same operators as \LangIf{} but
  6432. the arguments of operators are restricted to atomic expressions. The
  6433. \LangCIf{} language does not include \code{if} expressions but it does
  6434. include a restricted form of \code{if} statment. The condition must be
  6435. a comparison and the two branches may only contain \code{goto}
  6436. statements. These restrictions make it easier to translate \code{if}
  6437. statements to x86.
  6438. %
  6439. \fi}
  6440. %
  6441. The \key{CProgram} construct contains
  6442. %
  6443. \racket{an alist}\python{a dictionary}
  6444. %
  6445. mapping labels to \emph{basic blocks}\index{subject}{basic block},
  6446. that is to say, a sequence of straight-line statements that ends with
  6447. a \code{return}, \code{goto}, or conditional \code{goto}.
  6448. %
  6449. \racket{Basic blocks are represented in the grammar by the $\Tail$
  6450. non-terminal.}
  6451. \begin{figure}[tp]
  6452. \fbox{
  6453. \begin{minipage}{0.96\textwidth}
  6454. \small
  6455. {\if\edition\racketEd
  6456. \[
  6457. \begin{array}{lcl}
  6458. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6459. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  6460. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6461. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6462. &\MID& \UNIOP{\key{'not}}{\Atm}
  6463. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6464. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6465. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6466. \MID \GOTO{\itm{label}} \\
  6467. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6468. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6469. \end{array}
  6470. \]
  6471. \fi}
  6472. {\if\edition\pythonEd
  6473. \[
  6474. \begin{array}{lcl}
  6475. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6476. \Exp &::= & \Atm \MID \READ{} \\
  6477. &\MID& \BINOP{\Atm}{\itm{binop}}{\Atm}
  6478. \MID \UNIOP{\itm{uniop}}{\Atm} \\
  6479. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6480. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6481. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6482. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6483. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6484. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6485. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  6486. \end{array}
  6487. \]
  6488. \fi}
  6489. \end{minipage}
  6490. }
  6491. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6492. (Figure~\ref{fig:c0-syntax})}.}
  6493. \label{fig:c1-syntax}
  6494. \end{figure}
  6495. \section{The \LangXIf{} Language}
  6496. \label{sec:x86-if}
  6497. \index{subject}{x86} To implement the new logical operations, the comparison
  6498. operations, and the \key{if} expression, we need to delve further into
  6499. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6500. define the concrete and abstract syntax for the \LangXIf{} subset
  6501. of x86, which includes instructions for logical operations,
  6502. comparisons, and \racket{conditional} jumps.
  6503. One challenge is that x86 does not provide an instruction that
  6504. directly implements logical negation (\code{not} in \LangIf{} and
  6505. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6506. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6507. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6508. bit of its arguments, and writes the results into its second argument.
  6509. Recall the truth table for exclusive-or:
  6510. \begin{center}
  6511. \begin{tabular}{l|cc}
  6512. & 0 & 1 \\ \hline
  6513. 0 & 0 & 1 \\
  6514. 1 & 1 & 0
  6515. \end{tabular}
  6516. \end{center}
  6517. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6518. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6519. for the bit $1$, the result is the opposite of the second bit. Thus,
  6520. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6521. the first argument as follows, where $\Arg$ is the translation of
  6522. $\Atm$.
  6523. \[
  6524. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6525. \qquad\Rightarrow\qquad
  6526. \begin{array}{l}
  6527. \key{movq}~ \Arg\key{,} \Var\\
  6528. \key{xorq}~ \key{\$1,} \Var
  6529. \end{array}
  6530. \]
  6531. \begin{figure}[tp]
  6532. \fbox{
  6533. \begin{minipage}{0.96\textwidth}
  6534. \[
  6535. \begin{array}{lcl}
  6536. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6537. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6538. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6539. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6540. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6541. \key{subq} \; \Arg\key{,} \Arg \MID
  6542. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6543. && \gray{ \key{callq} \; \itm{label} \MID
  6544. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6545. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6546. \MID \key{xorq}~\Arg\key{,}~\Arg
  6547. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6548. && \key{set}cc~\Arg
  6549. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6550. \MID \key{j}cc~\itm{label}
  6551. \\
  6552. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6553. & & \gray{ \key{main:} \; \Instr\ldots }
  6554. \end{array}
  6555. \]
  6556. \end{minipage}
  6557. }
  6558. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6559. \label{fig:x86-1-concrete}
  6560. \end{figure}
  6561. \begin{figure}[tp]
  6562. \fbox{
  6563. \begin{minipage}{0.98\textwidth}
  6564. \small
  6565. {\if\edition\racketEd
  6566. \[
  6567. \begin{array}{lcl}
  6568. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6569. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6570. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6571. \MID \BYTEREG{\itm{bytereg}} \\
  6572. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6573. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6574. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6575. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6576. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6577. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6578. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6579. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6580. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6581. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6582. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6583. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6584. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6585. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6586. \end{array}
  6587. \]
  6588. \fi}
  6589. %
  6590. {\if\edition\pythonEd
  6591. \[
  6592. \begin{array}{lcl}
  6593. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6594. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6595. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6596. \MID \BYTEREG{\itm{bytereg}} \\
  6597. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6598. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6599. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6600. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6601. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6602. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6603. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6604. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6605. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6606. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6607. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6608. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6609. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6610. \end{array}
  6611. \]
  6612. \fi}
  6613. \end{minipage}
  6614. }
  6615. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6616. \label{fig:x86-1}
  6617. \end{figure}
  6618. Next we consider the x86 instructions that are relevant for compiling
  6619. the comparison operations. The \key{cmpq} instruction compares its two
  6620. arguments to determine whether one argument is less than, equal, or
  6621. greater than the other argument. The \key{cmpq} instruction is unusual
  6622. regarding the order of its arguments and where the result is
  6623. placed. The argument order is backwards: if you want to test whether
  6624. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6625. \key{cmpq} is placed in the special EFLAGS register. This register
  6626. cannot be accessed directly but it can be queried by a number of
  6627. instructions, including the \key{set} instruction. The instruction
  6628. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6629. depending on whether the comparison comes out according to the
  6630. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6631. for less-or-equal, \key{g} for greater, \key{ge} for
  6632. greater-or-equal). The \key{set} instruction has a quirk in
  6633. that its destination argument must be single byte register, such as
  6634. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6635. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6636. instruction can be used to move from a single byte register to a
  6637. normal 64-bit register. The abstract syntax for the \code{set}
  6638. instruction differs from the concrete syntax in that it separates the
  6639. instruction name from the condition code.
  6640. \python{The x86 instructions for jumping are relevant to the
  6641. compilation of \key{if} expressions.}
  6642. %
  6643. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6644. counter to the address of the instruction after the specified
  6645. label.}
  6646. %
  6647. \racket{The x86 instruction for conditional jump is relevant to the
  6648. compilation of \key{if} expressions.}
  6649. %
  6650. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6651. counter to point to the instruction after \itm{label} depending on
  6652. whether the result in the EFLAGS register matches the condition code
  6653. \itm{cc}, otherwise the jump instruction falls through to the next
  6654. instruction. Like the abstract syntax for \code{set}, the abstract
  6655. syntax for conditional jump separates the instruction name from the
  6656. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6657. to \code{jle foo}. Because the conditional jump instruction relies on
  6658. the EFLAGS register, it is common for it to be immediately preceded by
  6659. a \key{cmpq} instruction to set the EFLAGS register.
  6660. \section{Shrink the \LangIf{} Language}
  6661. \label{sec:shrink-Lif}
  6662. The \LangIf{} language includes several features that are easily
  6663. expressible with other features. For example, \code{and} and \code{or}
  6664. are expressible using \code{if} as follows.
  6665. \begin{align*}
  6666. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6667. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6668. \end{align*}
  6669. By performing these translations in the front-end of the compiler, the
  6670. later passes of the compiler do not need to deal with these features,
  6671. making the passes shorter.
  6672. %% For example, subtraction is
  6673. %% expressible using addition and negation.
  6674. %% \[
  6675. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6676. %% \]
  6677. %% Several of the comparison operations are expressible using less-than
  6678. %% and logical negation.
  6679. %% \[
  6680. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6681. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6682. %% \]
  6683. %% The \key{let} is needed in the above translation to ensure that
  6684. %% expression $e_1$ is evaluated before $e_2$.
  6685. On the other hand, sometimes translations reduce the efficiency of the
  6686. generated code by increasing the number of instructions. For example,
  6687. expressing subtraction in terms of negation
  6688. \[
  6689. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6690. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6691. \]
  6692. produces code with two x86 instructions (\code{negq} and \code{addq})
  6693. instead of just one (\code{subq}).
  6694. %% However,
  6695. %% these differences typically do not affect the number of accesses to
  6696. %% memory, which is the primary factor that determines execution time on
  6697. %% modern computer architectures.
  6698. \begin{exercise}\normalfont
  6699. %
  6700. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6701. the language by translating them to \code{if} expressions in \LangIf{}.
  6702. %
  6703. Create four test programs that involve these operators.
  6704. %
  6705. {\if\edition\racketEd
  6706. In the \code{run-tests.rkt} script, add the following entry for
  6707. \code{shrink} to the list of passes (it should be the only pass at
  6708. this point).
  6709. \begin{lstlisting}
  6710. (list "shrink" shrink interp_Lif type-check-Lif)
  6711. \end{lstlisting}
  6712. This instructs \code{interp-tests} to run the intepreter
  6713. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6714. output of \code{shrink}.
  6715. \fi}
  6716. %
  6717. Run the script to test your compiler on all the test programs.
  6718. \end{exercise}
  6719. {\if\edition\racketEd
  6720. \section{Uniquify Variables}
  6721. \label{sec:uniquify-Lif}
  6722. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6723. \code{if} expressions.
  6724. \begin{exercise}\normalfont
  6725. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6726. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6727. \begin{lstlisting}
  6728. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6729. \end{lstlisting}
  6730. Run the script to test your compiler.
  6731. \end{exercise}
  6732. \fi}
  6733. \section{Remove Complex Operands}
  6734. \label{sec:remove-complex-opera-Lif}
  6735. The output language of \code{remove\_complex\_operands} is \LangIfANF{}
  6736. (Figure~\ref{fig:Lif-anf-syntax}), the administrative normal form of
  6737. \LangIf{}. A Boolean constant is an atomic expressions but the
  6738. \code{if} expression is not.
  6739. All three sub-expressions of an
  6740. \code{if} are allowed to be complex expressions but the operands of
  6741. \code{not} and the comparisons must be atomic.
  6742. %
  6743. \python{We add a new language form, the \code{Let} expression, to aid
  6744. in the translation of \code{if} expressions. The
  6745. $\LET{x}{e_1}{e_2}$ form is like an assignment statement, but can be
  6746. used as an expression. It assigns the result of $e_1$ to the
  6747. variable $x$, an then evaluates $e_2$, which may reference $x$.}
  6748. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6749. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6750. according to whether the output needs to be \Exp{} or \Atm{} as
  6751. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6752. particularly important to \textbf{not} replace its condition with a
  6753. temporary variable because that would interfere with the generation of
  6754. high-quality output in the \code{explicate\_control} pass.
  6755. \begin{figure}[tp]
  6756. \centering
  6757. \fbox{
  6758. \begin{minipage}{0.96\textwidth}
  6759. {\if\edition\racketEd
  6760. \[
  6761. \begin{array}{rcl}
  6762. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6763. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6764. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6765. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6766. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6767. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6768. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6769. \end{array}
  6770. \]
  6771. \fi}
  6772. {\if\edition\pythonEd
  6773. \[
  6774. \begin{array}{rcl}
  6775. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  6776. \Exp &::=& \Atm \MID \READ{} \\
  6777. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  6778. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6779. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  6780. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6781. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  6782. P^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  6783. \end{array}
  6784. \]
  6785. \fi}
  6786. \end{minipage}
  6787. }
  6788. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  6789. \label{fig:Lif-anf-syntax}
  6790. \end{figure}
  6791. \begin{exercise}\normalfont
  6792. %
  6793. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6794. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6795. %
  6796. Create three new \LangInt{} programs that exercise the interesting
  6797. code in this pass.
  6798. %
  6799. {\if\edition\racketEd
  6800. In the \code{run-tests.rkt} script, add the following entry to the
  6801. list of \code{passes} and then run the script to test your compiler.
  6802. \begin{lstlisting}
  6803. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  6804. \end{lstlisting}
  6805. \fi}
  6806. \end{exercise}
  6807. \section{Explicate Control}
  6808. \label{sec:explicate-control-Lif}
  6809. \racket{Recall that the purpose of \code{explicate\_control} is to
  6810. make the order of evaluation explicit in the syntax of the program.
  6811. With the addition of \key{if} this get more interesting.}
  6812. %
  6813. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  6814. %
  6815. The main challenge to overcome is that the condition of an \key{if}
  6816. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  6817. condition must be a comparison.
  6818. As a motivating example, consider the following program that has an
  6819. \key{if} expression nested in the condition of another \key{if}.%
  6820. \python{\footnote{Programmers rarely write nested \code{if}
  6821. expressions, but it is not uncommon for the condition of an
  6822. \code{if} statement to be a call of a function that also contains an
  6823. \code{if} statement. When such a function is inlined, the result is
  6824. a nested \code{if} that requires the techniques discussed in this
  6825. section.}}
  6826. % cond_test_41.rkt, if_lt_eq.py
  6827. \begin{center}
  6828. \begin{minipage}{0.96\textwidth}
  6829. {\if\edition\racketEd
  6830. \begin{lstlisting}
  6831. (let ([x (read)])
  6832. (let ([y (read)])
  6833. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6834. (+ y 2)
  6835. (+ y 10))))
  6836. \end{lstlisting}
  6837. \fi}
  6838. {\if\edition\pythonEd
  6839. \begin{lstlisting}
  6840. x = input_int()
  6841. y = input_int()
  6842. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  6843. \end{lstlisting}
  6844. \fi}
  6845. \end{minipage}
  6846. \end{center}
  6847. %
  6848. The naive way to compile \key{if} and the comparison operations would
  6849. be to handle each of them in isolation, regardless of their context.
  6850. Each comparison would be translated into a \key{cmpq} instruction
  6851. followed by a couple instructions to move the result from the EFLAGS
  6852. register into a general purpose register or stack location. Each
  6853. \key{if} would be translated into a \key{cmpq} instruction followed by
  6854. a conditional jump. The generated code for the inner \key{if} in the
  6855. above example would be as follows.
  6856. \begin{center}
  6857. \begin{minipage}{0.96\textwidth}
  6858. \begin{lstlisting}
  6859. cmpq $1, x
  6860. setl %al
  6861. movzbq %al, tmp
  6862. cmpq $1, tmp
  6863. je then_branch_1
  6864. jmp else_branch_1
  6865. \end{lstlisting}
  6866. \end{minipage}
  6867. \end{center}
  6868. However, if we take context into account we can do better and reduce
  6869. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6870. Our goal will be to compile \key{if} expressions so that the relevant
  6871. comparison instruction appears directly before the conditional jump.
  6872. For example, we want to generate the following code for the inner
  6873. \code{if}.
  6874. \begin{center}
  6875. \begin{minipage}{0.96\textwidth}
  6876. \begin{lstlisting}
  6877. cmpq $1, x
  6878. je then_branch_1
  6879. jmp else_branch_1
  6880. \end{lstlisting}
  6881. \end{minipage}
  6882. \end{center}
  6883. One way to achieve this is to reorganize the code at the level of
  6884. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  6885. the following code.
  6886. \begin{center}
  6887. \begin{minipage}{0.96\textwidth}
  6888. {\if\edition\racketEd
  6889. \begin{lstlisting}
  6890. (let ([x (read)])
  6891. (let ([y (read)])
  6892. (if (< x 1)
  6893. (if (eq? x 0)
  6894. (+ y 2)
  6895. (+ y 10))
  6896. (if (eq? x 2)
  6897. (+ y 2)
  6898. (+ y 10)))))
  6899. \end{lstlisting}
  6900. \fi}
  6901. {\if\edition\pythonEd
  6902. \begin{lstlisting}
  6903. x = input_int()
  6904. y = intput_int()
  6905. print(((y + 2) if x == 0 else (y + 10)) \
  6906. if (x < 1) \
  6907. else ((y + 2) if (x == 2) else (y + 10)))
  6908. \end{lstlisting}
  6909. \fi}
  6910. \end{minipage}
  6911. \end{center}
  6912. Unfortunately, this approach duplicates the two branches from the
  6913. outer \code{if} and a compiler must never duplicate code! After all,
  6914. the two branches could have been very large expressions.
  6915. We need a way to perform the above transformation but without
  6916. duplicating code. That is, we need a way for different parts of a
  6917. program to refer to the same piece of code.
  6918. %
  6919. Put another way, we need to move away from abstract syntax
  6920. \emph{trees} and instead use \emph{graphs}.
  6921. %
  6922. At the level of x86 assembly this is straightforward because we can
  6923. label the code for each branch and insert jumps in all the places that
  6924. need to execute the branch.
  6925. %
  6926. Likewise, our language \LangCIf{} provides the ability to label a
  6927. sequence of code and to jump to a label via \code{goto}.
  6928. %
  6929. %% In particular, we use a standard program representation called a
  6930. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  6931. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  6932. %% is a labeled sequence of code, called a \emph{basic block}, and each
  6933. %% edge represents a jump to another block.
  6934. %
  6935. %% The nice thing about the output of \code{explicate\_control} is that
  6936. %% there are no unnecessary comparisons and every comparison is part of a
  6937. %% conditional jump.
  6938. %% The down-side of this output is that it includes
  6939. %% trivial blocks, such as the blocks labeled \code{block92} through
  6940. %% \code{block95}, that only jump to another block. We discuss a solution
  6941. %% to this problem in Section~\ref{sec:opt-jumps}.
  6942. {\if\edition\racketEd
  6943. %
  6944. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  6945. \code{explicate\_control} for \LangVar{} using two mutually recursive
  6946. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  6947. former function translates expressions in tail position whereas the
  6948. later function translates expressions on the right-hand-side of a
  6949. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  6950. have a new kind of position to deal with: the predicate position of
  6951. the \key{if}. We need another function, \code{explicate\_pred}, that
  6952. takes an \LangIf{} expression and two blocks for the then-branch and
  6953. else-branch. The output of \code{explicate\_pred} is a block. In the
  6954. following paragraphs we discuss specific cases in the
  6955. \code{explicate\_pred} function as well as additions to the
  6956. \code{explicate\_tail} and \code{explicate\_assign} functions.
  6957. %
  6958. \fi}
  6959. %
  6960. {\if\edition\pythonEd
  6961. %
  6962. We recommend implementing \code{explicate\_control} using the
  6963. following four auxiliary functions.
  6964. \begin{description}
  6965. \item[\code{explicate\_effect}] generates code for expressions as
  6966. statements, so their result is ignored and only their side effects
  6967. matter.
  6968. \item[\code{explicate\_assign}] generates code for expressions
  6969. on the right-hand side of an assignment.
  6970. \item[\code{explicate\_pred}] generates code for an \code{if}
  6971. expression or statement by analyzing the condition expression.
  6972. \item[\code{explicate\_stmt}] generates code for statements.
  6973. \end{description}
  6974. These four functions should build the dictionary of basic blocks. The
  6975. following auxiliary function can be used to create a new basic block
  6976. from a list of statements. It returns a \code{goto} statement that
  6977. jumps to the new basic block.
  6978. \begin{center}
  6979. \begin{minipage}{\textwidth}
  6980. \begin{lstlisting}
  6981. def create_block(stmts, basic_blocks):
  6982. label = label_name(generate_name('block'))
  6983. basic_blocks[label] = stmts
  6984. return Goto(label)
  6985. \end{lstlisting}
  6986. \end{minipage}
  6987. \end{center}
  6988. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  6989. \code{explicate\_control} pass.
  6990. The \code{explicate\_effect} function has three parameters: 1) the
  6991. expression to be compiled, 2) the already-compiled code for this
  6992. expression's \emph{continuation}, that is, the list of statements that
  6993. should execute after this expression, and 3) the dictionary of
  6994. generated basic blocks. The \code{explicate\_effect} function returns
  6995. a list of \LangCIf{} statements and it may add to the dictionary of
  6996. basic blocks.
  6997. %
  6998. Let's consider a few of the cases for the expression to be compiled.
  6999. If the expression to be compiled is a constant, then it can be
  7000. discarded because it has no side effects. If it's a \CREAD{}, then it
  7001. has a side-effect and should be preserved. So the exprssion should be
  7002. translated into a statement using the \code{Expr} AST class. If the
  7003. expression to be compiled is an \code{if} expression, we translate the
  7004. two branches using \code{explicate\_effect} and then translate the
  7005. condition expression using \code{explicate\_pred}, which generates
  7006. code for the entire \code{if}.
  7007. The \code{explicate\_assign} function has four parameters: 1) the
  7008. right-hand-side of the assignment, 2) the left-hand-side of the
  7009. assignment (the variable), 3) the continuation, and 4) the dictionary
  7010. of basic blocks. The \code{explicate\_assign} function returns a list
  7011. of \LangCIf{} statements and it may add to the dictionary of basic
  7012. blocks.
  7013. When the right-hand-side is an \code{if} expression, there is some
  7014. work to do. In particular, the two branches should be translated using
  7015. \code{explicate\_assign} and the condition expression should be
  7016. translated using \code{explicate\_pred}. Otherwise we can simply
  7017. generate an assignment statement, with the given left and right-hand
  7018. sides, concatenated with its continuation.
  7019. \begin{figure}[tbp]
  7020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7021. def explicate_effect(e, cont, basic_blocks):
  7022. match e:
  7023. case IfExp(test, body, orelse):
  7024. ...
  7025. case Call(func, args):
  7026. ...
  7027. case Let(var, rhs, body):
  7028. ...
  7029. case _:
  7030. ...
  7031. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7032. match rhs:
  7033. case IfExp(test, body, orelse):
  7034. ...
  7035. case Let(var, rhs, body):
  7036. ...
  7037. case _:
  7038. return [Assign([lhs], rhs)] + cont
  7039. def explicate_pred(cnd, thn, els, basic_blocks):
  7040. match cnd:
  7041. case Compare(left, [op], [right]):
  7042. goto_thn = create_block(thn, basic_blocks)
  7043. goto_els = create_block(els, basic_blocks)
  7044. return [If(cnd, [goto_thn], [goto_els])]
  7045. case Constant(True):
  7046. return thn;
  7047. case Constant(False):
  7048. return els;
  7049. case UnaryOp(Not(), operand):
  7050. ...
  7051. case IfExp(test, body, orelse):
  7052. ...
  7053. case Let(var, rhs, body):
  7054. ...
  7055. case _:
  7056. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7057. [create_block(els, basic_blocks)],
  7058. [create_block(thn, basic_blocks)])]
  7059. def explicate_stmt(s, cont, basic_blocks):
  7060. match s:
  7061. case Assign([lhs], rhs):
  7062. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7063. case Expr(value):
  7064. return explicate_effect(value, cont, basic_blocks)
  7065. case If(test, body, orelse):
  7066. ...
  7067. def explicate_control(p):
  7068. match p:
  7069. case Module(body):
  7070. new_body = [Return(Constant(0))]
  7071. basic_blocks = {}
  7072. for s in reversed(body):
  7073. new_body = explicate_stmt(s, new_body, basic_blocks)
  7074. basic_blocks[label_name('start')] = new_body
  7075. return CProgram(basic_blocks)
  7076. \end{lstlisting}
  7077. \caption{Skeleton for the \code{explicate\_control} pass.}
  7078. \label{fig:explicate-control-Lif}
  7079. \end{figure}
  7080. \fi}
  7081. {\if\edition\racketEd
  7082. \begin{figure}[tbp]
  7083. \begin{lstlisting}
  7084. (define (explicate_pred cnd thn els)
  7085. (match cnd
  7086. [(Var x) ___]
  7087. [(Let x rhs body) ___]
  7088. [(Prim 'not (list e)) ___]
  7089. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7090. (IfStmt (Prim op arg*) (force (block->goto thn))
  7091. (force (block->goto els)))]
  7092. [(Bool b) (if b thn els)]
  7093. [(If cnd^ thn^ els^) ___]
  7094. [else (error "explicate_pred unhandled case" cnd)]))
  7095. \end{lstlisting}
  7096. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7097. \label{fig:explicate-pred}
  7098. \end{figure}
  7099. \fi}
  7100. \racket{The skeleton for the \code{explicate\_pred} function is given
  7101. in Figure~\ref{fig:explicate-pred}. It has a case for every
  7102. expression that can have type \code{Boolean}. We detail a few cases
  7103. here and leave the rest for the reader. The input to this function
  7104. is an expression and two blocks, \code{thn} and \code{els}, for the
  7105. two branches of the enclosing \key{if}.}
  7106. %
  7107. \python{The \code{explicate\_pred} function has four parameters: 1)
  7108. the condition expession, 2) the generated statements for the
  7109. ``then'' branch, 3) the generated statements for the ``else''
  7110. branch, and 4) the dictionary of basic blocks. The
  7111. \code{explicate\_pred} function returns a list of \LangCIf{}
  7112. statements and it may add to the dictionary of basic blocks.}
  7113. %
  7114. Consider the case for comparison operators. We translate the
  7115. comparison to an \code{if} statement whose branches are \code{goto}
  7116. statements created by applying \code{create\_block} to the \code{thn}
  7117. and \code{els} branches.
  7118. %
  7119. Next consider the case for Boolean constants. We perform a kind of
  7120. partial evaluation\index{subject}{partial evaluation} and output
  7121. either the \code{thn} or \code{els} branch depending on whether the
  7122. constant is \TRUE{} or \FALSE{}. This case demonstrates that we
  7123. sometimes discard the \code{thn} or \code{els} blocks that are input
  7124. to \code{explicate\_pred}.
  7125. The case for \key{if} expressions in \code{explicate\_pred} is
  7126. particularly illuminating because it deals with the challenges we
  7127. discussed above regarding nested \key{if} expressions
  7128. (Figure~\ref{fig:explicate-control-s1-38}). The
  7129. \racket{\lstinline{thn^}}\python{\code{body}} and
  7130. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7131. \key{if} inherit their context from the current one, that is,
  7132. predicate context. So you should recursively apply
  7133. \code{explicate\_pred} to the
  7134. \racket{\lstinline{thn^}}\python{\code{body}} and
  7135. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7136. those recursive calls, pass \code{thn} and \code{els} as the extra
  7137. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7138. inside each recursive call. As discussed above, to avoid duplicating
  7139. code, we need to add them to the dictionary of basic blocks so that we
  7140. can instead refer to them by name and execute them with a \key{goto}.
  7141. {\if\edition\pythonEd
  7142. %
  7143. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7144. three parameters: 1) the statement to be compiled, 2) the code for its
  7145. continuation, and 3) the dictionary of basic blocks. The
  7146. \code{explicate\_stmt} returns a list of statements and it may add to
  7147. the dictionary of basic blocks. The cases for assignment and an
  7148. expression-statement are given in full in the skeleton code: they
  7149. simply dispatch to \code{explicate\_assign} and
  7150. \code{explicate\_effect}, respectively. The case for \code{if}
  7151. statements is not given, and is similar to the case for \code{if}
  7152. expressions.
  7153. The \code{explicate\_control} function itself is given in
  7154. Figure~\ref{fig:explicate-control-Lif}. It applies
  7155. \code{explicate\_stmt} to each statement in the program, from back to
  7156. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7157. used as the continuation parameter in the next call to
  7158. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7159. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7160. the dictionary of basic blocks, labeling it as the ``start'' block.
  7161. %
  7162. \fi}
  7163. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7164. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7165. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  7166. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7167. %% results from the two recursive calls. We complete the case for
  7168. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7169. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7170. %% the result $B_5$.
  7171. %% \[
  7172. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7173. %% \quad\Rightarrow\quad
  7174. %% B_5
  7175. %% \]
  7176. \racket{The \code{explicate\_tail} and \code{explicate\_assign}
  7177. functions need additional cases for Boolean constants and \key{if}.
  7178. In the cases for \code{if}, the two branches inherit the current
  7179. context, so in \code{explicate\_tail} they are in tail position and
  7180. in \code{explicate\_assign} they are in assignment position. The
  7181. \code{cont} parameter of \code{explicate\_assign} is used in both
  7182. recursive calls, so make sure to use \code{block->goto} on it.}
  7183. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7184. %% inherit the current context, so they are in tail position. Thus, the
  7185. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7186. %% \code{explicate\_tail}.
  7187. %% %
  7188. %% We need to pass $B_0$ as the accumulator argument for both of these
  7189. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7190. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  7191. %% to the control-flow graph and obtain a promised goto $G_0$.
  7192. %% %
  7193. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7194. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7195. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7196. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7197. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7198. %% \[
  7199. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7200. %% \]
  7201. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7202. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7203. %% should not be confused with the labels for the blocks that appear in
  7204. %% the generated code. We initially construct unlabeled blocks; we only
  7205. %% attach labels to blocks when we add them to the control-flow graph, as
  7206. %% we see in the next case.
  7207. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7208. %% function. The context of the \key{if} is an assignment to some
  7209. %% variable $x$ and then the control continues to some promised block
  7210. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7211. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7212. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  7213. %% branches of the \key{if} inherit the current context, so they are in
  7214. %% assignment positions. Let $B_2$ be the result of applying
  7215. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7216. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7217. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7218. %% the result of applying \code{explicate\_pred} to the predicate
  7219. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7220. %% translates to the promise $B_4$.
  7221. %% \[
  7222. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7223. %% \]
  7224. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7225. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7226. \code{remove\_complex\_operands} pass and then the
  7227. \code{explicate\_control} pass on the example program. We walk through
  7228. the output program.
  7229. %
  7230. Following the order of evaluation in the output of
  7231. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7232. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7233. in the predicate of the inner \key{if}. In the output of
  7234. \code{explicate\_control}, in the
  7235. block labeled \code{start}, are two assignment statements followed by a
  7236. \code{if} statement that branches to \code{block\_8} or
  7237. \code{block\_9}. The blocks associated with those labels contain the
  7238. translations of the code
  7239. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7240. and
  7241. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7242. respectively. In particular, we start \code{block\_8} with the
  7243. comparison
  7244. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7245. and then branch to \code{block\_4} or \code{block\_5}.
  7246. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7247. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7248. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7249. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7250. and go directly to \code{block\_2} and \code{block\_3},
  7251. which we investigate doing in Section~\ref{sec:opt-jumps}.
  7252. Getting back to the example, \code{block\_2} and \code{block\_3},
  7253. corresponds to the two branches of the outer \key{if}, i.e.,
  7254. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7255. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7256. %
  7257. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7258. %
  7259. \python{The \code{block\_1} corresponds to the \code{print} statment
  7260. at the end of the program.}
  7261. \begin{figure}[tbp]
  7262. {\if\edition\racketEd
  7263. \begin{tabular}{lll}
  7264. \begin{minipage}{0.4\textwidth}
  7265. % cond_test_41.rkt
  7266. \begin{lstlisting}
  7267. (let ([x (read)])
  7268. (let ([y (read)])
  7269. (if (if (< x 1)
  7270. (eq? x 0)
  7271. (eq? x 2))
  7272. (+ y 2)
  7273. (+ y 10))))
  7274. \end{lstlisting}
  7275. \end{minipage}
  7276. &
  7277. $\Rightarrow$
  7278. &
  7279. \begin{minipage}{0.55\textwidth}
  7280. TODO: replace with non-optimized version. -Jeremy
  7281. \begin{lstlisting}
  7282. start:
  7283. x = (read);
  7284. y = (read);
  7285. if (< x 1) goto block40;
  7286. else goto block41;
  7287. block40:
  7288. if (eq? x 0) goto block38;
  7289. else goto block39;
  7290. block41:
  7291. if (eq? x 2) goto block38;
  7292. else goto block39;
  7293. block38:
  7294. return (+ y 2);
  7295. block39:
  7296. return (+ y 10);
  7297. \end{lstlisting}
  7298. \end{minipage}
  7299. \end{tabular}
  7300. \fi}
  7301. {\if\edition\pythonEd
  7302. \begin{tabular}{lll}
  7303. \begin{minipage}{0.4\textwidth}
  7304. % cond_test_41.rkt
  7305. \begin{lstlisting}
  7306. x = input_int()
  7307. y = input_int()
  7308. print(y + 2 \
  7309. if (x == 0 \
  7310. if x < 1 \
  7311. else x == 2) \
  7312. else y + 10)
  7313. \end{lstlisting}
  7314. \end{minipage}
  7315. &
  7316. $\Rightarrow$
  7317. &
  7318. \begin{minipage}{0.55\textwidth}
  7319. \begin{lstlisting}
  7320. start:
  7321. x = input_int()
  7322. y = input_int()
  7323. if x < 1:
  7324. goto block_8
  7325. else:
  7326. goto block_9
  7327. block_8:
  7328. if x == 0:
  7329. goto block_4
  7330. else:
  7331. goto block_5
  7332. block_9:
  7333. if x == 2:
  7334. goto block_6
  7335. else:
  7336. goto block_7
  7337. block_4:
  7338. goto block_2
  7339. block_5:
  7340. goto block_3
  7341. block_6:
  7342. goto block_2
  7343. block_7:
  7344. goto block_3
  7345. block_2:
  7346. tmp_0 = y + 2
  7347. goto block_1
  7348. block_3:
  7349. tmp_0 = y + 10
  7350. goto block_1
  7351. block_1:
  7352. print(tmp_0)
  7353. return 0
  7354. \end{lstlisting}
  7355. \end{minipage}
  7356. \end{tabular}
  7357. \fi}
  7358. \caption{Translation from \LangIf{} to \LangCIf{}
  7359. via the \code{explicate\_control}.}
  7360. \label{fig:explicate-control-s1-38}
  7361. \end{figure}
  7362. {\if\edition\racketEd
  7363. The way in which the \code{shrink} pass transforms logical operations
  7364. such as \code{and} and \code{or} can impact the quality of code
  7365. generated by \code{explicate\_control}. For example, consider the
  7366. following program.
  7367. % cond_test_21.rkt, and_eq_input.py
  7368. \begin{lstlisting}
  7369. (if (and (eq? (read) 0) (eq? (read) 1))
  7370. 0
  7371. 42)
  7372. \end{lstlisting}
  7373. The \code{and} operation should transform into something that the
  7374. \code{explicate\_pred} function can still analyze and descend through to
  7375. reach the underlying \code{eq?} conditions. Ideally, your
  7376. \code{explicate\_control} pass should generate code similar to the
  7377. following for the above program.
  7378. \begin{center}
  7379. \begin{lstlisting}
  7380. start:
  7381. tmp1 = (read);
  7382. if (eq? tmp1 0) goto block40;
  7383. else goto block39;
  7384. block40:
  7385. tmp2 = (read);
  7386. if (eq? tmp2 1) goto block38;
  7387. else goto block39;
  7388. block38:
  7389. return 0;
  7390. block39:
  7391. return 42;
  7392. \end{lstlisting}
  7393. \end{center}
  7394. \fi}
  7395. \begin{exercise}\normalfont
  7396. \racket{
  7397. Implement the pass \code{explicate\_control} by adding the cases for
  7398. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7399. \code{explicate\_assign} functions. Implement the auxiliary function
  7400. \code{explicate\_pred} for predicate contexts.}
  7401. \python{Implement \code{explicate\_control} pass with its
  7402. four auxiliary functions.}
  7403. %
  7404. Create test cases that exercise all of the new cases in the code for
  7405. this pass.
  7406. %
  7407. {\if\edition\racketEd
  7408. Add the following entry to the list of \code{passes} in
  7409. \code{run-tests.rkt} and then run this script to test your compiler.
  7410. \begin{lstlisting}
  7411. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7412. \end{lstlisting}
  7413. \fi}
  7414. \end{exercise}
  7415. \clearpage
  7416. \section{Select Instructions}
  7417. \label{sec:select-Lif}
  7418. \index{subject}{instruction selection}
  7419. The \code{select\_instructions} pass translates \LangCIf{} to
  7420. \LangXIfVar{}.
  7421. %
  7422. \racket{Recall that we implement this pass using three auxiliary
  7423. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7424. $\Tail$.}
  7425. %
  7426. \racket{For $\Atm$, we have new cases for the Booleans.}
  7427. %
  7428. \python{We begin with the Boolean constants.}
  7429. We take the usual approach of encoding them as integers.
  7430. \[
  7431. \TRUE{} \quad\Rightarrow\quad \key{1}
  7432. \qquad\qquad
  7433. \FALSE{} \quad\Rightarrow\quad \key{0}
  7434. \]
  7435. For translating statements, we discuss a couple cases. The \code{not}
  7436. operation can be implemented in terms of \code{xorq} as we discussed
  7437. at the beginning of this section. Given an assignment, if the
  7438. left-hand side variable is the same as the argument of \code{not},
  7439. then just the \code{xorq} instruction suffices.
  7440. \[
  7441. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7442. \quad\Rightarrow\quad
  7443. \key{xorq}~\key{\$}1\key{,}~\Var
  7444. \]
  7445. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7446. semantics of x86. In the following translation, let $\Arg$ be the
  7447. result of translating $\Atm$ to x86.
  7448. \[
  7449. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7450. \quad\Rightarrow\quad
  7451. \begin{array}{l}
  7452. \key{movq}~\Arg\key{,}~\Var\\
  7453. \key{xorq}~\key{\$}1\key{,}~\Var
  7454. \end{array}
  7455. \]
  7456. Next consider the cases for equality. Translating this operation to
  7457. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7458. instruction discussed above. We recommend translating an assignment
  7459. with an equality on the right-hand side into a sequence of three
  7460. instructions. \\
  7461. \begin{tabular}{lll}
  7462. \begin{minipage}{0.4\textwidth}
  7463. \begin{lstlisting}
  7464. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7465. \end{lstlisting}
  7466. \end{minipage}
  7467. &
  7468. $\Rightarrow$
  7469. &
  7470. \begin{minipage}{0.4\textwidth}
  7471. \begin{lstlisting}
  7472. cmpq |$\Arg_2$|, |$\Arg_1$|
  7473. sete %al
  7474. movzbq %al, |$\Var$|
  7475. \end{lstlisting}
  7476. \end{minipage}
  7477. \end{tabular} \\
  7478. The translations for the other comparison operators are similar to the
  7479. above but use different suffixes for the \code{set} instruction.
  7480. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7481. \key{goto} and \key{if} statements. Both are straightforward to
  7482. translate to x86.}
  7483. %
  7484. A \key{goto} statement becomes a jump instruction.
  7485. \[
  7486. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7487. \]
  7488. %
  7489. An \key{if} statement becomes a compare instruction followed by a
  7490. conditional jump (for the ``then'' branch) and the fall-through is to
  7491. a regular jump (for the ``else'' branch).\\
  7492. \begin{tabular}{lll}
  7493. \begin{minipage}{0.4\textwidth}
  7494. \begin{lstlisting}
  7495. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7496. goto |$\ell_1$||$\racket{\key{;}}$|
  7497. else|$\python{\key{:}}$|
  7498. goto |$\ell_2$||$\racket{\key{;}}$|
  7499. \end{lstlisting}
  7500. \end{minipage}
  7501. &
  7502. $\Rightarrow$
  7503. &
  7504. \begin{minipage}{0.4\textwidth}
  7505. \begin{lstlisting}
  7506. cmpq |$\Arg_2$|, |$\Arg_1$|
  7507. je |$\ell_1$|
  7508. jmp |$\ell_2$|
  7509. \end{lstlisting}
  7510. \end{minipage}
  7511. \end{tabular} \\
  7512. Again, the translations for the other comparison operators are similar to the
  7513. above but use different suffixes for the conditional jump instruction.
  7514. \python{Regarding the \key{return} statement, we recommend treating it
  7515. as an assignment to the \key{rax} register followed by a jump to the
  7516. conclusion of the \code{main} function.}
  7517. \begin{exercise}\normalfont
  7518. Expand your \code{select\_instructions} pass to handle the new
  7519. features of the \LangIf{} language.
  7520. %
  7521. {\if\edition\racketEd
  7522. Add the following entry to the list of \code{passes} in
  7523. \code{run-tests.rkt}
  7524. \begin{lstlisting}
  7525. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7526. \end{lstlisting}
  7527. \fi}
  7528. %
  7529. Run the script to test your compiler on all the test programs.
  7530. \end{exercise}
  7531. \section{Register Allocation}
  7532. \label{sec:register-allocation-Lif}
  7533. \index{subject}{register allocation}
  7534. The changes required for \LangIf{} affect liveness analysis, building the
  7535. interference graph, and assigning homes, but the graph coloring
  7536. algorithm itself does not change.
  7537. \subsection{Liveness Analysis}
  7538. \label{sec:liveness-analysis-Lif}
  7539. \index{subject}{liveness analysis}
  7540. Recall that for \LangVar{} we implemented liveness analysis for a
  7541. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7542. the addition of \key{if} expressions to \LangIf{},
  7543. \code{explicate\_control} produces many basic blocks.
  7544. %% We recommend that you create a new auxiliary function named
  7545. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7546. %% control-flow graph.
  7547. The first question is: what order should we process the basic blocks?
  7548. Recall that to perform liveness analysis on a basic block we need to
  7549. know the live-after set for the last instruction in the block. If a
  7550. basic block has no successors (i.e. contains no jumps to other
  7551. blocks), then it has an empty live-after set and we can immediately
  7552. apply liveness analysis to it. If a basic block has some successors,
  7553. then we need to complete liveness analysis on those blocks
  7554. first. These ordering contraints are the reverse of a
  7555. \emph{topological order}\index{subject}{topological order} on the
  7556. control-flow graph of the program~\citep{Allen:1970uq}. In a
  7557. \emph{control flow graph} (CFG), each node represents a basic
  7558. block and each edge represents a jump from one block to another
  7559. \index{subject}{control-flow graph}. It is straightforward to
  7560. generate a CFG from the dictionary of basic blocks. One then needs to
  7561. transpose the CFG and apply the topological sort algorithm.
  7562. %
  7563. %
  7564. \racket{We recommend using the \code{tsort} and \code{transpose}
  7565. functions of the Racket \code{graph} package to accomplish this.}
  7566. %
  7567. \python{We provide implementations of \code{topological\_sort} and
  7568. \code{transpose} in the file \code{graph.py} of the support code.}
  7569. %
  7570. As an aside, a topological ordering is only guaranteed to exist if the
  7571. graph does not contain any cycles. That is indeed the case for the
  7572. control-flow graphs that we generate from \LangIf{} programs.
  7573. However, in Chapter~\ref{ch:Rwhile} we add loops to create \LangLoop{}
  7574. and learn how to handle cycles in the control-flow graph.
  7575. \racket{You'll need to construct a directed graph to represent the
  7576. control-flow graph. Do not use the \code{directed-graph} of the
  7577. \code{graph} package because that only allows at most one edge
  7578. between each pair of vertices, but a control-flow graph may have
  7579. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7580. file in the support code implements a graph representation that
  7581. allows multiple edges between a pair of vertices.}
  7582. {\if\edition\racketEd
  7583. The next question is how to analyze jump instructions. Recall that in
  7584. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7585. \code{label->live} that maps each label to the set of live locations
  7586. at the beginning of its block. We use \code{label->live} to determine
  7587. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7588. that we have many basic blocks, \code{label->live} needs to be updated
  7589. as we process the blocks. In particular, after performing liveness
  7590. analysis on a block, we take the live-before set of its first
  7591. instruction and associate that with the block's label in the
  7592. \code{label->live}.
  7593. \fi}
  7594. %
  7595. {\if\edition\pythonEd
  7596. %
  7597. The next question is how to analyze jump instructions. The locations
  7598. that are live before a \code{jmp} should be the locations in
  7599. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7600. maintaining a dictionary named \code{live\_before\_block} that maps each
  7601. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7602. block. After performing liveness analysis on each block, we take the
  7603. live-before set of its first instruction and associate that with the
  7604. block's label in the \code{live\_before\_block} dictionary.
  7605. %
  7606. \fi}
  7607. In \LangXIfVar{} we also have the conditional jump
  7608. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7609. this instruction is particularly interesting because, during
  7610. compilation, we do not know which way a conditional jump will go. So
  7611. we do not know whether to use the live-before set for the following
  7612. instruction or the live-before set for the block associated with the
  7613. $\itm{label}$. However, there is no harm to the correctness of the
  7614. generated code if we classify more locations as live than the ones
  7615. that are truly live during one particular execution of the
  7616. instruction. Thus, we can take the union of the live-before sets from
  7617. the following instruction and from the mapping for $\itm{label}$ in
  7618. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7619. The auxiliary functions for computing the variables in an
  7620. instruction's argument and for computing the variables read-from ($R$)
  7621. or written-to ($W$) by an instruction need to be updated to handle the
  7622. new kinds of arguments and instructions in \LangXIfVar{}.
  7623. \begin{exercise}\normalfont
  7624. {\if\edition\racketEd
  7625. %
  7626. Update the \code{uncover\_live} pass to apply liveness analysis to
  7627. every basic block in the program.
  7628. %
  7629. Add the following entry to the list of \code{passes} in the
  7630. \code{run-tests.rkt} script.
  7631. \begin{lstlisting}
  7632. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  7633. \end{lstlisting}
  7634. \fi}
  7635. {\if\edition\pythonEd
  7636. %
  7637. Update the \code{uncover\_live} function to perform liveness analysis,
  7638. in reverse topological order, on all of the basic blocks in the
  7639. program.
  7640. %
  7641. \fi}
  7642. % Check that the live-after sets that you generate for
  7643. % example X matches the following... -Jeremy
  7644. \end{exercise}
  7645. \subsection{Build the Interference Graph}
  7646. \label{sec:build-interference-Lif}
  7647. Many of the new instructions in \LangXIfVar{} can be handled in the
  7648. same way as the instructions in \LangXVar{}. Thus, if your code was
  7649. already quite general, it will not need to be changed to handle the
  7650. new instructions. If you code is not general enough, we recommend that
  7651. you change your code to be more general. For example, you can factor
  7652. out the computing of the the read and write sets for each kind of
  7653. instruction into auxiliary functions.
  7654. Note that the \key{movzbq} instruction requires some special care,
  7655. similar to the \key{movq} instruction. See rule number 1 in
  7656. Section~\ref{sec:build-interference}.
  7657. \begin{exercise}\normalfont
  7658. Update the \code{build\_interference} pass for \LangXIfVar{}.
  7659. {\if\edition\racketEd
  7660. Add the following entries to the list of \code{passes} in the
  7661. \code{run-tests.rkt} script.
  7662. \begin{lstlisting}
  7663. (list "build_interference" build_interference interp-pseudo-x86-1)
  7664. (list "allocate_registers" allocate_registers interp-x86-1)
  7665. \end{lstlisting}
  7666. \fi}
  7667. % Check that the interference graph that you generate for
  7668. % example X matches the following graph G... -Jeremy
  7669. \end{exercise}
  7670. \section{Patch Instructions}
  7671. The new instructions \key{cmpq} and \key{movzbq} have some special
  7672. restrictions that need to be handled in the \code{patch\_instructions}
  7673. pass.
  7674. %
  7675. The second argument of the \key{cmpq} instruction must not be an
  7676. immediate value (such as an integer). So if you are comparing two
  7677. immediates, we recommend inserting a \key{movq} instruction to put the
  7678. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  7679. one memory reference.
  7680. %
  7681. The second argument of the \key{movzbq} must be a register.
  7682. \begin{exercise}\normalfont
  7683. %
  7684. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  7685. %
  7686. {\if\edition\racketEd
  7687. Add the following entry to the list of \code{passes} in
  7688. \code{run-tests.rkt} and then run this script to test your compiler.
  7689. \begin{lstlisting}
  7690. (list "patch_instructions" patch_instructions interp-x86-1)
  7691. \end{lstlisting}
  7692. \fi}
  7693. \end{exercise}
  7694. {\if\edition\pythonEd
  7695. \section{Print x86}
  7696. \label{sec:print-x86-cond}
  7697. The generation of the \code{main} function with its prelude and
  7698. conclusion must change to accomodate how the program now consists of
  7699. one or more basic blocks. After the prelude in \code{main}, jump to
  7700. the \code{start} block. Place the conclusion in a basic block labelled
  7701. with \code{conclusion}.
  7702. \fi}
  7703. Figure~\ref{fig:if-example-x86} shows a simple example program in
  7704. \LangIf{} translated to x86, showing the results of
  7705. \code{explicate\_control}, \code{select\_instructions}, and the final
  7706. x86 assembly.
  7707. \begin{figure}[tbp]
  7708. {\if\edition\racketEd
  7709. \begin{tabular}{lll}
  7710. \begin{minipage}{0.4\textwidth}
  7711. % cond_test_20.rkt, eq_input.py
  7712. \begin{lstlisting}
  7713. (if (eq? (read) 1) 42 0)
  7714. \end{lstlisting}
  7715. $\Downarrow$
  7716. \begin{lstlisting}
  7717. start:
  7718. tmp7951 = (read);
  7719. if (eq? tmp7951 1)
  7720. goto block7952;
  7721. else
  7722. goto block7953;
  7723. block7952:
  7724. return 42;
  7725. block7953:
  7726. return 0;
  7727. \end{lstlisting}
  7728. $\Downarrow$
  7729. \begin{lstlisting}
  7730. start:
  7731. callq read_int
  7732. movq %rax, tmp7951
  7733. cmpq $1, tmp7951
  7734. je block7952
  7735. jmp block7953
  7736. block7953:
  7737. movq $0, %rax
  7738. jmp conclusion
  7739. block7952:
  7740. movq $42, %rax
  7741. jmp conclusion
  7742. \end{lstlisting}
  7743. \end{minipage}
  7744. &
  7745. $\Rightarrow\qquad$
  7746. \begin{minipage}{0.4\textwidth}
  7747. \begin{lstlisting}
  7748. start:
  7749. callq read_int
  7750. movq %rax, %rcx
  7751. cmpq $1, %rcx
  7752. je block7952
  7753. jmp block7953
  7754. block7953:
  7755. movq $0, %rax
  7756. jmp conclusion
  7757. block7952:
  7758. movq $42, %rax
  7759. jmp conclusion
  7760. .globl main
  7761. main:
  7762. pushq %rbp
  7763. movq %rsp, %rbp
  7764. pushq %r13
  7765. pushq %r12
  7766. pushq %rbx
  7767. pushq %r14
  7768. subq $0, %rsp
  7769. jmp start
  7770. conclusion:
  7771. addq $0, %rsp
  7772. popq %r14
  7773. popq %rbx
  7774. popq %r12
  7775. popq %r13
  7776. popq %rbp
  7777. retq
  7778. \end{lstlisting}
  7779. \end{minipage}
  7780. \end{tabular}
  7781. \fi}
  7782. {\if\edition\pythonEd
  7783. \begin{tabular}{lll}
  7784. \begin{minipage}{0.4\textwidth}
  7785. % cond_test_20.rkt, eq_input.py
  7786. \begin{lstlisting}
  7787. print(42 if input_int() == 1 else 0)
  7788. \end{lstlisting}
  7789. $\Downarrow$
  7790. \begin{lstlisting}
  7791. start:
  7792. tmp_0 = input_int()
  7793. if tmp_0 == 1:
  7794. goto block_3
  7795. else:
  7796. goto block_4
  7797. block_3:
  7798. tmp_1 = 42
  7799. goto block_2
  7800. block_4:
  7801. tmp_1 = 0
  7802. goto block_2
  7803. block_2:
  7804. print(tmp_1)
  7805. return 0
  7806. \end{lstlisting}
  7807. $\Downarrow$
  7808. \begin{lstlisting}
  7809. start:
  7810. callq read_int
  7811. movq %rax, tmp_0
  7812. cmpq 1, tmp_0
  7813. je block_3
  7814. jmp block_4
  7815. block_3:
  7816. movq 42, tmp_1
  7817. jmp block_2
  7818. block_4:
  7819. movq 0, tmp_1
  7820. jmp block_2
  7821. block_2:
  7822. movq tmp_1, %rdi
  7823. callq print_int
  7824. movq 0, %rax
  7825. jmp conclusion
  7826. \end{lstlisting}
  7827. \end{minipage}
  7828. &
  7829. $\Rightarrow\qquad$
  7830. \begin{minipage}{0.4\textwidth}
  7831. \begin{lstlisting}
  7832. .globl main
  7833. main:
  7834. pushq %rbp
  7835. movq %rsp, %rbp
  7836. subq $0, %rsp
  7837. jmp start
  7838. start:
  7839. callq read_int
  7840. movq %rax, %rcx
  7841. cmpq $1, %rcx
  7842. je block_3
  7843. jmp block_4
  7844. block_3:
  7845. movq $42, %rcx
  7846. jmp block_2
  7847. block_4:
  7848. movq $0, %rcx
  7849. jmp block_2
  7850. block_2:
  7851. movq %rcx, %rdi
  7852. callq print_int
  7853. movq $0, %rax
  7854. jmp conclusion
  7855. conclusion:
  7856. addq $0, %rsp
  7857. popq %rbp
  7858. retq
  7859. \end{lstlisting}
  7860. \end{minipage}
  7861. \end{tabular}
  7862. \fi}
  7863. \caption{Example compilation of an \key{if} expression to x86, showing
  7864. the results of \code{explicate\_control},
  7865. \code{select\_instructions}, and the final x86 assembly code. }
  7866. \label{fig:if-example-x86}
  7867. \end{figure}
  7868. \begin{figure}[tbp]
  7869. {\if\edition\racketEd
  7870. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7871. \node (Lif) at (0,2) {\large \LangIf{}};
  7872. \node (Lif-2) at (3,2) {\large \LangIf{}};
  7873. \node (Lif-3) at (6,2) {\large \LangIf{}};
  7874. \node (Lif-4) at (9,2) {\large \LangIf{}};
  7875. \node (Lif-5) at (12,2) {\large \LangIf{}};
  7876. \node (C1-1) at (3,0) {\large \LangCIf{}};
  7877. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  7878. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  7879. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  7880. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  7881. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  7882. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  7883. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  7884. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  7885. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  7886. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  7887. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  7888. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  7889. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  7890. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  7891. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  7892. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  7893. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  7894. \end{tikzpicture}
  7895. \fi}
  7896. {\if\edition\pythonEd
  7897. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7898. \node (Lif-1) at (0,2) {\large \LangIf{}};
  7899. \node (Lif-2) at (3,2) {\large \LangIf{}};
  7900. \node (Lif-3) at (6,2) {\large \LangIf{}};
  7901. \node (C-1) at (3,0) {\large \LangCIf{}};
  7902. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  7903. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  7904. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  7905. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  7906. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  7907. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  7908. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  7909. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  7910. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  7911. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  7912. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86 } (x86-4);
  7913. \end{tikzpicture}
  7914. \fi}
  7915. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  7916. \label{fig:Lif-passes}
  7917. \end{figure}
  7918. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  7919. compilation of \LangIf{}.
  7920. \section{Challenge: Optimize Blocks and Remove Jumps}
  7921. \label{sec:opt-jumps}
  7922. We discuss two optional challenges that involve optimizing the
  7923. control-flow of the program.
  7924. \subsection{Optimize Blocks}
  7925. The algorithm for \code{explicate\_control} that we discussed in
  7926. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  7927. blocks. It does so in two different ways.
  7928. %
  7929. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  7930. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  7931. a new basic block from a single \code{goto} statement, whereas we
  7932. could have simply returned the \code{goto} statement. We can solve
  7933. this problem by modifying the \code{create\_block} function to
  7934. recognize this situation.
  7935. Second, \code{explicate\_control} creates a basic block whenever a
  7936. continuation \emph{might} get used more than once (wheneven a
  7937. continuation is passed into two or more recursive calls). However,
  7938. just because a continuation might get used more than once, doesn't
  7939. mean it will. In fact, some continuation parameters may not be used
  7940. at all because we sometimes ignore them. For example, consider the
  7941. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  7942. discard the \code{els} branch. So the question is how can we decide
  7943. whether to create a basic block?
  7944. The solution to this conundrum is to use \emph{lazy
  7945. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  7946. to delay creating a basic block until the point in time where we know
  7947. it will be used.
  7948. %
  7949. {\if\edition\racketEd
  7950. %
  7951. Racket provides support for
  7952. lazy evaluation with the
  7953. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  7954. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  7955. \index{subject}{delay} creates a
  7956. \emph{promise}\index{subject}{promise} in which the evaluation of the
  7957. expressions is postponed. When \key{(force}
  7958. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  7959. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  7960. result of $e_n$ is cached in the promise and returned. If \code{force}
  7961. is applied again to the same promise, then the cached result is
  7962. returned. If \code{force} is applied to an argument that is not a
  7963. promise, \code{force} simply returns the argument.
  7964. %
  7965. \fi}
  7966. %
  7967. {\if\edition\pythonEd
  7968. %
  7969. While Python does not provide direct support for lazy evaluation, it
  7970. is easy to mimic. We can \emph{delay} the evaluation of a computation
  7971. by wrapping it inside a function with no parameters. We can
  7972. \emph{force} its evaluation by calling the function. However, in some
  7973. cases of \code{explicate\_pred}, etc., we will return a list of
  7974. statements and in other cases we will return a function that computes
  7975. a list of statements. We use the term \emph{promise} to refer to a
  7976. value that may or may not be delayed. To uniformly deal with
  7977. promises, we define the following \code{force} function that checks
  7978. whether its input is delayed (i.e. whether it is a function) and then
  7979. either 1) calls the function, or 2) returns the input.
  7980. \begin{lstlisting}
  7981. def force(promise):
  7982. if isinstance(promise, types.FunctionType):
  7983. return promise()
  7984. else:
  7985. return promise
  7986. \end{lstlisting}
  7987. %
  7988. \fi}
  7989. We use promises for the input and output of the functions
  7990. \code{explicate\_pred}, \code{explicate\_assign},
  7991. %
  7992. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  7993. %
  7994. So instead of taking and returning lists of statments, they take and
  7995. return promises. Furthermore, when we come to a situation in which a
  7996. continuation might be used more than once, as in the case for
  7997. \code{if} in \code{explicate\_pred}, we create a delayed computation
  7998. that creates a basic block for each continuation (if there is not
  7999. already one) and then returns a \code{goto} statement to that basic
  8000. block.
  8001. %
  8002. {\if\edition\racketEd
  8003. %
  8004. The following auxiliary function named \code{block->goto} accomplishes
  8005. this task. It begins with \code{delay} to create a promise. When
  8006. forced, this promise will force the original promise. If that returns
  8007. a \code{goto} (because the block was already added to the control-flow
  8008. graph), then we return the \code{goto}. Otherwise we add the block to
  8009. the control-flow graph with another auxiliary function named
  8010. \code{add-node}. That function returns the label for the new block,
  8011. which we use to create a \code{goto}.
  8012. \begin{lstlisting}
  8013. (define (block->goto block)
  8014. (delay
  8015. (define b (force block))
  8016. (match b
  8017. [(Goto label) (Goto label)]
  8018. [else (Goto (add-node b))])))
  8019. \end{lstlisting}
  8020. \fi}
  8021. {\if\edition\pythonEd
  8022. %
  8023. Here's the new version of the \code{create\_block} auxiliary function
  8024. that works on promises and that checks whether the block consists of a
  8025. solitary \code{goto} statement.\\
  8026. \begin{minipage}{\textwidth}
  8027. \begin{lstlisting}
  8028. def create_block(promise, basic_blocks):
  8029. stmts = force(promise)
  8030. match stmts:
  8031. case [Goto(l)]:
  8032. return Goto(l)
  8033. case _:
  8034. label = label_name(generate_name('block'))
  8035. basic_blocks[label] = stmts
  8036. return Goto(label)
  8037. \end{lstlisting}
  8038. \end{minipage}
  8039. \fi}
  8040. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8041. \code{explicate\_control} on the example of the nested \code{if}
  8042. expressions with the two improvements discussed above. As you can
  8043. see, the number of basic blocks has been reduced from 10 blocks (see
  8044. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8045. \begin{figure}[tbp]
  8046. {\if\edition\racketEd
  8047. \begin{tabular}{lll}
  8048. \begin{minipage}{0.4\textwidth}
  8049. % cond_test_41.rkt
  8050. \begin{lstlisting}
  8051. (let ([x (read)])
  8052. (let ([y (read)])
  8053. (if (if (< x 1)
  8054. (eq? x 0)
  8055. (eq? x 2))
  8056. (+ y 2)
  8057. (+ y 10))))
  8058. \end{lstlisting}
  8059. \end{minipage}
  8060. &
  8061. $\Rightarrow$
  8062. &
  8063. \begin{minipage}{0.55\textwidth}
  8064. \begin{lstlisting}
  8065. start:
  8066. x = (read);
  8067. y = (read);
  8068. if (< x 1) goto block40;
  8069. else goto block41;
  8070. block40:
  8071. if (eq? x 0) goto block38;
  8072. else goto block39;
  8073. block41:
  8074. if (eq? x 2) goto block38;
  8075. else goto block39;
  8076. block38:
  8077. return (+ y 2);
  8078. block39:
  8079. return (+ y 10);
  8080. \end{lstlisting}
  8081. \end{minipage}
  8082. \end{tabular}
  8083. \fi}
  8084. {\if\edition\pythonEd
  8085. \begin{tabular}{lll}
  8086. \begin{minipage}{0.4\textwidth}
  8087. % cond_test_41.rkt
  8088. \begin{lstlisting}
  8089. x = input_int()
  8090. y = input_int()
  8091. print(y + 2 \
  8092. if (x == 0 \
  8093. if x < 1 \
  8094. else x == 2) \
  8095. else y + 10)
  8096. \end{lstlisting}
  8097. \end{minipage}
  8098. &
  8099. $\Rightarrow$
  8100. &
  8101. \begin{minipage}{0.55\textwidth}
  8102. \begin{lstlisting}
  8103. start:
  8104. x = input_int()
  8105. y = input_int()
  8106. if x < 1:
  8107. goto block_4
  8108. else:
  8109. goto block_5
  8110. block_4:
  8111. if x == 0:
  8112. goto block_2
  8113. else:
  8114. goto block_3
  8115. block_5:
  8116. if x == 2:
  8117. goto block_2
  8118. else:
  8119. goto block_3
  8120. block_2:
  8121. tmp_0 = y + 2
  8122. goto block_1
  8123. block_3:
  8124. tmp_0 = y + 10
  8125. goto block_1
  8126. block_1:
  8127. print(tmp_0)
  8128. return 0
  8129. \end{lstlisting}
  8130. \end{minipage}
  8131. \end{tabular}
  8132. \fi}
  8133. \caption{Translation from \LangIf{} to \LangCIf{}
  8134. via the improved \code{explicate\_control}.}
  8135. \label{fig:explicate-control-challenge}
  8136. \end{figure}
  8137. %% Recall that in the example output of \code{explicate\_control} in
  8138. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8139. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8140. %% block. The first goal of this challenge assignment is to remove those
  8141. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8142. %% \code{explicate\_control} on the left and shows the result of bypassing
  8143. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8144. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8145. %% \code{block55}. The optimized code on the right of
  8146. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8147. %% \code{then} branch jumping directly to \code{block55}. The story is
  8148. %% similar for the \code{else} branch, as well as for the two branches in
  8149. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8150. %% have been optimized in this way, there are no longer any jumps to
  8151. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8152. %% \begin{figure}[tbp]
  8153. %% \begin{tabular}{lll}
  8154. %% \begin{minipage}{0.4\textwidth}
  8155. %% \begin{lstlisting}
  8156. %% block62:
  8157. %% tmp54 = (read);
  8158. %% if (eq? tmp54 2) then
  8159. %% goto block59;
  8160. %% else
  8161. %% goto block60;
  8162. %% block61:
  8163. %% tmp53 = (read);
  8164. %% if (eq? tmp53 0) then
  8165. %% goto block57;
  8166. %% else
  8167. %% goto block58;
  8168. %% block60:
  8169. %% goto block56;
  8170. %% block59:
  8171. %% goto block55;
  8172. %% block58:
  8173. %% goto block56;
  8174. %% block57:
  8175. %% goto block55;
  8176. %% block56:
  8177. %% return (+ 700 77);
  8178. %% block55:
  8179. %% return (+ 10 32);
  8180. %% start:
  8181. %% tmp52 = (read);
  8182. %% if (eq? tmp52 1) then
  8183. %% goto block61;
  8184. %% else
  8185. %% goto block62;
  8186. %% \end{lstlisting}
  8187. %% \end{minipage}
  8188. %% &
  8189. %% $\Rightarrow$
  8190. %% &
  8191. %% \begin{minipage}{0.55\textwidth}
  8192. %% \begin{lstlisting}
  8193. %% block62:
  8194. %% tmp54 = (read);
  8195. %% if (eq? tmp54 2) then
  8196. %% goto block55;
  8197. %% else
  8198. %% goto block56;
  8199. %% block61:
  8200. %% tmp53 = (read);
  8201. %% if (eq? tmp53 0) then
  8202. %% goto block55;
  8203. %% else
  8204. %% goto block56;
  8205. %% block56:
  8206. %% return (+ 700 77);
  8207. %% block55:
  8208. %% return (+ 10 32);
  8209. %% start:
  8210. %% tmp52 = (read);
  8211. %% if (eq? tmp52 1) then
  8212. %% goto block61;
  8213. %% else
  8214. %% goto block62;
  8215. %% \end{lstlisting}
  8216. %% \end{minipage}
  8217. %% \end{tabular}
  8218. %% \caption{Optimize jumps by removing trivial blocks.}
  8219. %% \label{fig:optimize-jumps}
  8220. %% \end{figure}
  8221. %% The name of this pass is \code{optimize-jumps}. We recommend
  8222. %% implementing this pass in two phases. The first phrase builds a hash
  8223. %% table that maps labels to possibly improved labels. The second phase
  8224. %% changes the target of each \code{goto} to use the improved label. If
  8225. %% the label is for a trivial block, then the hash table should map the
  8226. %% label to the first non-trivial block that can be reached from this
  8227. %% label by jumping through trivial blocks. If the label is for a
  8228. %% non-trivial block, then the hash table should map the label to itself;
  8229. %% we do not want to change jumps to non-trivial blocks.
  8230. %% The first phase can be accomplished by constructing an empty hash
  8231. %% table, call it \code{short-cut}, and then iterating over the control
  8232. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8233. %% then update the hash table, mapping the block's source to the target
  8234. %% of the \code{goto}. Also, the hash table may already have mapped some
  8235. %% labels to the block's source, to you must iterate through the hash
  8236. %% table and update all of those so that they instead map to the target
  8237. %% of the \code{goto}.
  8238. %% For the second phase, we recommend iterating through the $\Tail$ of
  8239. %% each block in the program, updating the target of every \code{goto}
  8240. %% according to the mapping in \code{short-cut}.
  8241. \begin{exercise}\normalfont
  8242. Implement the improvements to the \code{explicate\_control} pass.
  8243. Check that it removes trivial blocks in a few example programs. Then
  8244. check that your compiler still passes all of your tests.
  8245. \end{exercise}
  8246. \subsection{Remove Jumps}
  8247. There is an opportunity for removing jumps that is apparent in the
  8248. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8249. ends with a jump to \code{block\_4} and there are no other jumps to
  8250. \code{block\_4} in the rest of the program. In this situation we can
  8251. avoid the runtime overhead of this jump by merging \code{block\_4}
  8252. into the preceding block, in this case the \code{start} block.
  8253. Figure~\ref{fig:remove-jumps} shows the output of
  8254. \code{select\_instructions} on the left and the result of this
  8255. optimization on the right.
  8256. \begin{figure}[tbp]
  8257. {\if\edition\racketEd
  8258. \begin{tabular}{lll}
  8259. \begin{minipage}{0.5\textwidth}
  8260. % cond_test_20.rkt
  8261. \begin{lstlisting}
  8262. start:
  8263. callq read_int
  8264. movq %rax, tmp7951
  8265. cmpq $1, tmp7951
  8266. je block7952
  8267. jmp block7953
  8268. block7953:
  8269. movq $0, %rax
  8270. jmp conclusion
  8271. block7952:
  8272. movq $42, %rax
  8273. jmp conclusion
  8274. \end{lstlisting}
  8275. \end{minipage}
  8276. &
  8277. $\Rightarrow\qquad$
  8278. \begin{minipage}{0.4\textwidth}
  8279. \begin{lstlisting}
  8280. start:
  8281. callq read_int
  8282. movq %rax, tmp7951
  8283. cmpq $1, tmp7951
  8284. je block7952
  8285. movq $0, %rax
  8286. jmp conclusion
  8287. block7952:
  8288. movq $42, %rax
  8289. jmp conclusion
  8290. \end{lstlisting}
  8291. \end{minipage}
  8292. \end{tabular}
  8293. \fi}
  8294. {\if\edition\pythonEd
  8295. \begin{tabular}{lll}
  8296. \begin{minipage}{0.5\textwidth}
  8297. % cond_test_20.rkt
  8298. \begin{lstlisting}
  8299. start:
  8300. callq read_int
  8301. movq %rax, tmp_0
  8302. cmpq 1, tmp_0
  8303. je block_3
  8304. jmp block_4
  8305. block_3:
  8306. movq 42, tmp_1
  8307. jmp block_2
  8308. block_4:
  8309. movq 0, tmp_1
  8310. jmp block_2
  8311. block_2:
  8312. movq tmp_1, %rdi
  8313. callq print_int
  8314. movq 0, %rax
  8315. jmp conclusion
  8316. \end{lstlisting}
  8317. \end{minipage}
  8318. &
  8319. $\Rightarrow\qquad$
  8320. \begin{minipage}{0.4\textwidth}
  8321. \begin{lstlisting}
  8322. start:
  8323. callq read_int
  8324. movq %rax, tmp_0
  8325. cmpq 1, tmp_0
  8326. je block_3
  8327. movq 0, tmp_1
  8328. jmp block_2
  8329. block_3:
  8330. movq 42, tmp_1
  8331. jmp block_2
  8332. block_2:
  8333. movq tmp_1, %rdi
  8334. callq print_int
  8335. movq 0, %rax
  8336. jmp conclusion
  8337. \end{lstlisting}
  8338. \end{minipage}
  8339. \end{tabular}
  8340. \fi}
  8341. \caption{Merging basic blocks by removing unnecessary jumps.}
  8342. \label{fig:remove-jumps}
  8343. \end{figure}
  8344. \begin{exercise}\normalfont
  8345. %
  8346. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8347. into their preceding basic block, when there is only one preceding
  8348. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8349. %
  8350. {\if\edition\racketEd
  8351. In the \code{run-tests.rkt} script, add the following entry to the
  8352. list of \code{passes} between \code{allocate\_registers}
  8353. and \code{patch\_instructions}.
  8354. \begin{lstlisting}
  8355. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8356. \end{lstlisting}
  8357. \fi}
  8358. %
  8359. Run the script to test your compiler.
  8360. %
  8361. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8362. blocks on several test programs.
  8363. \end{exercise}
  8364. \section{Further Reading}
  8365. \label{sec:cond-further-reading}
  8366. The algorithm for the \code{explicate\_control} pass comes from the
  8367. course notes of \citet{Dybvig:2010aa}. The use of lazy evaluation in
  8368. Section~\ref{sec:opt-jumps} to optimize basic blocks is new. There
  8369. are algorithms similar to \code{explicate\_control} in the literature,
  8370. such as the case-of-case transformation of \citet{PeytonJones:1998}.
  8371. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8372. \chapter{Loops and Dataflow Analysis}
  8373. \label{ch:Rwhile}
  8374. % TODO: define R'_8
  8375. % TODO: multi-graph
  8376. \if\edition\racketEd
  8377. In this chapter we study two features that are the hallmarks of
  8378. imperative programming languages: loops and assignments to local
  8379. variables. The following example demonstrates these new features by
  8380. computing the sum of the first five positive integers.
  8381. % similar to loop_test_1.rkt
  8382. \begin{lstlisting}
  8383. (let ([sum 0])
  8384. (let ([i 5])
  8385. (begin
  8386. (while (> i 0)
  8387. (begin
  8388. (set! sum (+ sum i))
  8389. (set! i (- i 1))))
  8390. sum)))
  8391. \end{lstlisting}
  8392. The \code{while} loop consists of a condition and a body.
  8393. %
  8394. The \code{set!} consists of a variable and a right-hand-side expression.
  8395. %
  8396. The primary purpose of both the \code{while} loop and \code{set!} is
  8397. to cause side effects, so it is convenient to also include in a
  8398. language feature for sequencing side effects: the \code{begin}
  8399. expression. It consists of one or more subexpressions that are
  8400. evaluated left-to-right.
  8401. \section{The \LangLoop{} Language}
  8402. \begin{figure}[tp]
  8403. \centering
  8404. \fbox{
  8405. \begin{minipage}{0.96\textwidth}
  8406. \small
  8407. \[
  8408. \begin{array}{lcl}
  8409. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  8410. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8411. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8412. &\MID& \gray{\key{\#t} \MID \key{\#f}
  8413. \MID (\key{and}\;\Exp\;\Exp)
  8414. \MID (\key{or}\;\Exp\;\Exp)
  8415. \MID (\key{not}\;\Exp) } \\
  8416. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8417. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  8418. (\key{vector-ref}\;\Exp\;\Int)} \\
  8419. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  8420. \MID (\Exp \; \Exp\ldots) } \\
  8421. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  8422. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  8423. &\MID& \CSETBANG{\Var}{\Exp}
  8424. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8425. \MID \CWHILE{\Exp}{\Exp} \\
  8426. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8427. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  8428. \end{array}
  8429. \]
  8430. \end{minipage}
  8431. }
  8432. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  8433. \label{fig:Rwhile-concrete-syntax}
  8434. \end{figure}
  8435. \begin{figure}[tp]
  8436. \centering
  8437. \fbox{
  8438. \begin{minipage}{0.96\textwidth}
  8439. \small
  8440. \[
  8441. \begin{array}{lcl}
  8442. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8443. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8444. &\MID& \gray{ \BOOL{\itm{bool}}
  8445. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8446. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  8447. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  8448. &\MID& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  8449. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8450. \MID \WHILE{\Exp}{\Exp} \\
  8451. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8452. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8453. \end{array}
  8454. \]
  8455. \end{minipage}
  8456. }
  8457. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  8458. \label{fig:Rwhile-syntax}
  8459. \end{figure}
  8460. The concrete syntax of \LangLoop{} is defined in
  8461. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  8462. in Figure~\ref{fig:Rwhile-syntax}.
  8463. %
  8464. The definitional interpreter for \LangLoop{} is shown in
  8465. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  8466. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  8467. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  8468. support assignment to variables and to make their lifetimes indefinite
  8469. (see the second example in Section~\ref{sec:assignment-scoping}), we
  8470. box the value that is bound to each variable (in \code{Let}) and
  8471. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  8472. the value.
  8473. %
  8474. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8475. variable in the environment to obtain a boxed value and then we change
  8476. it using \code{set-box!} to the result of evaluating the right-hand
  8477. side. The result value of a \code{SetBang} is \code{void}.
  8478. %
  8479. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8480. if the result is true, 2) evaluate the body.
  8481. The result value of a \code{while} loop is also \code{void}.
  8482. %
  8483. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8484. subexpressions \itm{es} for their effects and then evaluates
  8485. and returns the result from \itm{body}.
  8486. \begin{figure}[tbp]
  8487. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8488. (define interp-Rwhile_class
  8489. (class interp-Rany_class
  8490. (super-new)
  8491. (define/override ((interp-exp env) e)
  8492. (define recur (interp-exp env))
  8493. (match e
  8494. [(SetBang x rhs)
  8495. (set-box! (lookup x env) (recur rhs))]
  8496. [(WhileLoop cnd body)
  8497. (define (loop)
  8498. (cond [(recur cnd) (recur body) (loop)]
  8499. [else (void)]))
  8500. (loop)]
  8501. [(Begin es body)
  8502. (for ([e es]) (recur e))
  8503. (recur body)]
  8504. [else ((super interp-exp env) e)]))
  8505. ))
  8506. (define (interp-Rwhile p)
  8507. (send (new interp-Rwhile_class) interp-program p))
  8508. \end{lstlisting}
  8509. \caption{Interpreter for \LangLoop{}.}
  8510. \label{fig:interp-Rwhile}
  8511. \end{figure}
  8512. The type checker for \LangLoop{} is define in
  8513. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  8514. variable and the right-hand-side must agree. The result type is
  8515. \code{Void}. For the \code{WhileLoop}, the condition must be a
  8516. \code{Boolean}. The result type is also \code{Void}. For
  8517. \code{Begin}, the result type is the type of its last subexpression.
  8518. \begin{figure}[tbp]
  8519. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8520. (define type-check-Rwhile_class
  8521. (class type-check-Rany_class
  8522. (super-new)
  8523. (inherit check-type-equal?)
  8524. (define/override (type-check-exp env)
  8525. (lambda (e)
  8526. (define recur (type-check-exp env))
  8527. (match e
  8528. [(SetBang x rhs)
  8529. (define-values (rhs^ rhsT) (recur rhs))
  8530. (define varT (dict-ref env x))
  8531. (check-type-equal? rhsT varT e)
  8532. (values (SetBang x rhs^) 'Void)]
  8533. [(WhileLoop cnd body)
  8534. (define-values (cnd^ Tc) (recur cnd))
  8535. (check-type-equal? Tc 'Boolean e)
  8536. (define-values (body^ Tbody) ((type-check-exp env) body))
  8537. (values (WhileLoop cnd^ body^) 'Void)]
  8538. [(Begin es body)
  8539. (define-values (es^ ts)
  8540. (for/lists (l1 l2) ([e es]) (recur e)))
  8541. (define-values (body^ Tbody) (recur body))
  8542. (values (Begin es^ body^) Tbody)]
  8543. [else ((super type-check-exp env) e)])))
  8544. ))
  8545. (define (type-check-Rwhile p)
  8546. (send (new type-check-Rwhile_class) type-check-program p))
  8547. \end{lstlisting}
  8548. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  8549. and \code{Begin} in \LangLoop{}.}
  8550. \label{fig:type-check-Rwhile}
  8551. \end{figure}
  8552. At first glance, the translation of these language features to x86
  8553. seems straightforward because the \LangCFun{} intermediate language
  8554. already supports all of the ingredients that we need: assignment,
  8555. \code{goto}, conditional branching, and sequencing. However, there are
  8556. complications that arise which we discuss in the next section. After
  8557. that we introduce the changes necessary to the existing passes.
  8558. \section{Cyclic Control Flow and Dataflow Analysis}
  8559. \label{sec:dataflow-analysis}
  8560. Up until this point the control-flow graphs generated in
  8561. \code{explicate\_control} were guaranteed to be acyclic. However, each
  8562. \code{while} loop introduces a cycle in the control-flow graph.
  8563. But does that matter?
  8564. %
  8565. Indeed it does. Recall that for register allocation, the compiler
  8566. performs liveness analysis to determine which variables can share the
  8567. same register. In Section~\ref{sec:liveness-analysis-Lif} we analyze
  8568. the control-flow graph in reverse topological order, but topological
  8569. order is only well-defined for acyclic graphs.
  8570. Let us return to the example of computing the sum of the first five
  8571. positive integers. Here is the program after instruction selection but
  8572. before register allocation.
  8573. \begin{center}
  8574. \begin{minipage}{0.45\textwidth}
  8575. \begin{lstlisting}
  8576. (define (main) : Integer
  8577. mainstart:
  8578. movq $0, sum1
  8579. movq $5, i2
  8580. jmp block5
  8581. block5:
  8582. movq i2, tmp3
  8583. cmpq tmp3, $0
  8584. jl block7
  8585. jmp block8
  8586. \end{lstlisting}
  8587. \end{minipage}
  8588. \begin{minipage}{0.45\textwidth}
  8589. \begin{lstlisting}
  8590. block7:
  8591. addq i2, sum1
  8592. movq $1, tmp4
  8593. negq tmp4
  8594. addq tmp4, i2
  8595. jmp block5
  8596. block8:
  8597. movq $27, %rax
  8598. addq sum1, %rax
  8599. jmp mainconclusion
  8600. )
  8601. \end{lstlisting}
  8602. \end{minipage}
  8603. \end{center}
  8604. Recall that liveness analysis works backwards, starting at the end
  8605. of each function. For this example we could start with \code{block8}
  8606. because we know what is live at the beginning of the conclusion,
  8607. just \code{rax} and \code{rsp}. So the live-before set
  8608. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  8609. %
  8610. Next we might try to analyze \code{block5} or \code{block7}, but
  8611. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  8612. we are stuck.
  8613. The way out of this impasse comes from the realization that one can
  8614. perform liveness analysis starting with an empty live-after set to
  8615. compute an under-approximation of the live-before set. By
  8616. \emph{under-approximation}, we mean that the set only contains
  8617. variables that are really live, but it may be missing some. Next, the
  8618. under-approximations for each block can be improved by 1) updating the
  8619. live-after set for each block using the approximate live-before sets
  8620. from the other blocks and 2) perform liveness analysis again on each
  8621. block. In fact, by iterating this process, the under-approximations
  8622. eventually become the correct solutions!
  8623. %
  8624. This approach of iteratively analyzing a control-flow graph is
  8625. applicable to many static analysis problems and goes by the name
  8626. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  8627. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  8628. Washington.
  8629. Let us apply this approach to the above example. We use the empty set
  8630. for the initial live-before set for each block. Let $m_0$ be the
  8631. following mapping from label names to sets of locations (variables and
  8632. registers).
  8633. \begin{center}
  8634. \begin{lstlisting}
  8635. mainstart: {}
  8636. block5: {}
  8637. block7: {}
  8638. block8: {}
  8639. \end{lstlisting}
  8640. \end{center}
  8641. Using the above live-before approximations, we determine the
  8642. live-after for each block and then apply liveness analysis to each
  8643. block. This produces our next approximation $m_1$ of the live-before
  8644. sets.
  8645. \begin{center}
  8646. \begin{lstlisting}
  8647. mainstart: {}
  8648. block5: {i2}
  8649. block7: {i2, sum1}
  8650. block8: {rsp, sum1}
  8651. \end{lstlisting}
  8652. \end{center}
  8653. For the second round, the live-after for \code{mainstart} is the
  8654. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  8655. liveness analysis for \code{mainstart} computes the empty set. The
  8656. live-after for \code{block5} is the union of the live-before sets for
  8657. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  8658. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  8659. sum1\}}. The live-after for \code{block7} is the live-before for
  8660. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  8661. So the liveness analysis for \code{block7} remains \code{\{i2,
  8662. sum1\}}. Together these yield the following approximation $m_2$ of
  8663. the live-before sets.
  8664. \begin{center}
  8665. \begin{lstlisting}
  8666. mainstart: {}
  8667. block5: {i2, rsp, sum1}
  8668. block7: {i2, sum1}
  8669. block8: {rsp, sum1}
  8670. \end{lstlisting}
  8671. \end{center}
  8672. In the preceding iteration, only \code{block5} changed, so we can
  8673. limit our attention to \code{mainstart} and \code{block7}, the two
  8674. blocks that jump to \code{block5}. As a result, the live-before sets
  8675. for \code{mainstart} and \code{block7} are updated to include
  8676. \code{rsp}, yielding the following approximation $m_3$.
  8677. \begin{center}
  8678. \begin{lstlisting}
  8679. mainstart: {rsp}
  8680. block5: {i2, rsp, sum1}
  8681. block7: {i2, rsp, sum1}
  8682. block8: {rsp, sum1}
  8683. \end{lstlisting}
  8684. \end{center}
  8685. Because \code{block7} changed, we analyze \code{block5} once more, but
  8686. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  8687. our approximations have converged, so $m_3$ is the solution.
  8688. This iteration process is guaranteed to converge to a solution by the
  8689. Kleene Fixed-Point Theorem, a general theorem about functions on
  8690. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  8691. any collection that comes with a partial ordering $\sqsubseteq$ on its
  8692. elements, a least element $\bot$ (pronounced bottom), and a join
  8693. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  8694. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  8695. working with join semi-lattices.} When two elements are ordered $m_i
  8696. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  8697. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  8698. approximation than $m_i$. The bottom element $\bot$ represents the
  8699. complete lack of information, i.e., the worst approximation. The join
  8700. operator takes two lattice elements and combines their information,
  8701. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  8702. bound}
  8703. A dataflow analysis typically involves two lattices: one lattice to
  8704. represent abstract states and another lattice that aggregates the
  8705. abstract states of all the blocks in the control-flow graph. For
  8706. liveness analysis, an abstract state is a set of locations. We form
  8707. the lattice $L$ by taking its elements to be sets of locations, the
  8708. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  8709. set, and the join operator to be set union.
  8710. %
  8711. We form a second lattice $M$ by taking its elements to be mappings
  8712. from the block labels to sets of locations (elements of $L$). We
  8713. order the mappings point-wise, using the ordering of $L$. So given any
  8714. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  8715. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  8716. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  8717. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  8718. We can think of one iteration of liveness analysis as being a function
  8719. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  8720. mapping.
  8721. \[
  8722. f(m_i) = m_{i+1}
  8723. \]
  8724. Next let us think for a moment about what a final solution $m_s$
  8725. should look like. If we perform liveness analysis using the solution
  8726. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  8727. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  8728. \[
  8729. f(m_s) = m_s
  8730. \]
  8731. Furthermore, the solution should only include locations that are
  8732. forced to be there by performing liveness analysis on the program, so
  8733. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  8734. The Kleene Fixed-Point Theorem states that if a function $f$ is
  8735. monotone (better inputs produce better outputs), then the least fixed
  8736. point of $f$ is the least upper bound of the \emph{ascending Kleene
  8737. chain} obtained by starting at $\bot$ and iterating $f$ as
  8738. follows.\index{subject}{Kleene Fixed-Point Theorem}
  8739. \[
  8740. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8741. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  8742. \]
  8743. When a lattice contains only finitely-long ascending chains, then
  8744. every Kleene chain tops out at some fixed point after a number of
  8745. iterations of $f$. So that fixed point is also a least upper
  8746. bound of the chain.
  8747. \[
  8748. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8749. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  8750. \]
  8751. The liveness analysis is indeed a monotone function and the lattice
  8752. $M$ only has finitely-long ascending chains because there are only a
  8753. finite number of variables and blocks in the program. Thus we are
  8754. guaranteed that iteratively applying liveness analysis to all blocks
  8755. in the program will eventually produce the least fixed point solution.
  8756. Next let us consider dataflow analysis in general and discuss the
  8757. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  8758. %
  8759. The algorithm has four parameters: the control-flow graph \code{G}, a
  8760. function \code{transfer} that applies the analysis to one block, the
  8761. \code{bottom} and \code{join} operator for the lattice of abstract
  8762. states. The algorithm begins by creating the bottom mapping,
  8763. represented by a hash table. It then pushes all of the nodes in the
  8764. control-flow graph onto the work list (a queue). The algorithm repeats
  8765. the \code{while} loop as long as there are items in the work list. In
  8766. each iteration, a node is popped from the work list and processed. The
  8767. \code{input} for the node is computed by taking the join of the
  8768. abstract states of all the predecessor nodes. The \code{transfer}
  8769. function is then applied to obtain the \code{output} abstract
  8770. state. If the output differs from the previous state for this block,
  8771. the mapping for this block is updated and its successor nodes are
  8772. pushed onto the work list.
  8773. \begin{figure}[tb]
  8774. \begin{lstlisting}
  8775. (define (analyze-dataflow G transfer bottom join)
  8776. (define mapping (make-hash))
  8777. (for ([v (in-vertices G)])
  8778. (dict-set! mapping v bottom))
  8779. (define worklist (make-queue))
  8780. (for ([v (in-vertices G)])
  8781. (enqueue! worklist v))
  8782. (define trans-G (transpose G))
  8783. (while (not (queue-empty? worklist))
  8784. (define node (dequeue! worklist))
  8785. (define input (for/fold ([state bottom])
  8786. ([pred (in-neighbors trans-G node)])
  8787. (join state (dict-ref mapping pred))))
  8788. (define output (transfer node input))
  8789. (cond [(not (equal? output (dict-ref mapping node)))
  8790. (dict-set! mapping node output)
  8791. (for ([v (in-neighbors G node)])
  8792. (enqueue! worklist v))]))
  8793. mapping)
  8794. \end{lstlisting}
  8795. \caption{Generic work list algorithm for dataflow analysis}
  8796. \label{fig:generic-dataflow}
  8797. \end{figure}
  8798. Having discussed the complications that arise from adding support for
  8799. assignment and loops, we turn to discussing the significant changes to
  8800. existing passes.
  8801. \section{Remove Complex Operands}
  8802. \label{sec:rco-loop}
  8803. The three new language forms, \code{while}, \code{set!}, and
  8804. \code{begin} are all complex expressions and their subexpressions are
  8805. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  8806. output language \LangFunANF{} of this pass.
  8807. \begin{figure}[tp]
  8808. \centering
  8809. \fbox{
  8810. \begin{minipage}{0.96\textwidth}
  8811. \small
  8812. \[
  8813. \begin{array}{rcl}
  8814. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  8815. \MID \VOID{} } \\
  8816. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8817. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  8818. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  8819. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8820. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8821. \end{array}
  8822. \]
  8823. \end{minipage}
  8824. }
  8825. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  8826. \label{fig:Rwhile-anf-syntax}
  8827. \end{figure}
  8828. As usual, when a complex expression appears in a grammar position that
  8829. needs to be atomic, such as the argument of a primitive operator, we
  8830. must introduce a temporary variable and bind it to the complex
  8831. expression. This approach applies, unchanged, to handle the new
  8832. language forms. For example, in the following code there are two
  8833. \code{begin} expressions appearing as arguments to \code{+}. The
  8834. output of \code{rco\_exp} is shown below, in which the \code{begin}
  8835. expressions have been bound to temporary variables. Recall that
  8836. \code{let} expressions in \LangLoopANF{} are allowed to have
  8837. arbitrary expressions in their right-hand-side expression, so it is
  8838. fine to place \code{begin} there.
  8839. \begin{lstlisting}
  8840. (let ([x0 10])
  8841. (let ([y1 0])
  8842. (+ (+ (begin (set! y1 (read)) x0)
  8843. (begin (set! x0 (read)) y1))
  8844. x0)))
  8845. |$\Rightarrow$|
  8846. (let ([x0 10])
  8847. (let ([y1 0])
  8848. (let ([tmp2 (begin (set! y1 (read)) x0)])
  8849. (let ([tmp3 (begin (set! x0 (read)) y1)])
  8850. (let ([tmp4 (+ tmp2 tmp3)])
  8851. (+ tmp4 x0))))))
  8852. \end{lstlisting}
  8853. \section{Explicate Control and \LangCLoop{}}
  8854. \label{sec:explicate-loop}
  8855. Recall that in the \code{explicate\_control} pass we define one helper
  8856. function for each kind of position in the program. For the \LangVar{}
  8857. language of integers and variables we needed kinds of positions:
  8858. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  8859. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  8860. yet another kind of position: effect position. Except for the last
  8861. subexpression, the subexpressions inside a \code{begin} are evaluated
  8862. only for their effect. Their result values are discarded. We can
  8863. generate better code by taking this fact into account.
  8864. The output language of \code{explicate\_control} is \LangCLoop{}
  8865. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  8866. \LangCLam{}. The only syntactic difference is that \code{Call},
  8867. \code{vector-set!}, and \code{read} may also appear as statements.
  8868. The most significant difference between \LangCLam{} and \LangCLoop{}
  8869. is that the control-flow graphs of the later may contain cycles.
  8870. \begin{figure}[tp]
  8871. \fbox{
  8872. \begin{minipage}{0.96\textwidth}
  8873. \small
  8874. \[
  8875. \begin{array}{lcl}
  8876. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8877. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  8878. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  8879. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  8880. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  8881. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8882. \end{array}
  8883. \]
  8884. \end{minipage}
  8885. }
  8886. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  8887. \label{fig:c7-syntax}
  8888. \end{figure}
  8889. The new auxiliary function \code{explicate\_effect} takes an expression
  8890. (in an effect position) and a promise of a continuation block. The
  8891. function returns a promise for a $\Tail$ that includes the generated
  8892. code for the input expression followed by the continuation block. If
  8893. the expression is obviously pure, that is, never causes side effects,
  8894. then the expression can be removed, so the result is just the
  8895. continuation block.
  8896. %
  8897. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  8898. case. First, you will need a fresh label $\itm{loop}$ for the top of
  8899. the loop. Recursively process the \itm{body} (in effect position)
  8900. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  8901. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  8902. \itm{body'} as the then-branch and the continuation block as the
  8903. else-branch. The result should be added to the control-flow graph with
  8904. the label \itm{loop}. The result for the whole \code{while} loop is a
  8905. \code{goto} to the \itm{loop} label. Note that the loop should only be
  8906. added to the control-flow graph if the loop is indeed used, which can
  8907. be accomplished using \code{delay}.
  8908. The auxiliary functions for tail, assignment, and predicate positions
  8909. need to be updated. The three new language forms, \code{while},
  8910. \code{set!}, and \code{begin}, can appear in assignment and tail
  8911. positions. Only \code{begin} may appear in predicate positions; the
  8912. other two have result type \code{Void}.
  8913. \section{Select Instructions}
  8914. \label{sec:select-instructions-loop}
  8915. Only three small additions are needed in the
  8916. \code{select\_instructions} pass to handle the changes to \LangCLoop{}. That
  8917. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  8918. stand-alone statements instead of only appearing on the right-hand
  8919. side of an assignment statement. The code generation is nearly
  8920. identical; just leave off the instruction for moving the result into
  8921. the left-hand side.
  8922. \section{Register Allocation}
  8923. \label{sec:register-allocation-loop}
  8924. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  8925. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  8926. which complicates the liveness analysis needed for register
  8927. allocation.
  8928. \subsection{Liveness Analysis}
  8929. \label{sec:liveness-analysis-r8}
  8930. We recommend using the generic \code{analyze-dataflow} function that
  8931. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  8932. perform liveness analysis, replacing the code in
  8933. \code{uncover\_live} that processed the basic blocks in topological
  8934. order (Section~\ref{sec:liveness-analysis-Lif}).
  8935. The \code{analyze-dataflow} function has four parameters.
  8936. \begin{enumerate}
  8937. \item The first parameter \code{G} should be a directed graph from the
  8938. \code{racket/graph} package (see the sidebar in
  8939. Section~\ref{sec:build-interference}) that represents the
  8940. control-flow graph.
  8941. \item The second parameter \code{transfer} is a function that applies
  8942. liveness analysis to a basic block. It takes two parameters: the
  8943. label for the block to analyze and the live-after set for that
  8944. block. The transfer function should return the live-before set for
  8945. the block. Also, as a side-effect, it should update the block's
  8946. $\itm{info}$ with the liveness information for each instruction. To
  8947. implement the \code{transfer} function, you should be able to reuse
  8948. the code you already have for analyzing basic blocks.
  8949. \item The third and fourth parameters of \code{analyze-dataflow} are
  8950. \code{bottom} and \code{join} for the lattice of abstract states,
  8951. i.e. sets of locations. The bottom of the lattice is the empty set
  8952. \code{(set)} and the join operator is \code{set-union}.
  8953. \end{enumerate}
  8954. \begin{figure}[p]
  8955. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8956. \node (Rfun) at (0,2) {\large \LangLoop{}};
  8957. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  8958. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  8959. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  8960. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  8961. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  8962. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  8963. \node (F1-4) at (6,2) {\large \LangLoop{}};
  8964. \node (F1-5) at (9,2) {\large \LangLoop{}};
  8965. \node (C3-2) at (3,0) {\large \LangCLoop{}};
  8966. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8967. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8968. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8969. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8970. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8971. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8972. %% \path[->,bend left=15] (Rfun) edge [above] node
  8973. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  8974. \path[->,bend left=15] (Rfun) edge [above] node
  8975. {\ttfamily\footnotesize shrink} (Rfun-2);
  8976. \path[->,bend left=15] (Rfun-2) edge [above] node
  8977. {\ttfamily\footnotesize uniquify} (F1-4);
  8978. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  8979. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  8980. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  8981. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  8982. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  8983. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  8984. %% \path[->,bend right=15] (F1-2) edge [above] node
  8985. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  8986. %% \path[->,bend right=15] (F1-3) edge [above] node
  8987. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8988. \path[->,bend left=15] (F1-4) edge [above] node
  8989. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  8990. \path[->,bend left=15] (F1-5) edge [right] node
  8991. {\ttfamily\footnotesize explicate\_control} (C3-2);
  8992. \path[->,bend left=15] (C3-2) edge [left] node
  8993. {\ttfamily\footnotesize select\_instr.} (x86-2);
  8994. \path[->,bend right=15] (x86-2) edge [left] node
  8995. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8996. \path[->,bend right=15] (x86-2-1) edge [below] node
  8997. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8998. \path[->,bend right=15] (x86-2-2) edge [left] node
  8999. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9000. \path[->,bend left=15] (x86-3) edge [above] node
  9001. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9002. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  9003. \end{tikzpicture}
  9004. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  9005. \label{fig:Rwhile-passes}
  9006. \end{figure}
  9007. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9008. for the compilation of \LangLoop{}.
  9009. % Further Reading: dataflow analysis
  9010. \fi
  9011. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9012. \chapter{Tuples and Garbage Collection}
  9013. \label{ch:Rvec}
  9014. \index{subject}{tuple}
  9015. \index{subject}{vector}
  9016. \if\edition\racketEd
  9017. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9018. %% all the IR grammars are spelled out! \\ --Jeremy}
  9019. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9020. %% the root stack. \\ --Jeremy}
  9021. In this chapter we study the implementation of mutable tuples, called
  9022. vectors in Racket. This language feature is the first to use the
  9023. computer's \emph{heap}\index{subject}{heap} because the lifetime of a
  9024. Racket tuple is indefinite, that is, a tuple lives forever from the
  9025. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  9026. is important to reclaim the space associated with a tuple when it is
  9027. no longer needed, which is why we also study \emph{garbage
  9028. collection} \index{garbage collection} techniques in this chapter.
  9029. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9030. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  9031. language of Chapter~\ref{ch:Lif} with vectors and Racket's
  9032. \code{void} value. The reason for including the later is that the
  9033. \code{vector-set!} operation returns a value of type
  9034. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  9035. called the \code{Unit} type in the programming languages
  9036. literature. Racket's \code{Void} type is inhabited by a single value
  9037. \code{void} which corresponds to \code{unit} or \code{()} in the
  9038. literature~\citep{Pierce:2002hj}.}.
  9039. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9040. copying live objects back and forth between two halves of the
  9041. heap. The garbage collector requires coordination with the compiler so
  9042. that it can see all of the \emph{root} pointers, that is, pointers in
  9043. registers or on the procedure call stack.
  9044. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9045. discuss all the necessary changes and additions to the compiler
  9046. passes, including a new compiler pass named \code{expose-allocation}.
  9047. \section{The \LangVec{} Language}
  9048. \label{sec:r3}
  9049. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  9050. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  9051. \LangVec{} language includes three new forms: \code{vector} for creating a
  9052. tuple, \code{vector-ref} for reading an element of a tuple, and
  9053. \code{vector-set!} for writing to an element of a tuple. The program
  9054. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  9055. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  9056. the 3-tuple, demonstrating that tuples are first-class values. The
  9057. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  9058. of the \key{if} is taken. The element at index $0$ of \code{t} is
  9059. \code{40}, to which we add \code{2}, the element at index $0$ of the
  9060. 1-tuple. So the result of the program is \code{42}.
  9061. \begin{figure}[tbp]
  9062. \centering
  9063. \fbox{
  9064. \begin{minipage}{0.96\textwidth}
  9065. \[
  9066. \begin{array}{lcl}
  9067. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  9068. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  9069. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9070. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9071. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  9072. \MID \LP\key{and}\;\Exp\;\Exp\RP
  9073. \MID \LP\key{or}\;\Exp\;\Exp\RP
  9074. \MID \LP\key{not}\;\Exp\RP } \\
  9075. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  9076. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9077. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  9078. \MID \LP\key{vector-length}\;\Exp\RP \\
  9079. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9080. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  9081. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  9082. \LangVecM{} &::=& \Exp
  9083. \end{array}
  9084. \]
  9085. \end{minipage}
  9086. }
  9087. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  9088. (Figure~\ref{fig:Lif-concrete-syntax}).}
  9089. \label{fig:Rvec-concrete-syntax}
  9090. \end{figure}
  9091. \begin{figure}[tbp]
  9092. \begin{lstlisting}
  9093. (let ([t (vector 40 #t (vector 2))])
  9094. (if (vector-ref t 1)
  9095. (+ (vector-ref t 0)
  9096. (vector-ref (vector-ref t 2) 0))
  9097. 44))
  9098. \end{lstlisting}
  9099. \caption{Example program that creates tuples and reads from them.}
  9100. \label{fig:vector-eg}
  9101. \end{figure}
  9102. \begin{figure}[tp]
  9103. \centering
  9104. \fbox{
  9105. \begin{minipage}{0.96\textwidth}
  9106. \[
  9107. \begin{array}{lcl}
  9108. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  9109. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9110. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  9111. \MID \BOOL{\itm{bool}}
  9112. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9113. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  9114. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9115. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  9116. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9117. \end{array}
  9118. \]
  9119. \end{minipage}
  9120. }
  9121. \caption{The abstract syntax of \LangVec{}.}
  9122. \label{fig:Rvec-syntax}
  9123. \end{figure}
  9124. \index{subject}{allocate}
  9125. \index{subject}{heap allocate}
  9126. Tuples are our first encounter with heap-allocated data, which raises
  9127. several interesting issues. First, variable binding performs a
  9128. shallow-copy when dealing with tuples, which means that different
  9129. variables can refer to the same tuple, that is, different variables
  9130. can be \emph{aliases} for the same entity. Consider the following
  9131. example in which both \code{t1} and \code{t2} refer to the same tuple.
  9132. Thus, the mutation through \code{t2} is visible when referencing the
  9133. tuple from \code{t1}, so the result of this program is \code{42}.
  9134. \index{subject}{alias}\index{subject}{mutation}
  9135. \begin{center}
  9136. \begin{minipage}{0.96\textwidth}
  9137. \begin{lstlisting}
  9138. (let ([t1 (vector 3 7)])
  9139. (let ([t2 t1])
  9140. (let ([_ (vector-set! t2 0 42)])
  9141. (vector-ref t1 0))))
  9142. \end{lstlisting}
  9143. \end{minipage}
  9144. \end{center}
  9145. The next issue concerns the lifetime of tuples. Of course, they are
  9146. created by the \code{vector} form, but when does their lifetime end?
  9147. Notice that \LangVec{} does not include an operation for deleting
  9148. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  9149. of static scoping. For example, the following program returns
  9150. \code{42} even though the variable \code{w} goes out of scope prior to
  9151. the \code{vector-ref} that reads from the vector it was bound to.
  9152. \begin{center}
  9153. \begin{minipage}{0.96\textwidth}
  9154. \begin{lstlisting}
  9155. (let ([v (vector (vector 44))])
  9156. (let ([x (let ([w (vector 42)])
  9157. (let ([_ (vector-set! v 0 w)])
  9158. 0))])
  9159. (+ x (vector-ref (vector-ref v 0) 0))))
  9160. \end{lstlisting}
  9161. \end{minipage}
  9162. \end{center}
  9163. From the perspective of programmer-observable behavior, tuples live
  9164. forever. Of course, if they really lived forever, then many programs
  9165. would run out of memory.\footnote{The \LangVec{} language does not have
  9166. looping or recursive functions, so it is nigh impossible to write a
  9167. program in \LangVec{} that will run out of memory. However, we add
  9168. recursive functions in the next Chapter!} A Racket implementation
  9169. must therefore perform automatic garbage collection.
  9170. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  9171. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  9172. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  9173. terms of the corresponding operations in Racket. One subtle point is
  9174. that the \code{vector-set!} operation returns the \code{\#<void>}
  9175. value. The \code{\#<void>} value can be passed around just like other
  9176. values inside an \LangVec{} program and a \code{\#<void>} value can be
  9177. compared for equality with another \code{\#<void>} value. However,
  9178. there are no other operations specific to the the \code{\#<void>}
  9179. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  9180. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  9181. otherwise.
  9182. \begin{figure}[tbp]
  9183. \begin{lstlisting}
  9184. (define interp-Rvec_class
  9185. (class interp-Lif_class
  9186. (super-new)
  9187. (define/override (interp-op op)
  9188. (match op
  9189. ['eq? (lambda (v1 v2)
  9190. (cond [(or (and (fixnum? v1) (fixnum? v2))
  9191. (and (boolean? v1) (boolean? v2))
  9192. (and (vector? v1) (vector? v2))
  9193. (and (void? v1) (void? v2)))
  9194. (eq? v1 v2)]))]
  9195. ['vector vector]
  9196. ['vector-length vector-length]
  9197. ['vector-ref vector-ref]
  9198. ['vector-set! vector-set!]
  9199. [else (super interp-op op)]
  9200. ))
  9201. (define/override ((interp-exp env) e)
  9202. (define recur (interp-exp env))
  9203. (match e
  9204. [(HasType e t) (recur e)]
  9205. [(Void) (void)]
  9206. [else ((super interp-exp env) e)]
  9207. ))
  9208. ))
  9209. (define (interp-Rvec p)
  9210. (send (new interp-Rvec_class) interp-program p))
  9211. \end{lstlisting}
  9212. \caption{Interpreter for the \LangVec{} language.}
  9213. \label{fig:interp-Rvec}
  9214. \end{figure}
  9215. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  9216. deserves some explanation. When allocating a vector, we need to know
  9217. which elements of the vector are pointers (i.e. are also vectors). We
  9218. can obtain this information during type checking. The type checker in
  9219. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  9220. expression, it also wraps every \key{vector} creation with the form
  9221. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  9222. %
  9223. To create the s-expression for the \code{Vector} type in
  9224. Figure~\ref{fig:type-check-Rvec}, we use the
  9225. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  9226. operator} \code{,@} to insert the list \code{t*} without its usual
  9227. start and end parentheses. \index{subject}{unquote-slicing}
  9228. \begin{figure}[tp]
  9229. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9230. (define type-check-Rvec_class
  9231. (class type-check-Lif_class
  9232. (super-new)
  9233. (inherit check-type-equal?)
  9234. (define/override (type-check-exp env)
  9235. (lambda (e)
  9236. (define recur (type-check-exp env))
  9237. (match e
  9238. [(Void) (values (Void) 'Void)]
  9239. [(Prim 'vector es)
  9240. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  9241. (define t `(Vector ,@t*))
  9242. (values (HasType (Prim 'vector e*) t) t)]
  9243. [(Prim 'vector-ref (list e1 (Int i)))
  9244. (define-values (e1^ t) (recur e1))
  9245. (match t
  9246. [`(Vector ,ts ...)
  9247. (unless (and (0 . <= . i) (i . < . (length ts)))
  9248. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  9249. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  9250. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  9251. [(Prim 'vector-set! (list e1 (Int i) arg) )
  9252. (define-values (e-vec t-vec) (recur e1))
  9253. (define-values (e-arg^ t-arg) (recur arg))
  9254. (match t-vec
  9255. [`(Vector ,ts ...)
  9256. (unless (and (0 . <= . i) (i . < . (length ts)))
  9257. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  9258. (check-type-equal? (list-ref ts i) t-arg e)
  9259. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  9260. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  9261. [(Prim 'vector-length (list e))
  9262. (define-values (e^ t) (recur e))
  9263. (match t
  9264. [`(Vector ,ts ...)
  9265. (values (Prim 'vector-length (list e^)) 'Integer)]
  9266. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  9267. [(Prim 'eq? (list arg1 arg2))
  9268. (define-values (e1 t1) (recur arg1))
  9269. (define-values (e2 t2) (recur arg2))
  9270. (match* (t1 t2)
  9271. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9272. [(other wise) (check-type-equal? t1 t2 e)])
  9273. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9274. [(HasType (Prim 'vector es) t)
  9275. ((type-check-exp env) (Prim 'vector es))]
  9276. [(HasType e1 t)
  9277. (define-values (e1^ t^) (recur e1))
  9278. (check-type-equal? t t^ e)
  9279. (values (HasType e1^ t) t)]
  9280. [else ((super type-check-exp env) e)]
  9281. )))
  9282. ))
  9283. (define (type-check-Rvec p)
  9284. (send (new type-check-Rvec_class) type-check-program p))
  9285. \end{lstlisting}
  9286. \caption{Type checker for the \LangVec{} language.}
  9287. \label{fig:type-check-Rvec}
  9288. \end{figure}
  9289. \section{Garbage Collection}
  9290. \label{sec:GC}
  9291. Here we study a relatively simple algorithm for garbage collection
  9292. that is the basis of state-of-the-art garbage
  9293. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  9294. particular, we describe a two-space copying
  9295. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  9296. perform the
  9297. copy~\citep{Cheney:1970aa}.
  9298. \index{subject}{copying collector}
  9299. \index{subject}{two-space copying collector}
  9300. Figure~\ref{fig:copying-collector} gives a
  9301. coarse-grained depiction of what happens in a two-space collector,
  9302. showing two time steps, prior to garbage collection (on the top) and
  9303. after garbage collection (on the bottom). In a two-space collector,
  9304. the heap is divided into two parts named the FromSpace and the
  9305. ToSpace. Initially, all allocations go to the FromSpace until there is
  9306. not enough room for the next allocation request. At that point, the
  9307. garbage collector goes to work to make more room.
  9308. \index{subject}{ToSpace}
  9309. \index{subject}{FromSpace}
  9310. The garbage collector must be careful not to reclaim tuples that will
  9311. be used by the program in the future. Of course, it is impossible in
  9312. general to predict what a program will do, but we can over approximate
  9313. the will-be-used tuples by preserving all tuples that could be
  9314. accessed by \emph{any} program given the current computer state. A
  9315. program could access any tuple whose address is in a register or on
  9316. the procedure call stack. These addresses are called the \emph{root
  9317. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  9318. transitively reachable from the root set. Thus, it is safe for the
  9319. garbage collector to reclaim the tuples that are not reachable in this
  9320. way.
  9321. So the goal of the garbage collector is twofold:
  9322. \begin{enumerate}
  9323. \item preserve all tuple that are reachable from the root set via a
  9324. path of pointers, that is, the \emph{live} tuples, and
  9325. \item reclaim the memory of everything else, that is, the
  9326. \emph{garbage}.
  9327. \end{enumerate}
  9328. A copying collector accomplishes this by copying all of the live
  9329. objects from the FromSpace into the ToSpace and then performs a sleight
  9330. of hand, treating the ToSpace as the new FromSpace and the old
  9331. FromSpace as the new ToSpace. In the example of
  9332. Figure~\ref{fig:copying-collector}, there are three pointers in the
  9333. root set, one in a register and two on the stack. All of the live
  9334. objects have been copied to the ToSpace (the right-hand side of
  9335. Figure~\ref{fig:copying-collector}) in a way that preserves the
  9336. pointer relationships. For example, the pointer in the register still
  9337. points to a 2-tuple whose first element is a 3-tuple and whose second
  9338. element is a 2-tuple. There are four tuples that are not reachable
  9339. from the root set and therefore do not get copied into the ToSpace.
  9340. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  9341. created by a well-typed program in \LangVec{} because it contains a
  9342. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  9343. We design the garbage collector to deal with cycles to begin with so
  9344. we will not need to revisit this issue.
  9345. \begin{figure}[tbp]
  9346. \centering
  9347. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  9348. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  9349. \caption{A copying collector in action.}
  9350. \label{fig:copying-collector}
  9351. \end{figure}
  9352. There are many alternatives to copying collectors (and their bigger
  9353. siblings, the generational collectors) when its comes to garbage
  9354. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  9355. reference counting~\citep{Collins:1960aa}. The strengths of copying
  9356. collectors are that allocation is fast (just a comparison and pointer
  9357. increment), there is no fragmentation, cyclic garbage is collected,
  9358. and the time complexity of collection only depends on the amount of
  9359. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  9360. main disadvantages of a two-space copying collector is that it uses a
  9361. lot of space and takes a long time to perform the copy, though these
  9362. problems are ameliorated in generational collectors. Racket and
  9363. Scheme programs tend to allocate many small objects and generate a lot
  9364. of garbage, so copying and generational collectors are a good fit.
  9365. Garbage collection is an active research topic, especially concurrent
  9366. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  9367. developing new techniques and revisiting old
  9368. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  9369. meet every year at the International Symposium on Memory Management to
  9370. present these findings.
  9371. \subsection{Graph Copying via Cheney's Algorithm}
  9372. \label{sec:cheney}
  9373. \index{subject}{Cheney's algorithm}
  9374. Let us take a closer look at the copying of the live objects. The
  9375. allocated objects and pointers can be viewed as a graph and we need to
  9376. copy the part of the graph that is reachable from the root set. To
  9377. make sure we copy all of the reachable vertices in the graph, we need
  9378. an exhaustive graph traversal algorithm, such as depth-first search or
  9379. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  9380. such algorithms take into account the possibility of cycles by marking
  9381. which vertices have already been visited, so as to ensure termination
  9382. of the algorithm. These search algorithms also use a data structure
  9383. such as a stack or queue as a to-do list to keep track of the vertices
  9384. that need to be visited. We use breadth-first search and a trick
  9385. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  9386. and copying tuples into the ToSpace.
  9387. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  9388. copy progresses. The queue is represented by a chunk of contiguous
  9389. memory at the beginning of the ToSpace, using two pointers to track
  9390. the front and the back of the queue. The algorithm starts by copying
  9391. all tuples that are immediately reachable from the root set into the
  9392. ToSpace to form the initial queue. When we copy a tuple, we mark the
  9393. old tuple to indicate that it has been visited. We discuss how this
  9394. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  9395. pointers inside the copied tuples in the queue still point back to the
  9396. FromSpace. Once the initial queue has been created, the algorithm
  9397. enters a loop in which it repeatedly processes the tuple at the front
  9398. of the queue and pops it off the queue. To process a tuple, the
  9399. algorithm copies all the tuple that are directly reachable from it to
  9400. the ToSpace, placing them at the back of the queue. The algorithm then
  9401. updates the pointers in the popped tuple so they point to the newly
  9402. copied tuples.
  9403. \begin{figure}[tbp]
  9404. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  9405. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  9406. \label{fig:cheney}
  9407. \end{figure}
  9408. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  9409. tuple whose second element is $42$ to the back of the queue. The other
  9410. pointer goes to a tuple that has already been copied, so we do not
  9411. need to copy it again, but we do need to update the pointer to the new
  9412. location. This can be accomplished by storing a \emph{forwarding
  9413. pointer} to the new location in the old tuple, back when we initially
  9414. copied the tuple into the ToSpace. This completes one step of the
  9415. algorithm. The algorithm continues in this way until the front of the
  9416. queue is empty, that is, until the front catches up with the back.
  9417. \subsection{Data Representation}
  9418. \label{sec:data-rep-gc}
  9419. The garbage collector places some requirements on the data
  9420. representations used by our compiler. First, the garbage collector
  9421. needs to distinguish between pointers and other kinds of data. There
  9422. are several ways to accomplish this.
  9423. \begin{enumerate}
  9424. \item Attached a tag to each object that identifies what type of
  9425. object it is~\citep{McCarthy:1960dz}.
  9426. \item Store different types of objects in different
  9427. regions~\citep{Steele:1977ab}.
  9428. \item Use type information from the program to either generate
  9429. type-specific code for collecting or to generate tables that can
  9430. guide the
  9431. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  9432. \end{enumerate}
  9433. Dynamically typed languages, such as Lisp, need to tag objects
  9434. anyways, so option 1 is a natural choice for those languages.
  9435. However, \LangVec{} is a statically typed language, so it would be
  9436. unfortunate to require tags on every object, especially small and
  9437. pervasive objects like integers and Booleans. Option 3 is the
  9438. best-performing choice for statically typed languages, but comes with
  9439. a relatively high implementation complexity. To keep this chapter
  9440. within a 2-week time budget, we recommend a combination of options 1
  9441. and 2, using separate strategies for the stack and the heap.
  9442. Regarding the stack, we recommend using a separate stack for pointers,
  9443. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  9444. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  9445. is, when a local variable needs to be spilled and is of type
  9446. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  9447. stack instead of the normal procedure call stack. Furthermore, we
  9448. always spill vector-typed variables if they are live during a call to
  9449. the collector, thereby ensuring that no pointers are in registers
  9450. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  9451. example from Figure~\ref{fig:copying-collector} and contrasts it with
  9452. the data layout using a root stack. The root stack contains the two
  9453. pointers from the regular stack and also the pointer in the second
  9454. register.
  9455. \begin{figure}[tbp]
  9456. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  9457. \caption{Maintaining a root stack to facilitate garbage collection.}
  9458. \label{fig:shadow-stack}
  9459. \end{figure}
  9460. The problem of distinguishing between pointers and other kinds of data
  9461. also arises inside of each tuple on the heap. We solve this problem by
  9462. attaching a tag, an extra 64-bits, to each
  9463. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  9464. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  9465. that we have drawn the bits in a big-endian way, from right-to-left,
  9466. with bit location 0 (the least significant bit) on the far right,
  9467. which corresponds to the direction of the x86 shifting instructions
  9468. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  9469. is dedicated to specifying which elements of the tuple are pointers,
  9470. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  9471. indicates there is a pointer and a 0 bit indicates some other kind of
  9472. data. The pointer mask starts at bit location 7. We have limited
  9473. tuples to a maximum size of 50 elements, so we just need 50 bits for
  9474. the pointer mask. The tag also contains two other pieces of
  9475. information. The length of the tuple (number of elements) is stored in
  9476. bits location 1 through 6. Finally, the bit at location 0 indicates
  9477. whether the tuple has yet to be copied to the ToSpace. If the bit has
  9478. value 1, then this tuple has not yet been copied. If the bit has
  9479. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  9480. of a pointer are always zero anyways because our tuples are 8-byte
  9481. aligned.)
  9482. \begin{figure}[tbp]
  9483. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  9484. \caption{Representation of tuples in the heap.}
  9485. \label{fig:tuple-rep}
  9486. \end{figure}
  9487. \subsection{Implementation of the Garbage Collector}
  9488. \label{sec:organize-gz}
  9489. \index{subject}{prelude}
  9490. An implementation of the copying collector is provided in the
  9491. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  9492. interface to the garbage collector that is used by the compiler. The
  9493. \code{initialize} function creates the FromSpace, ToSpace, and root
  9494. stack and should be called in the prelude of the \code{main}
  9495. function. The arguments of \code{initialize} are the root stack size
  9496. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  9497. good choice for both. The \code{initialize} function puts the address
  9498. of the beginning of the FromSpace into the global variable
  9499. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  9500. the address that is 1-past the last element of the FromSpace. (We use
  9501. half-open intervals to represent chunks of
  9502. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  9503. points to the first element of the root stack.
  9504. As long as there is room left in the FromSpace, your generated code
  9505. can allocate tuples simply by moving the \code{free\_ptr} forward.
  9506. %
  9507. The amount of room left in FromSpace is the difference between the
  9508. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  9509. function should be called when there is not enough room left in the
  9510. FromSpace for the next allocation. The \code{collect} function takes
  9511. a pointer to the current top of the root stack (one past the last item
  9512. that was pushed) and the number of bytes that need to be
  9513. allocated. The \code{collect} function performs the copying collection
  9514. and leaves the heap in a state such that the next allocation will
  9515. succeed.
  9516. \begin{figure}[tbp]
  9517. \begin{lstlisting}
  9518. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  9519. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  9520. int64_t* free_ptr;
  9521. int64_t* fromspace_begin;
  9522. int64_t* fromspace_end;
  9523. int64_t** rootstack_begin;
  9524. \end{lstlisting}
  9525. \caption{The compiler's interface to the garbage collector.}
  9526. \label{fig:gc-header}
  9527. \end{figure}
  9528. %% \begin{exercise}
  9529. %% In the file \code{runtime.c} you will find the implementation of
  9530. %% \code{initialize} and a partial implementation of \code{collect}.
  9531. %% The \code{collect} function calls another function, \code{cheney},
  9532. %% to perform the actual copy, and that function is left to the reader
  9533. %% to implement. The following is the prototype for \code{cheney}.
  9534. %% \begin{lstlisting}
  9535. %% static void cheney(int64_t** rootstack_ptr);
  9536. %% \end{lstlisting}
  9537. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  9538. %% rootstack (which is an array of pointers). The \code{cheney} function
  9539. %% also communicates with \code{collect} through the global
  9540. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  9541. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  9542. %% the ToSpace:
  9543. %% \begin{lstlisting}
  9544. %% static int64_t* tospace_begin;
  9545. %% static int64_t* tospace_end;
  9546. %% \end{lstlisting}
  9547. %% The job of the \code{cheney} function is to copy all the live
  9548. %% objects (reachable from the root stack) into the ToSpace, update
  9549. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  9550. %% update the root stack so that it points to the objects in the
  9551. %% ToSpace, and finally to swap the global pointers for the FromSpace
  9552. %% and ToSpace.
  9553. %% \end{exercise}
  9554. %% \section{Compiler Passes}
  9555. %% \label{sec:code-generation-gc}
  9556. The introduction of garbage collection has a non-trivial impact on our
  9557. compiler passes. We introduce a new compiler pass named
  9558. \code{expose-allocation}. We make
  9559. significant changes to \code{select\_instructions},
  9560. \code{build\_interference}, \code{allocate\_registers}, and
  9561. \code{print\_x86} and make minor changes in several more passes. The
  9562. following program will serve as our running example. It creates two
  9563. tuples, one nested inside the other. Both tuples have length one. The
  9564. program accesses the element in the inner tuple tuple via two vector
  9565. references.
  9566. % tests/s2_17.rkt
  9567. \begin{lstlisting}
  9568. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  9569. \end{lstlisting}
  9570. \section{Shrink}
  9571. \label{sec:shrink-Rvec}
  9572. Recall that the \code{shrink} pass translates the primitives operators
  9573. into a smaller set of primitives. Because this pass comes after type
  9574. checking, but before the passes that require the type information in
  9575. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  9576. to wrap \code{HasType} around each AST node that it generates.
  9577. \section{Expose Allocation}
  9578. \label{sec:expose-allocation}
  9579. The pass \code{expose-allocation} lowers the \code{vector} creation
  9580. form into a conditional call to the collector followed by the
  9581. allocation. We choose to place the \code{expose-allocation} pass
  9582. before \code{remove\_complex\_operands} because the code generated by
  9583. \code{expose-allocation} contains complex operands. We also place
  9584. \code{expose-allocation} before \code{explicate\_control} because
  9585. \code{expose-allocation} introduces new variables using \code{let},
  9586. but \code{let} is gone after \code{explicate\_control}.
  9587. The output of \code{expose-allocation} is a language \LangAlloc{} that
  9588. extends \LangVec{} with the three new forms that we use in the translation
  9589. of the \code{vector} form.
  9590. \[
  9591. \begin{array}{lcl}
  9592. \Exp &::=& \cdots
  9593. \MID (\key{collect} \,\itm{int})
  9594. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  9595. \MID (\key{global-value} \,\itm{name})
  9596. \end{array}
  9597. \]
  9598. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  9599. $n$ bytes. It will become a call to the \code{collect} function in
  9600. \code{runtime.c} in \code{select\_instructions}. The
  9601. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  9602. \index{subject}{allocate}
  9603. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  9604. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  9605. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  9606. a global variable, such as \code{free\_ptr}.
  9607. In the following, we show the transformation for the \code{vector}
  9608. form into 1) a sequence of let-bindings for the initializing
  9609. expressions, 2) a conditional call to \code{collect}, 3) a call to
  9610. \code{allocate}, and 4) the initialization of the vector. In the
  9611. following, \itm{len} refers to the length of the vector and
  9612. \itm{bytes} is how many total bytes need to be allocated for the
  9613. vector, which is 8 for the tag plus \itm{len} times 8.
  9614. \begin{lstlisting}
  9615. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  9616. |$\Longrightarrow$|
  9617. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  9618. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  9619. (global-value fromspace_end))
  9620. (void)
  9621. (collect |\itm{bytes}|))])
  9622. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  9623. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  9624. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  9625. |$v$|) ... )))) ...)
  9626. \end{lstlisting}
  9627. In the above, we suppressed all of the \code{has-type} forms in the
  9628. output for the sake of readability. The placement of the initializing
  9629. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  9630. sequence of \code{vector-set!} is important, as those expressions may
  9631. trigger garbage collection and we cannot have an allocated but
  9632. uninitialized tuple on the heap during a collection.
  9633. Figure~\ref{fig:expose-alloc-output} shows the output of the
  9634. \code{expose-allocation} pass on our running example.
  9635. \begin{figure}[tbp]
  9636. % tests/s2_17.rkt
  9637. \begin{lstlisting}
  9638. (vector-ref
  9639. (vector-ref
  9640. (let ([vecinit7976
  9641. (let ([vecinit7972 42])
  9642. (let ([collectret7974
  9643. (if (< (+ (global-value free_ptr) 16)
  9644. (global-value fromspace_end))
  9645. (void)
  9646. (collect 16)
  9647. )])
  9648. (let ([alloc7971 (allocate 1 (Vector Integer))])
  9649. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  9650. alloc7971)
  9651. )
  9652. )
  9653. )
  9654. ])
  9655. (let ([collectret7978
  9656. (if (< (+ (global-value free_ptr) 16)
  9657. (global-value fromspace_end))
  9658. (void)
  9659. (collect 16)
  9660. )])
  9661. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  9662. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  9663. alloc7975)
  9664. )
  9665. )
  9666. )
  9667. 0)
  9668. 0)
  9669. \end{lstlisting}
  9670. \caption{Output of the \code{expose-allocation} pass, minus
  9671. all of the \code{has-type} forms.}
  9672. \label{fig:expose-alloc-output}
  9673. \end{figure}
  9674. \section{Remove Complex Operands}
  9675. \label{sec:remove-complex-opera-Rvec}
  9676. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  9677. should all be treated as complex operands.
  9678. %% A new case for
  9679. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  9680. %% handled carefully to prevent the \code{Prim} node from being separated
  9681. %% from its enclosing \code{HasType}.
  9682. Figure~\ref{fig:Rvec-anf-syntax}
  9683. shows the grammar for the output language \LangVecANF{} of this
  9684. pass, which is \LangVec{} in administrative normal form.
  9685. \begin{figure}[tp]
  9686. \centering
  9687. \fbox{
  9688. \begin{minipage}{0.96\textwidth}
  9689. \small
  9690. \[
  9691. \begin{array}{rcl}
  9692. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  9693. \MID \VOID{} \\
  9694. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  9695. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  9696. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9697. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  9698. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  9699. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  9700. \MID \LP\key{GlobalValue}~\Var\RP\\
  9701. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  9702. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9703. \end{array}
  9704. \]
  9705. \end{minipage}
  9706. }
  9707. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  9708. \label{fig:Rvec-anf-syntax}
  9709. \end{figure}
  9710. \section{Explicate Control and the \LangCVec{} language}
  9711. \label{sec:explicate-control-r3}
  9712. \begin{figure}[tp]
  9713. \fbox{
  9714. \begin{minipage}{0.96\textwidth}
  9715. \small
  9716. \[
  9717. \begin{array}{lcl}
  9718. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  9719. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  9720. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  9721. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  9722. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  9723. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  9724. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  9725. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  9726. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  9727. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  9728. \MID \LP\key{Collect} \,\itm{int}\RP \\
  9729. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  9730. \MID \GOTO{\itm{label}} } \\
  9731. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9732. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  9733. \end{array}
  9734. \]
  9735. \end{minipage}
  9736. }
  9737. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  9738. (Figure~\ref{fig:c1-syntax}).}
  9739. \label{fig:c2-syntax}
  9740. \end{figure}
  9741. The output of \code{explicate\_control} is a program in the
  9742. intermediate language \LangCVec{}, whose abstract syntax is defined in
  9743. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  9744. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  9745. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  9746. \key{vector-set!}, and \key{global-value} expressions and the
  9747. \code{collect} statement. The \code{explicate\_control} pass can treat
  9748. these new forms much like the other expression forms that we've
  9749. already encoutered.
  9750. \section{Select Instructions and the \LangXGlobal{} Language}
  9751. \label{sec:select-instructions-gc}
  9752. \index{subject}{instruction selection}
  9753. %% void (rep as zero)
  9754. %% allocate
  9755. %% collect (callq collect)
  9756. %% vector-ref
  9757. %% vector-set!
  9758. %% global (postpone)
  9759. In this pass we generate x86 code for most of the new operations that
  9760. were needed to compile tuples, including \code{Allocate},
  9761. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  9762. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  9763. the later has a different concrete syntax (see
  9764. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  9765. \index{subject}{x86}
  9766. The \code{vector-ref} and \code{vector-set!} forms translate into
  9767. \code{movq} instructions. (The plus one in the offset is to get past
  9768. the tag at the beginning of the tuple representation.)
  9769. \begin{lstlisting}
  9770. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  9771. |$\Longrightarrow$|
  9772. movq |$\itm{vec}'$|, %r11
  9773. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  9774. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  9775. |$\Longrightarrow$|
  9776. movq |$\itm{vec}'$|, %r11
  9777. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  9778. movq $0, |$\itm{lhs'}$|
  9779. \end{lstlisting}
  9780. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  9781. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  9782. register \code{r11} ensures that offset expression
  9783. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  9784. removing \code{r11} from consideration by the register allocating.
  9785. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  9786. \code{rax}. Then the generated code for \code{vector-set!} would be
  9787. \begin{lstlisting}
  9788. movq |$\itm{vec}'$|, %rax
  9789. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  9790. movq $0, |$\itm{lhs}'$|
  9791. \end{lstlisting}
  9792. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  9793. \code{patch\_instructions} would insert a move through \code{rax}
  9794. as follows.
  9795. \begin{lstlisting}
  9796. movq |$\itm{vec}'$|, %rax
  9797. movq |$\itm{arg}'$|, %rax
  9798. movq %rax, |$8(n+1)$|(%rax)
  9799. movq $0, |$\itm{lhs}'$|
  9800. \end{lstlisting}
  9801. But the above sequence of instructions does not work because we're
  9802. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  9803. $\itm{arg}'$) at the same time!
  9804. We compile the \code{allocate} form to operations on the
  9805. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  9806. is the next free address in the FromSpace, so we copy it into
  9807. \code{r11} and then move it forward by enough space for the tuple
  9808. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  9809. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  9810. initialize the \itm{tag} and finally copy the address in \code{r11} to
  9811. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  9812. tag is organized. We recommend using the Racket operations
  9813. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  9814. during compilation. The type annotation in the \code{vector} form is
  9815. used to determine the pointer mask region of the tag.
  9816. \begin{lstlisting}
  9817. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  9818. |$\Longrightarrow$|
  9819. movq free_ptr(%rip), %r11
  9820. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  9821. movq $|$\itm{tag}$|, 0(%r11)
  9822. movq %r11, |$\itm{lhs}'$|
  9823. \end{lstlisting}
  9824. The \code{collect} form is compiled to a call to the \code{collect}
  9825. function in the runtime. The arguments to \code{collect} are 1) the
  9826. top of the root stack and 2) the number of bytes that need to be
  9827. allocated. We use another dedicated register, \code{r15}, to
  9828. store the pointer to the top of the root stack. So \code{r15} is not
  9829. available for use by the register allocator.
  9830. \begin{lstlisting}
  9831. (collect |$\itm{bytes}$|)
  9832. |$\Longrightarrow$|
  9833. movq %r15, %rdi
  9834. movq $|\itm{bytes}|, %rsi
  9835. callq collect
  9836. \end{lstlisting}
  9837. \begin{figure}[tp]
  9838. \fbox{
  9839. \begin{minipage}{0.96\textwidth}
  9840. \[
  9841. \begin{array}{lcl}
  9842. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  9843. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  9844. & & \gray{ \key{main:} \; \Instr\ldots }
  9845. \end{array}
  9846. \]
  9847. \end{minipage}
  9848. }
  9849. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  9850. \label{fig:x86-2-concrete}
  9851. \end{figure}
  9852. \begin{figure}[tp]
  9853. \fbox{
  9854. \begin{minipage}{0.96\textwidth}
  9855. \small
  9856. \[
  9857. \begin{array}{lcl}
  9858. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  9859. \MID \BYTEREG{\Reg}} \\
  9860. &\MID& (\key{Global}~\Var) \\
  9861. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  9862. \end{array}
  9863. \]
  9864. \end{minipage}
  9865. }
  9866. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  9867. \label{fig:x86-2}
  9868. \end{figure}
  9869. The concrete and abstract syntax of the \LangXGlobal{} language is
  9870. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  9871. differs from \LangXIf{} just in the addition of the form for global
  9872. variables.
  9873. %
  9874. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  9875. \code{select\_instructions} pass on the running example.
  9876. \begin{figure}[tbp]
  9877. \centering
  9878. % tests/s2_17.rkt
  9879. \begin{minipage}[t]{0.5\textwidth}
  9880. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9881. block35:
  9882. movq free_ptr(%rip), alloc9024
  9883. addq $16, free_ptr(%rip)
  9884. movq alloc9024, %r11
  9885. movq $131, 0(%r11)
  9886. movq alloc9024, %r11
  9887. movq vecinit9025, 8(%r11)
  9888. movq $0, initret9026
  9889. movq alloc9024, %r11
  9890. movq 8(%r11), tmp9034
  9891. movq tmp9034, %r11
  9892. movq 8(%r11), %rax
  9893. jmp conclusion
  9894. block36:
  9895. movq $0, collectret9027
  9896. jmp block35
  9897. block38:
  9898. movq free_ptr(%rip), alloc9020
  9899. addq $16, free_ptr(%rip)
  9900. movq alloc9020, %r11
  9901. movq $3, 0(%r11)
  9902. movq alloc9020, %r11
  9903. movq vecinit9021, 8(%r11)
  9904. movq $0, initret9022
  9905. movq alloc9020, vecinit9025
  9906. movq free_ptr(%rip), tmp9031
  9907. movq tmp9031, tmp9032
  9908. addq $16, tmp9032
  9909. movq fromspace_end(%rip), tmp9033
  9910. cmpq tmp9033, tmp9032
  9911. jl block36
  9912. jmp block37
  9913. block37:
  9914. movq %r15, %rdi
  9915. movq $16, %rsi
  9916. callq 'collect
  9917. jmp block35
  9918. block39:
  9919. movq $0, collectret9023
  9920. jmp block38
  9921. \end{lstlisting}
  9922. \end{minipage}
  9923. \begin{minipage}[t]{0.45\textwidth}
  9924. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9925. start:
  9926. movq $42, vecinit9021
  9927. movq free_ptr(%rip), tmp9028
  9928. movq tmp9028, tmp9029
  9929. addq $16, tmp9029
  9930. movq fromspace_end(%rip), tmp9030
  9931. cmpq tmp9030, tmp9029
  9932. jl block39
  9933. jmp block40
  9934. block40:
  9935. movq %r15, %rdi
  9936. movq $16, %rsi
  9937. callq 'collect
  9938. jmp block38
  9939. \end{lstlisting}
  9940. \end{minipage}
  9941. \caption{Output of the \code{select\_instructions} pass.}
  9942. \label{fig:select-instr-output-gc}
  9943. \end{figure}
  9944. \clearpage
  9945. \section{Register Allocation}
  9946. \label{sec:reg-alloc-gc}
  9947. \index{subject}{register allocation}
  9948. As discussed earlier in this chapter, the garbage collector needs to
  9949. access all the pointers in the root set, that is, all variables that
  9950. are vectors. It will be the responsibility of the register allocator
  9951. to make sure that:
  9952. \begin{enumerate}
  9953. \item the root stack is used for spilling vector-typed variables, and
  9954. \item if a vector-typed variable is live during a call to the
  9955. collector, it must be spilled to ensure it is visible to the
  9956. collector.
  9957. \end{enumerate}
  9958. The later responsibility can be handled during construction of the
  9959. interference graph, by adding interference edges between the call-live
  9960. vector-typed variables and all the callee-saved registers. (They
  9961. already interfere with the caller-saved registers.) The type
  9962. information for variables is in the \code{Program} form, so we
  9963. recommend adding another parameter to the \code{build\_interference}
  9964. function to communicate this alist.
  9965. The spilling of vector-typed variables to the root stack can be
  9966. handled after graph coloring, when choosing how to assign the colors
  9967. (integers) to registers and stack locations. The \code{Program} output
  9968. of this pass changes to also record the number of spills to the root
  9969. stack.
  9970. % build-interference
  9971. %
  9972. % callq
  9973. % extra parameter for var->type assoc. list
  9974. % update 'program' and 'if'
  9975. % allocate-registers
  9976. % allocate spilled vectors to the rootstack
  9977. % don't change color-graph
  9978. \section{Generate Prelude and Conclusion}
  9979. \label{sec:print-x86-gc}
  9980. \label{sec:prelude-conclusion-x86-gc}
  9981. \index{subject}{prelude}\index{subject}{conclusion}
  9982. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  9983. \code{prelude\_and\_conclusion} pass on the running example. In the
  9984. prelude and conclusion of the \code{main} function, we treat the root
  9985. stack very much like the regular stack in that we move the root stack
  9986. pointer (\code{r15}) to make room for the spills to the root stack,
  9987. except that the root stack grows up instead of down. For the running
  9988. example, there was just one spill so we increment \code{r15} by 8
  9989. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  9990. One issue that deserves special care is that there may be a call to
  9991. \code{collect} prior to the initializing assignments for all the
  9992. variables in the root stack. We do not want the garbage collector to
  9993. accidentally think that some uninitialized variable is a pointer that
  9994. needs to be followed. Thus, we zero-out all locations on the root
  9995. stack in the prelude of \code{main}. In
  9996. Figure~\ref{fig:print-x86-output-gc}, the instruction
  9997. %
  9998. \lstinline{movq $0, (%r15)}
  9999. %
  10000. accomplishes this task. The garbage collector tests each root to see
  10001. if it is null prior to dereferencing it.
  10002. \begin{figure}[htbp]
  10003. \begin{minipage}[t]{0.5\textwidth}
  10004. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10005. block35:
  10006. movq free_ptr(%rip), %rcx
  10007. addq $16, free_ptr(%rip)
  10008. movq %rcx, %r11
  10009. movq $131, 0(%r11)
  10010. movq %rcx, %r11
  10011. movq -8(%r15), %rax
  10012. movq %rax, 8(%r11)
  10013. movq $0, %rdx
  10014. movq %rcx, %r11
  10015. movq 8(%r11), %rcx
  10016. movq %rcx, %r11
  10017. movq 8(%r11), %rax
  10018. jmp conclusion
  10019. block36:
  10020. movq $0, %rcx
  10021. jmp block35
  10022. block38:
  10023. movq free_ptr(%rip), %rcx
  10024. addq $16, free_ptr(%rip)
  10025. movq %rcx, %r11
  10026. movq $3, 0(%r11)
  10027. movq %rcx, %r11
  10028. movq %rbx, 8(%r11)
  10029. movq $0, %rdx
  10030. movq %rcx, -8(%r15)
  10031. movq free_ptr(%rip), %rcx
  10032. addq $16, %rcx
  10033. movq fromspace_end(%rip), %rdx
  10034. cmpq %rdx, %rcx
  10035. jl block36
  10036. movq %r15, %rdi
  10037. movq $16, %rsi
  10038. callq collect
  10039. jmp block35
  10040. block39:
  10041. movq $0, %rcx
  10042. jmp block38
  10043. \end{lstlisting}
  10044. \end{minipage}
  10045. \begin{minipage}[t]{0.45\textwidth}
  10046. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10047. start:
  10048. movq $42, %rbx
  10049. movq free_ptr(%rip), %rdx
  10050. addq $16, %rdx
  10051. movq fromspace_end(%rip), %rcx
  10052. cmpq %rcx, %rdx
  10053. jl block39
  10054. movq %r15, %rdi
  10055. movq $16, %rsi
  10056. callq collect
  10057. jmp block38
  10058. .globl main
  10059. main:
  10060. pushq %rbp
  10061. movq %rsp, %rbp
  10062. pushq %r13
  10063. pushq %r12
  10064. pushq %rbx
  10065. pushq %r14
  10066. subq $0, %rsp
  10067. movq $16384, %rdi
  10068. movq $16384, %rsi
  10069. callq initialize
  10070. movq rootstack_begin(%rip), %r15
  10071. movq $0, (%r15)
  10072. addq $8, %r15
  10073. jmp start
  10074. conclusion:
  10075. subq $8, %r15
  10076. addq $0, %rsp
  10077. popq %r14
  10078. popq %rbx
  10079. popq %r12
  10080. popq %r13
  10081. popq %rbp
  10082. retq
  10083. \end{lstlisting}
  10084. \end{minipage}
  10085. \caption{Output of the \code{print\_x86} pass.}
  10086. \label{fig:print-x86-output-gc}
  10087. \end{figure}
  10088. \begin{figure}[p]
  10089. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10090. \node (Rvec) at (0,2) {\large \LangVec{}};
  10091. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  10092. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  10093. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  10094. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  10095. \node (C2-4) at (3,0) {\large \LangCVec{}};
  10096. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  10097. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  10098. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  10099. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  10100. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  10101. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  10102. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  10103. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  10104. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  10105. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Rvec-4);
  10106. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvec-5);
  10107. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  10108. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  10109. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10110. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10111. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10112. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10113. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  10114. \end{tikzpicture}
  10115. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  10116. \label{fig:Rvec-passes}
  10117. \end{figure}
  10118. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  10119. for the compilation of \LangVec{}.
  10120. \section{Challenge: Simple Structures}
  10121. \label{sec:simple-structures}
  10122. \index{subject}{struct}
  10123. \index{subject}{structure}
  10124. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  10125. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  10126. Recall that a \code{struct} in Typed Racket is a user-defined data
  10127. type that contains named fields and that is heap allocated, similar to
  10128. a vector. The following is an example of a structure definition, in
  10129. this case the definition of a \code{point} type.
  10130. \begin{lstlisting}
  10131. (struct point ([x : Integer] [y : Integer]) #:mutable)
  10132. \end{lstlisting}
  10133. \begin{figure}[tbp]
  10134. \centering
  10135. \fbox{
  10136. \begin{minipage}{0.96\textwidth}
  10137. \[
  10138. \begin{array}{lcl}
  10139. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  10140. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  10141. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  10142. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  10143. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  10144. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  10145. \MID (\key{and}\;\Exp\;\Exp)
  10146. \MID (\key{or}\;\Exp\;\Exp)
  10147. \MID (\key{not}\;\Exp) } \\
  10148. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  10149. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  10150. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  10151. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  10152. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  10153. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  10154. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  10155. \LangStruct{} &::=& \Def \ldots \; \Exp
  10156. \end{array}
  10157. \]
  10158. \end{minipage}
  10159. }
  10160. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  10161. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  10162. \label{fig:r3s-concrete-syntax}
  10163. \end{figure}
  10164. An instance of a structure is created using function call syntax, with
  10165. the name of the structure in the function position:
  10166. \begin{lstlisting}
  10167. (point 7 12)
  10168. \end{lstlisting}
  10169. Function-call syntax is also used to read the value in a field of a
  10170. structure. The function name is formed by the structure name, a dash,
  10171. and the field name. The following example uses \code{point-x} and
  10172. \code{point-y} to access the \code{x} and \code{y} fields of two point
  10173. instances.
  10174. \begin{center}
  10175. \begin{lstlisting}
  10176. (let ([pt1 (point 7 12)])
  10177. (let ([pt2 (point 4 3)])
  10178. (+ (- (point-x pt1) (point-x pt2))
  10179. (- (point-y pt1) (point-y pt2)))))
  10180. \end{lstlisting}
  10181. \end{center}
  10182. Similarly, to write to a field of a structure, use its set function,
  10183. whose name starts with \code{set-}, followed by the structure name,
  10184. then a dash, then the field name, and concluded with an exclamation
  10185. mark. The following example uses \code{set-point-x!} to change the
  10186. \code{x} field from \code{7} to \code{42}.
  10187. \begin{center}
  10188. \begin{lstlisting}
  10189. (let ([pt (point 7 12)])
  10190. (let ([_ (set-point-x! pt 42)])
  10191. (point-x pt)))
  10192. \end{lstlisting}
  10193. \end{center}
  10194. \begin{exercise}\normalfont
  10195. Extend your compiler with support for simple structures, compiling
  10196. \LangStruct{} to x86 assembly code. Create five new test cases that use
  10197. structures and test your compiler.
  10198. \end{exercise}
  10199. \section{Challenge: Arrays}
  10200. \label{sec:arrays}
  10201. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10202. elements whose length is determined at compile-time and where each
  10203. element of a tuple may have a different type (they are
  10204. heterogeous). This challenge is also about sequences, but this time
  10205. the length is determined at run-time and all the elements have the same
  10206. type (they are homogeneous). We use the term ``array'' for this later
  10207. kind of sequence.
  10208. The Racket language does not distinguish between tuples and arrays,
  10209. they are both represented by vectors. However, Typed Racket
  10210. distinguishes between tuples and arrays: the \code{Vector} type is for
  10211. tuples and the \code{Vectorof} type is for arrays.
  10212. %
  10213. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10214. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10215. and the \code{make-vector} primitive operator for creating an array,
  10216. whose arguments are the length of the array and an initial value for
  10217. all the elements in the array. The \code{vector-length},
  10218. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10219. for tuples become overloaded for use with arrays.
  10220. %
  10221. We also include integer multiplication in \LangArray{}, as it is
  10222. useful in many examples involving arrays such as computing the
  10223. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10224. \begin{figure}[tp]
  10225. \centering
  10226. \fbox{
  10227. \begin{minipage}{0.96\textwidth}
  10228. \small
  10229. \[
  10230. \begin{array}{lcl}
  10231. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  10232. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10233. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  10234. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  10235. &\MID& \gray{\key{\#t} \MID \key{\#f}
  10236. \MID \LP\key{and}\;\Exp\;\Exp\RP
  10237. \MID \LP\key{or}\;\Exp\;\Exp\RP
  10238. \MID \LP\key{not}\;\Exp\RP } \\
  10239. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  10240. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  10241. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10242. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  10243. \MID \LP\Exp \; \Exp\ldots\RP } \\
  10244. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10245. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10246. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  10247. \MID \CBEGIN{\Exp\ldots}{\Exp}
  10248. \MID \CWHILE{\Exp}{\Exp} } \\
  10249. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  10250. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10251. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10252. \end{array}
  10253. \]
  10254. \end{minipage}
  10255. }
  10256. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10257. \label{fig:Rvecof-concrete-syntax}
  10258. \end{figure}
  10259. \begin{figure}[tp]
  10260. \begin{lstlisting}
  10261. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10262. [n : Integer]) : Integer
  10263. (let ([i 0])
  10264. (let ([prod 0])
  10265. (begin
  10266. (while (< i n)
  10267. (begin
  10268. (set! prod (+ prod (* (vector-ref A i)
  10269. (vector-ref B i))))
  10270. (set! i (+ i 1))
  10271. ))
  10272. prod))))
  10273. (let ([A (make-vector 2 2)])
  10274. (let ([B (make-vector 2 3)])
  10275. (+ (inner-product A B 2)
  10276. 30)))
  10277. \end{lstlisting}
  10278. \caption{Example program that computes the inner-product.}
  10279. \label{fig:inner-product}
  10280. \end{figure}
  10281. The type checker for \LangArray{} is define in
  10282. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10283. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10284. of the intializing expression. The length expression is required to
  10285. have type \code{Integer}. The type checking of the operators
  10286. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10287. updated to handle the situation where the vector has type
  10288. \code{Vectorof}. In these cases we translate the operators to their
  10289. \code{vectorof} form so that later passes can easily distinguish
  10290. between operations on tuples versus arrays. We override the
  10291. \code{operator-types} method to provide the type signature for
  10292. multiplication: it takes two integers and returns an integer. To
  10293. support injection and projection of arrays to the \code{Any} type
  10294. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10295. predicate.
  10296. \begin{figure}[tbp]
  10297. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10298. (define type-check-Rvecof_class
  10299. (class type-check-Rwhile_class
  10300. (super-new)
  10301. (inherit check-type-equal?)
  10302. (define/override (flat-ty? ty)
  10303. (match ty
  10304. ['(Vectorof Any) #t]
  10305. [else (super flat-ty? ty)]))
  10306. (define/override (operator-types)
  10307. (append '((* . ((Integer Integer) . Integer)))
  10308. (super operator-types)))
  10309. (define/override (type-check-exp env)
  10310. (lambda (e)
  10311. (define recur (type-check-exp env))
  10312. (match e
  10313. [(Prim 'make-vector (list e1 e2))
  10314. (define-values (e1^ t1) (recur e1))
  10315. (define-values (e2^ elt-type) (recur e2))
  10316. (define vec-type `(Vectorof ,elt-type))
  10317. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10318. vec-type)]
  10319. [(Prim 'vector-ref (list e1 e2))
  10320. (define-values (e1^ t1) (recur e1))
  10321. (define-values (e2^ t2) (recur e2))
  10322. (match* (t1 t2)
  10323. [(`(Vectorof ,elt-type) 'Integer)
  10324. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10325. [(other wise) ((super type-check-exp env) e)])]
  10326. [(Prim 'vector-set! (list e1 e2 e3) )
  10327. (define-values (e-vec t-vec) (recur e1))
  10328. (define-values (e2^ t2) (recur e2))
  10329. (define-values (e-arg^ t-arg) (recur e3))
  10330. (match t-vec
  10331. [`(Vectorof ,elt-type)
  10332. (check-type-equal? elt-type t-arg e)
  10333. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10334. [else ((super type-check-exp env) e)])]
  10335. [(Prim 'vector-length (list e1))
  10336. (define-values (e1^ t1) (recur e1))
  10337. (match t1
  10338. [`(Vectorof ,t)
  10339. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10340. [else ((super type-check-exp env) e)])]
  10341. [else ((super type-check-exp env) e)])))
  10342. ))
  10343. (define (type-check-Rvecof p)
  10344. (send (new type-check-Rvecof_class) type-check-program p))
  10345. \end{lstlisting}
  10346. \caption{Type checker for the \LangArray{} language.}
  10347. \label{fig:type-check-Rvecof}
  10348. \end{figure}
  10349. The interpreter for \LangArray{} is defined in
  10350. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10351. implemented with Racket's \code{make-vector} function and
  10352. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10353. integers.
  10354. \begin{figure}[tbp]
  10355. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10356. (define interp-Rvecof_class
  10357. (class interp-Rwhile_class
  10358. (super-new)
  10359. (define/override (interp-op op)
  10360. (verbose "Rvecof/interp-op" op)
  10361. (match op
  10362. ['make-vector make-vector]
  10363. ['* fx*]
  10364. [else (super interp-op op)]))
  10365. ))
  10366. (define (interp-Rvecof p)
  10367. (send (new interp-Rvecof_class) interp-program p))
  10368. \end{lstlisting}
  10369. \caption{Interpreter for \LangArray{}.}
  10370. \label{fig:interp-Rvecof}
  10371. \end{figure}
  10372. \subsection{Data Representation}
  10373. \label{sec:array-rep}
  10374. Just like tuples, we store arrays on the heap which means that the
  10375. garbage collector will need to inspect arrays. An immediate thought is
  10376. to use the same representation for arrays that we use for tuples.
  10377. However, we limit tuples to a length of $50$ so that their length and
  10378. pointer mask can fit into the 64-bit tag at the beginning of each
  10379. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10380. millions of elements, so we need more bits to store the length.
  10381. However, because arrays are homogeneous, we only need $1$ bit for the
  10382. pointer mask instead of one bit per array elements. Finally, the
  10383. garbage collector will need to be able to distinguish between tuples
  10384. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10385. arrive at the following layout for the 64-bit tag at the beginning of
  10386. an array:
  10387. \begin{itemize}
  10388. \item The right-most bit is the forwarding bit, just like in a tuple.
  10389. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10390. it is not.
  10391. \item The next bit to the left is the pointer mask. A $0$ indicates
  10392. that none of the elements are pointers to the heap and a $1$
  10393. indicates that all of the elements are pointers.
  10394. \item The next $61$ bits store the length of the array.
  10395. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10396. array ($1$).
  10397. \end{itemize}
  10398. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10399. differentiate the kinds of values that have been injected into the
  10400. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10401. to indicate that the value is an array.
  10402. In the following subsections we provide hints regarding how to update
  10403. the passes to handle arrays.
  10404. \subsection{Reveal Casts}
  10405. The array-access operators \code{vectorof-ref} and
  10406. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10407. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10408. that the type checker cannot tell whether the index will be in bounds,
  10409. so the bounds check must be performed at run time. Recall that the
  10410. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10411. an \code{If} arround a vector reference for update to check whether
  10412. the index is less than the length. You should do the same for
  10413. \code{vectorof-ref} and \code{vectorof-set!} .
  10414. In addition, the handling of the \code{any-vector} operators in
  10415. \code{reveal-casts} needs to be updated to account for arrays that are
  10416. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10417. generated code should test whether the tag is for tuples (\code{010})
  10418. or arrays (\code{110}) and then dispatch to either
  10419. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10420. we add a case in \code{select\_instructions} to generate the
  10421. appropriate instructions for accessing the array length from the
  10422. header of an array.
  10423. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10424. the generated code needs to check that the index is less than the
  10425. vector length, so like the code for \code{any-vector-length}, check
  10426. the tag to determine whether to use \code{any-vector-length} or
  10427. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10428. is complete, the generated code can use \code{any-vector-ref} and
  10429. \code{any-vector-set!} for both tuples and arrays because the
  10430. instructions used for those operators do not look at the tag at the
  10431. front of the tuple or array.
  10432. \subsection{Expose Allocation}
  10433. This pass should translate the \code{make-vector} operator into
  10434. lower-level operations. In particular, the new AST node
  10435. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10436. length specified by the $\Exp$, but does not initialize the elements
  10437. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10438. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10439. element type for the array. Regarding the initialization of the array,
  10440. we recommend generated a \code{while} loop that uses
  10441. \code{vector-set!} to put the initializing value into every element of
  10442. the array.
  10443. \subsection{Remove Complex Operands}
  10444. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  10445. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10446. complex and its subexpression must be atomic.
  10447. \subsection{Explicate Control}
  10448. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  10449. \code{explicate\_assign}.
  10450. \subsection{Select Instructions}
  10451. Generate instructions for \code{AllocateArray} similar to those for
  10452. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10453. that the tag at the front of the array should instead use the
  10454. representation discussed in Section~\ref{sec:array-rep}.
  10455. Regarding \code{vectorof-length}, extract the length from the tag
  10456. according to the representation discussed in
  10457. Section~\ref{sec:array-rep}.
  10458. The instructions generated for \code{vectorof-ref} differ from those
  10459. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10460. that the index is not a constant so the offset must be computed at
  10461. runtime, similar to the instructions generated for
  10462. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10463. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10464. appear in an assignment and as a stand-alone statement, so make sure
  10465. to handle both situations in this pass.
  10466. Finally, the instructions for \code{any-vectorof-length} should be
  10467. similar to those for \code{vectorof-length}, except that one must
  10468. first project the array by writing zeroes into the $3$-bit tag
  10469. \begin{exercise}\normalfont
  10470. Implement a compiler for the \LangArray{} language by extending your
  10471. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10472. programs, including the one in Figure~\ref{fig:inner-product} and also
  10473. a program that multiplies two matrices. Note that matrices are
  10474. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10475. arrays by laying out each row in the array, one after the next.
  10476. \end{exercise}
  10477. \section{Challenge: Generational Collection}
  10478. The copying collector described in Section~\ref{sec:GC} can incur
  10479. significant runtime overhead because the call to \code{collect} takes
  10480. time proportional to all of the live data. One way to reduce this
  10481. overhead is to reduce how much data is inspected in each call to
  10482. \code{collect}. In particular, researchers have observed that recently
  10483. allocated data is more likely to become garbage then data that has
  10484. survived one or more previous calls to \code{collect}. This insight
  10485. motivated the creation of \emph{generational garbage collectors}
  10486. \index{subject}{generational garbage collector} that
  10487. 1) segregates data according to its age into two or more generations,
  10488. 2) allocates less space for younger generations, so collecting them is
  10489. faster, and more space for the older generations, and 3) performs
  10490. collection on the younger generations more frequently then for older
  10491. generations~\citep{Wilson:1992fk}.
  10492. For this challenge assignment, the goal is to adapt the copying
  10493. collector implemented in \code{runtime.c} to use two generations, one
  10494. for young data and one for old data. Each generation consists of a
  10495. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  10496. \code{collect} function to use the two generations.
  10497. \begin{enumerate}
  10498. \item Copy the young generation's FromSpace to its ToSpace then switch
  10499. the role of the ToSpace and FromSpace
  10500. \item If there is enough space for the requested number of bytes in
  10501. the young FromSpace, then return from \code{collect}.
  10502. \item If there is not enough space in the young FromSpace for the
  10503. requested bytes, then move the data from the young generation to the
  10504. old one with the following steps:
  10505. \begin{enumerate}
  10506. \item If there is enough room in the old FromSpace, copy the young
  10507. FromSpace to the old FromSpace and then return.
  10508. \item If there is not enough room in the old FromSpace, then collect
  10509. the old generation by copying the old FromSpace to the old ToSpace
  10510. and swap the roles of the old FromSpace and ToSpace.
  10511. \item If there is enough room now, copy the young FromSpace to the
  10512. old FromSpace and return. Otherwise, allocate a larger FromSpace
  10513. and ToSpace for the old generation. Copy the young FromSpace and
  10514. the old FromSpace into the larger FromSpace for the old
  10515. generation and then return.
  10516. \end{enumerate}
  10517. \end{enumerate}
  10518. We recommend that you generalize the \code{cheney} function so that it
  10519. can be used for all the copies mentioned above: between the young
  10520. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  10521. between the young FromSpace and old FromSpace. This can be
  10522. accomplished by adding parameters to \code{cheney} that replace its
  10523. use of the global variables \code{fromspace\_begin},
  10524. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  10525. Note that the collection of the young generation does not traverse the
  10526. old generation. This introduces a potential problem: there may be
  10527. young data that is only reachable through pointers in the old
  10528. generation. If these pointers are not taken into account, the
  10529. collector could throw away young data that is live! One solution,
  10530. called \emph{pointer recording}, is to maintain a set of all the
  10531. pointers from the old generation into the new generation and consider
  10532. this set as part of the root set. To maintain this set, the compiler
  10533. must insert extra instructions around every \code{vector-set!}. If the
  10534. vector being modified is in the old generation, and if the value being
  10535. written is a pointer into the new generation, than that pointer must
  10536. be added to the set. Also, if the value being overwritten was a
  10537. pointer into the new generation, then that pointer should be removed
  10538. from the set.
  10539. \begin{exercise}\normalfont
  10540. Adapt the \code{collect} function in \code{runtime.c} to implement
  10541. generational garbage collection, as outlined in this section.
  10542. Update the code generation for \code{vector-set!} to implement
  10543. pointer recording. Make sure that your new compiler and runtime
  10544. passes your test suite.
  10545. \end{exercise}
  10546. % Further Reading
  10547. \fi % racketEd
  10548. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10549. \chapter{Functions}
  10550. \label{ch:Rfun}
  10551. \index{subject}{function}
  10552. \if\edition\racketEd
  10553. This chapter studies the compilation of functions similar to those
  10554. found in the C language. This corresponds to a subset of Typed Racket
  10555. in which only top-level function definitions are allowed. This kind of
  10556. function is an important stepping stone to implementing
  10557. lexically-scoped functions, that is, \key{lambda} abstractions, which
  10558. is the topic of Chapter~\ref{ch:Rlam}.
  10559. \section{The \LangFun{} Language}
  10560. The concrete and abstract syntax for function definitions and function
  10561. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  10562. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  10563. \LangFun{} begin with zero or more function definitions. The function
  10564. names from these definitions are in-scope for the entire program,
  10565. including all other function definitions (so the ordering of function
  10566. definitions does not matter). The concrete syntax for function
  10567. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  10568. where the first expression must
  10569. evaluate to a function and the rest are the arguments.
  10570. The abstract syntax for function application is
  10571. $\APPLY{\Exp}{\Exp\ldots}$.
  10572. %% The syntax for function application does not include an explicit
  10573. %% keyword, which is error prone when using \code{match}. To alleviate
  10574. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  10575. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  10576. Functions are first-class in the sense that a function pointer
  10577. \index{subject}{function pointer} is data and can be stored in memory or passed
  10578. as a parameter to another function. Thus, we introduce a function
  10579. type, written
  10580. \begin{lstlisting}
  10581. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  10582. \end{lstlisting}
  10583. for a function whose $n$ parameters have the types $\Type_1$ through
  10584. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  10585. these functions (with respect to Racket functions) is that they are
  10586. not lexically scoped. That is, the only external entities that can be
  10587. referenced from inside a function body are other globally-defined
  10588. functions. The syntax of \LangFun{} prevents functions from being nested
  10589. inside each other.
  10590. \begin{figure}[tp]
  10591. \centering
  10592. \fbox{
  10593. \begin{minipage}{0.96\textwidth}
  10594. \small
  10595. \[
  10596. \begin{array}{lcl}
  10597. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  10598. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  10599. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  10600. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  10601. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  10602. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  10603. \MID (\key{and}\;\Exp\;\Exp)
  10604. \MID (\key{or}\;\Exp\;\Exp)
  10605. \MID (\key{not}\;\Exp)} \\
  10606. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  10607. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  10608. (\key{vector-ref}\;\Exp\;\Int)} \\
  10609. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  10610. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  10611. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  10612. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  10613. \LangFunM{} &::=& \Def \ldots \; \Exp
  10614. \end{array}
  10615. \]
  10616. \end{minipage}
  10617. }
  10618. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  10619. \label{fig:Rfun-concrete-syntax}
  10620. \end{figure}
  10621. \begin{figure}[tp]
  10622. \centering
  10623. \fbox{
  10624. \begin{minipage}{0.96\textwidth}
  10625. \small
  10626. \[
  10627. \begin{array}{lcl}
  10628. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  10629. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10630. &\MID& \gray{ \BOOL{\itm{bool}}
  10631. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  10632. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  10633. \MID \APPLY{\Exp}{\Exp\ldots}\\
  10634. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  10635. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  10636. \end{array}
  10637. \]
  10638. \end{minipage}
  10639. }
  10640. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  10641. \label{fig:Rfun-syntax}
  10642. \end{figure}
  10643. The program in Figure~\ref{fig:Rfun-function-example} is a
  10644. representative example of defining and using functions in \LangFun{}. We
  10645. define a function \code{map-vec} that applies some other function
  10646. \code{f} to both elements of a vector and returns a new
  10647. vector containing the results. We also define a function \code{add1}.
  10648. The program applies
  10649. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  10650. \code{(vector 1 42)}, from which we return the \code{42}.
  10651. \begin{figure}[tbp]
  10652. \begin{lstlisting}
  10653. (define (map-vec [f : (Integer -> Integer)]
  10654. [v : (Vector Integer Integer)])
  10655. : (Vector Integer Integer)
  10656. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10657. (define (add1 [x : Integer]) : Integer
  10658. (+ x 1))
  10659. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10660. \end{lstlisting}
  10661. \caption{Example of using functions in \LangFun{}.}
  10662. \label{fig:Rfun-function-example}
  10663. \end{figure}
  10664. The definitional interpreter for \LangFun{} is in
  10665. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  10666. responsible for setting up the mutual recursion between the top-level
  10667. function definitions. We use the classic back-patching \index{subject}{back-patching}
  10668. approach that uses mutable variables and makes two passes over the function
  10669. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  10670. top-level environment using a mutable cons cell for each function
  10671. definition. Note that the \code{lambda} value for each function is
  10672. incomplete; it does not yet include the environment. Once the
  10673. top-level environment is constructed, we then iterate over it and
  10674. update the \code{lambda} values to use the top-level environment.
  10675. \begin{figure}[tp]
  10676. \begin{lstlisting}
  10677. (define interp-Rfun_class
  10678. (class interp-Rvec_class
  10679. (super-new)
  10680. (define/override ((interp-exp env) e)
  10681. (define recur (interp-exp env))
  10682. (match e
  10683. [(Var x) (unbox (dict-ref env x))]
  10684. [(Let x e body)
  10685. (define new-env (dict-set env x (box (recur e))))
  10686. ((interp-exp new-env) body)]
  10687. [(Apply fun args)
  10688. (define fun-val (recur fun))
  10689. (define arg-vals (for/list ([e args]) (recur e)))
  10690. (match fun-val
  10691. [`(function (,xs ...) ,body ,fun-env)
  10692. (define params-args (for/list ([x xs] [arg arg-vals])
  10693. (cons x (box arg))))
  10694. (define new-env (append params-args fun-env))
  10695. ((interp-exp new-env) body)]
  10696. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  10697. [else ((super interp-exp env) e)]
  10698. ))
  10699. (define/public (interp-def d)
  10700. (match d
  10701. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  10702. (cons f (box `(function ,xs ,body ())))]))
  10703. (define/override (interp-program p)
  10704. (match p
  10705. [(ProgramDefsExp info ds body)
  10706. (let ([top-level (for/list ([d ds]) (interp-def d))])
  10707. (for/list ([f (in-dict-values top-level)])
  10708. (set-box! f (match (unbox f)
  10709. [`(function ,xs ,body ())
  10710. `(function ,xs ,body ,top-level)])))
  10711. ((interp-exp top-level) body))]))
  10712. ))
  10713. (define (interp-Rfun p)
  10714. (send (new interp-Rfun_class) interp-program p))
  10715. \end{lstlisting}
  10716. \caption{Interpreter for the \LangFun{} language.}
  10717. \label{fig:interp-Rfun}
  10718. \end{figure}
  10719. %\margincomment{TODO: explain type checker}
  10720. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  10721. \begin{figure}[tp]
  10722. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10723. (define type-check-Rfun_class
  10724. (class type-check-Rvec_class
  10725. (super-new)
  10726. (inherit check-type-equal?)
  10727. (define/public (type-check-apply env e es)
  10728. (define-values (e^ ty) ((type-check-exp env) e))
  10729. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  10730. ((type-check-exp env) e)))
  10731. (match ty
  10732. [`(,ty^* ... -> ,rt)
  10733. (for ([arg-ty ty*] [param-ty ty^*])
  10734. (check-type-equal? arg-ty param-ty (Apply e es)))
  10735. (values e^ e* rt)]))
  10736. (define/override (type-check-exp env)
  10737. (lambda (e)
  10738. (match e
  10739. [(FunRef f)
  10740. (values (FunRef f) (dict-ref env f))]
  10741. [(Apply e es)
  10742. (define-values (e^ es^ rt) (type-check-apply env e es))
  10743. (values (Apply e^ es^) rt)]
  10744. [(Call e es)
  10745. (define-values (e^ es^ rt) (type-check-apply env e es))
  10746. (values (Call e^ es^) rt)]
  10747. [else ((super type-check-exp env) e)])))
  10748. (define/public (type-check-def env)
  10749. (lambda (e)
  10750. (match e
  10751. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  10752. (define new-env (append (map cons xs ps) env))
  10753. (define-values (body^ ty^) ((type-check-exp new-env) body))
  10754. (check-type-equal? ty^ rt body)
  10755. (Def f p:t* rt info body^)])))
  10756. (define/public (fun-def-type d)
  10757. (match d
  10758. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  10759. (define/override (type-check-program e)
  10760. (match e
  10761. [(ProgramDefsExp info ds body)
  10762. (define new-env (for/list ([d ds])
  10763. (cons (Def-name d) (fun-def-type d))))
  10764. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  10765. (define-values (body^ ty) ((type-check-exp new-env) body))
  10766. (check-type-equal? ty 'Integer body)
  10767. (ProgramDefsExp info ds^ body^)]))))
  10768. (define (type-check-Rfun p)
  10769. (send (new type-check-Rfun_class) type-check-program p))
  10770. \end{lstlisting}
  10771. \caption{Type checker for the \LangFun{} language.}
  10772. \label{fig:type-check-Rfun}
  10773. \end{figure}
  10774. \section{Functions in x86}
  10775. \label{sec:fun-x86}
  10776. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  10777. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  10778. %% \margincomment{\tiny Talk about the return address on the
  10779. %% stack and what callq and retq does.\\ --Jeremy }
  10780. The x86 architecture provides a few features to support the
  10781. implementation of functions. We have already seen that x86 provides
  10782. labels so that one can refer to the location of an instruction, as is
  10783. needed for jump instructions. Labels can also be used to mark the
  10784. beginning of the instructions for a function. Going further, we can
  10785. obtain the address of a label by using the \key{leaq} instruction and
  10786. PC-relative addressing. For example, the following puts the
  10787. address of the \code{add1} label into the \code{rbx} register.
  10788. \begin{lstlisting}
  10789. leaq add1(%rip), %rbx
  10790. \end{lstlisting}
  10791. The instruction pointer register \key{rip} (aka. the program counter
  10792. \index{subject}{program counter}) always points to the next instruction to be
  10793. executed. When combined with an label, as in \code{add1(\%rip)}, the
  10794. linker computes the distance $d$ between the address of \code{add1}
  10795. and where the \code{rip} would be at that moment and then changes
  10796. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  10797. the address of \code{add1}.
  10798. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  10799. jump to a function whose location is given by a label. To support
  10800. function calls in this chapter we instead will be jumping to a
  10801. function whose location is given by an address in a register, that is,
  10802. we need to make an \emph{indirect function call}. The x86 syntax for
  10803. this is a \code{callq} instruction but with an asterisk before the
  10804. register name.\index{subject}{indirect function call}
  10805. \begin{lstlisting}
  10806. callq *%rbx
  10807. \end{lstlisting}
  10808. \subsection{Calling Conventions}
  10809. \index{subject}{calling conventions}
  10810. The \code{callq} instruction provides partial support for implementing
  10811. functions: it pushes the return address on the stack and it jumps to
  10812. the target. However, \code{callq} does not handle
  10813. \begin{enumerate}
  10814. \item parameter passing,
  10815. \item pushing frames on the procedure call stack and popping them off,
  10816. or
  10817. \item determining how registers are shared by different functions.
  10818. \end{enumerate}
  10819. Regarding (1) parameter passing, recall that the following six
  10820. registers are used to pass arguments to a function, in this order.
  10821. \begin{lstlisting}
  10822. rdi rsi rdx rcx r8 r9
  10823. \end{lstlisting}
  10824. If there are
  10825. more than six arguments, then the convention is to use space on the
  10826. frame of the caller for the rest of the arguments. However, to ease
  10827. the implementation of efficient tail calls
  10828. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  10829. arguments.
  10830. %
  10831. Also recall that the register \code{rax} is for the return value of
  10832. the function.
  10833. \index{subject}{prelude}\index{subject}{conclusion}
  10834. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  10835. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  10836. the stack grows down, with each function call using a chunk of space
  10837. called a frame. The caller sets the stack pointer, register
  10838. \code{rsp}, to the last data item in its frame. The callee must not
  10839. change anything in the caller's frame, that is, anything that is at or
  10840. above the stack pointer. The callee is free to use locations that are
  10841. below the stack pointer.
  10842. Recall that we are storing variables of vector type on the root stack.
  10843. So the prelude needs to move the root stack pointer \code{r15} up and
  10844. the conclusion needs to move the root stack pointer back down. Also,
  10845. the prelude must initialize to \code{0} this frame's slots in the root
  10846. stack to signal to the garbage collector that those slots do not yet
  10847. contain a pointer to a vector. Otherwise the garbage collector will
  10848. interpret the garbage bits in those slots as memory addresses and try
  10849. to traverse them, causing serious mayhem!
  10850. Regarding (3) the sharing of registers between different functions,
  10851. recall from Section~\ref{sec:calling-conventions} that the registers
  10852. are divided into two groups, the caller-saved registers and the
  10853. callee-saved registers. The caller should assume that all the
  10854. caller-saved registers get overwritten with arbitrary values by the
  10855. callee. That is why we recommend in
  10856. Section~\ref{sec:calling-conventions} that variables that are live
  10857. during a function call should not be assigned to caller-saved
  10858. registers.
  10859. On the flip side, if the callee wants to use a callee-saved register,
  10860. the callee must save the contents of those registers on their stack
  10861. frame and then put them back prior to returning to the caller. That
  10862. is why we recommended in Section~\ref{sec:calling-conventions} that if
  10863. the register allocator assigns a variable to a callee-saved register,
  10864. then the prelude of the \code{main} function must save that register
  10865. to the stack and the conclusion of \code{main} must restore it. This
  10866. recommendation now generalizes to all functions.
  10867. Also recall that the base pointer, register \code{rbp}, is used as a
  10868. point-of-reference within a frame, so that each local variable can be
  10869. accessed at a fixed offset from the base pointer
  10870. (Section~\ref{sec:x86}).
  10871. %
  10872. Figure~\ref{fig:call-frames} shows the general layout of the caller
  10873. and callee frames.
  10874. \begin{figure}[tbp]
  10875. \centering
  10876. \begin{tabular}{r|r|l|l} \hline
  10877. Caller View & Callee View & Contents & Frame \\ \hline
  10878. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  10879. 0(\key{\%rbp}) & & old \key{rbp} \\
  10880. -8(\key{\%rbp}) & & callee-saved $1$ \\
  10881. \ldots & & \ldots \\
  10882. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  10883. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  10884. \ldots & & \ldots \\
  10885. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  10886. %% & & \\
  10887. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  10888. %% & \ldots & \ldots \\
  10889. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  10890. \hline
  10891. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  10892. & 0(\key{\%rbp}) & old \key{rbp} \\
  10893. & -8(\key{\%rbp}) & callee-saved $1$ \\
  10894. & \ldots & \ldots \\
  10895. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  10896. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  10897. & \ldots & \ldots \\
  10898. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  10899. \end{tabular}
  10900. \caption{Memory layout of caller and callee frames.}
  10901. \label{fig:call-frames}
  10902. \end{figure}
  10903. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  10904. %% local variables and for storing the values of callee-saved registers
  10905. %% (we shall refer to all of these collectively as ``locals''), and that
  10906. %% at the beginning of a function we move the stack pointer \code{rsp}
  10907. %% down to make room for them.
  10908. %% We recommend storing the local variables
  10909. %% first and then the callee-saved registers, so that the local variables
  10910. %% can be accessed using \code{rbp} the same as before the addition of
  10911. %% functions.
  10912. %% To make additional room for passing arguments, we shall
  10913. %% move the stack pointer even further down. We count how many stack
  10914. %% arguments are needed for each function call that occurs inside the
  10915. %% body of the function and find their maximum. Adding this number to the
  10916. %% number of locals gives us how much the \code{rsp} should be moved at
  10917. %% the beginning of the function. In preparation for a function call, we
  10918. %% offset from \code{rsp} to set up the stack arguments. We put the first
  10919. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  10920. %% so on.
  10921. %% Upon calling the function, the stack arguments are retrieved by the
  10922. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  10923. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  10924. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  10925. %% the layout of the caller and callee frames. Notice how important it is
  10926. %% that we correctly compute the maximum number of arguments needed for
  10927. %% function calls; if that number is too small then the arguments and
  10928. %% local variables will smash into each other!
  10929. \subsection{Efficient Tail Calls}
  10930. \label{sec:tail-call}
  10931. In general, the amount of stack space used by a program is determined
  10932. by the longest chain of nested function calls. That is, if function
  10933. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  10934. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  10935. $n$ can grow quite large in the case of recursive or mutually
  10936. recursive functions. However, in some cases we can arrange to use only
  10937. constant space, i.e. $O(1)$, instead of $O(n)$.
  10938. If a function call is the last action in a function body, then that
  10939. call is said to be a \emph{tail call}\index{subject}{tail call}.
  10940. For example, in the following
  10941. program, the recursive call to \code{tail-sum} is a tail call.
  10942. \begin{center}
  10943. \begin{lstlisting}
  10944. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  10945. (if (eq? n 0)
  10946. r
  10947. (tail-sum (- n 1) (+ n r))))
  10948. (+ (tail-sum 5 0) 27)
  10949. \end{lstlisting}
  10950. \end{center}
  10951. At a tail call, the frame of the caller is no longer needed, so we
  10952. can pop the caller's frame before making the tail call. With this
  10953. approach, a recursive function that only makes tail calls will only
  10954. use $O(1)$ stack space. Functional languages like Racket typically
  10955. rely heavily on recursive functions, so they typically guarantee that
  10956. all tail calls will be optimized in this way.
  10957. \index{subject}{frame}
  10958. However, some care is needed with regards to argument passing in tail
  10959. calls. As mentioned above, for arguments beyond the sixth, the
  10960. convention is to use space in the caller's frame for passing
  10961. arguments. But for a tail call we pop the caller's frame and can no
  10962. longer use it. Another alternative is to use space in the callee's
  10963. frame for passing arguments. However, this option is also problematic
  10964. because the caller and callee's frame overlap in memory. As we begin
  10965. to copy the arguments from their sources in the caller's frame, the
  10966. target locations in the callee's frame might overlap with the sources
  10967. for later arguments! We solve this problem by using the heap instead
  10968. of the stack for passing more than six arguments, as we describe in
  10969. the Section~\ref{sec:limit-functions-r4}.
  10970. As mentioned above, for a tail call we pop the caller's frame prior to
  10971. making the tail call. The instructions for popping a frame are the
  10972. instructions that we usually place in the conclusion of a
  10973. function. Thus, we also need to place such code immediately before
  10974. each tail call. These instructions include restoring the callee-saved
  10975. registers, so it is good that the argument passing registers are all
  10976. caller-saved registers.
  10977. One last note regarding which instruction to use to make the tail
  10978. call. When the callee is finished, it should not return to the current
  10979. function, but it should return to the function that called the current
  10980. one. Thus, the return address that is already on the stack is the
  10981. right one, and we should not use \key{callq} to make the tail call, as
  10982. that would unnecessarily overwrite the return address. Instead we can
  10983. simply use the \key{jmp} instruction. Like the indirect function call,
  10984. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  10985. prefixed with an asterisk. We recommend using \code{rax} to hold the
  10986. jump target because the preceding conclusion overwrites just about
  10987. everything else.
  10988. \begin{lstlisting}
  10989. jmp *%rax
  10990. \end{lstlisting}
  10991. \section{Shrink \LangFun{}}
  10992. \label{sec:shrink-r4}
  10993. The \code{shrink} pass performs a minor modification to ease the
  10994. later passes. This pass introduces an explicit \code{main} function
  10995. and changes the top \code{ProgramDefsExp} form to
  10996. \code{ProgramDefs} as follows.
  10997. \begin{lstlisting}
  10998. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  10999. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  11000. \end{lstlisting}
  11001. where $\itm{mainDef}$ is
  11002. \begin{lstlisting}
  11003. (Def 'main '() 'Integer '() |$\Exp'$|)
  11004. \end{lstlisting}
  11005. \section{Reveal Functions and the \LangFunRef{} language}
  11006. \label{sec:reveal-functions-r4}
  11007. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  11008. respect: it conflates the use of function names and local
  11009. variables. This is a problem because we need to compile the use of a
  11010. function name differently than the use of a local variable; we need to
  11011. use \code{leaq} to convert the function name (a label in x86) to an
  11012. address in a register. Thus, it is a good idea to create a new pass
  11013. that changes function references from just a symbol $f$ to
  11014. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  11015. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  11016. The concrete syntax for a function reference is $\CFUNREF{f}$.
  11017. \begin{figure}[tp]
  11018. \centering
  11019. \fbox{
  11020. \begin{minipage}{0.96\textwidth}
  11021. \[
  11022. \begin{array}{lcl}
  11023. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  11024. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11025. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  11026. \end{array}
  11027. \]
  11028. \end{minipage}
  11029. }
  11030. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  11031. (Figure~\ref{fig:Rfun-syntax}).}
  11032. \label{fig:f1-syntax}
  11033. \end{figure}
  11034. %% Distinguishing between calls in tail position and non-tail position
  11035. %% requires the pass to have some notion of context. We recommend using
  11036. %% two mutually recursive functions, one for processing expressions in
  11037. %% tail position and another for the rest.
  11038. Placing this pass after \code{uniquify} will make sure that there are
  11039. no local variables and functions that share the same name. On the
  11040. other hand, \code{reveal-functions} needs to come before the
  11041. \code{explicate\_control} pass because that pass helps us compile
  11042. \code{FunRef} forms into assignment statements.
  11043. \section{Limit Functions}
  11044. \label{sec:limit-functions-r4}
  11045. Recall that we wish to limit the number of function parameters to six
  11046. so that we do not need to use the stack for argument passing, which
  11047. makes it easier to implement efficient tail calls. However, because
  11048. the input language \LangFun{} supports arbitrary numbers of function
  11049. arguments, we have some work to do!
  11050. This pass transforms functions and function calls that involve more
  11051. than six arguments to pass the first five arguments as usual, but it
  11052. packs the rest of the arguments into a vector and passes it as the
  11053. sixth argument.
  11054. Each function definition with too many parameters is transformed as
  11055. follows.
  11056. \begin{lstlisting}
  11057. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  11058. |$\Rightarrow$|
  11059. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  11060. \end{lstlisting}
  11061. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  11062. the occurrences of the later parameters with vector references.
  11063. \begin{lstlisting}
  11064. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  11065. \end{lstlisting}
  11066. For function calls with too many arguments, the \code{limit-functions}
  11067. pass transforms them in the following way.
  11068. \begin{tabular}{lll}
  11069. \begin{minipage}{0.2\textwidth}
  11070. \begin{lstlisting}
  11071. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  11072. \end{lstlisting}
  11073. \end{minipage}
  11074. &
  11075. $\Rightarrow$
  11076. &
  11077. \begin{minipage}{0.4\textwidth}
  11078. \begin{lstlisting}
  11079. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  11080. \end{lstlisting}
  11081. \end{minipage}
  11082. \end{tabular}
  11083. \section{Remove Complex Operands}
  11084. \label{sec:rco-r4}
  11085. The primary decisions to make for this pass is whether to classify
  11086. \code{FunRef} and \code{Apply} as either atomic or complex
  11087. expressions. Recall that a simple expression will eventually end up as
  11088. just an immediate argument of an x86 instruction. Function
  11089. application will be translated to a sequence of instructions, so
  11090. \code{Apply} must be classified as complex expression.
  11091. On the other hand, the arguments of \code{Apply} should be
  11092. atomic expressions.
  11093. %
  11094. Regarding \code{FunRef}, as discussed above, the function label needs
  11095. to be converted to an address using the \code{leaq} instruction. Thus,
  11096. even though \code{FunRef} seems rather simple, it needs to be
  11097. classified as a complex expression so that we generate an assignment
  11098. statement with a left-hand side that can serve as the target of the
  11099. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  11100. output language \LangFunANF{} of this pass.
  11101. \begin{figure}[tp]
  11102. \centering
  11103. \fbox{
  11104. \begin{minipage}{0.96\textwidth}
  11105. \small
  11106. \[
  11107. \begin{array}{rcl}
  11108. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  11109. \MID \VOID{} } \\
  11110. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  11111. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  11112. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  11113. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  11114. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  11115. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  11116. \MID \LP\key{GlobalValue}~\Var\RP }\\
  11117. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  11118. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11119. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  11120. \end{array}
  11121. \]
  11122. \end{minipage}
  11123. }
  11124. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  11125. \label{fig:Rfun-anf-syntax}
  11126. \end{figure}
  11127. \section{Explicate Control and the \LangCFun{} language}
  11128. \label{sec:explicate-control-r4}
  11129. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  11130. output of \code{explicate\_control}. (The concrete syntax is given in
  11131. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  11132. functions for assignment and tail contexts should be updated with
  11133. cases for \code{Apply} and \code{FunRef} and the function for
  11134. predicate context should be updated for \code{Apply} but not
  11135. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  11136. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  11137. tail position \code{Apply} becomes \code{TailCall}. We recommend
  11138. defining a new auxiliary function for processing function definitions.
  11139. This code is similar to the case for \code{Program} in \LangVec{}. The
  11140. top-level \code{explicate\_control} function that handles the
  11141. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  11142. all the function definitions.
  11143. \begin{figure}[tp]
  11144. \fbox{
  11145. \begin{minipage}{0.96\textwidth}
  11146. \small
  11147. \[
  11148. \begin{array}{lcl}
  11149. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  11150. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  11151. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  11152. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  11153. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  11154. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  11155. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  11156. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  11157. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  11158. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  11159. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  11160. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  11161. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  11162. \MID \GOTO{\itm{label}} } \\
  11163. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  11164. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  11165. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  11166. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11167. \end{array}
  11168. \]
  11169. \end{minipage}
  11170. }
  11171. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  11172. \label{fig:c3-syntax}
  11173. \end{figure}
  11174. \section{Select Instructions and the \LangXIndCall{} Language}
  11175. \label{sec:select-r4}
  11176. \index{subject}{instruction selection}
  11177. The output of select instructions is a program in the \LangXIndCall{}
  11178. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  11179. \index{subject}{x86}
  11180. \begin{figure}[tp]
  11181. \fbox{
  11182. \begin{minipage}{0.96\textwidth}
  11183. \small
  11184. \[
  11185. \begin{array}{lcl}
  11186. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  11187. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  11188. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  11189. \Instr &::=& \ldots
  11190. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  11191. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  11192. \Block &::= & \Instr\ldots \\
  11193. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  11194. \LangXIndCallM{} &::= & \Def\ldots
  11195. \end{array}
  11196. \]
  11197. \end{minipage}
  11198. }
  11199. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  11200. \label{fig:x86-3-concrete}
  11201. \end{figure}
  11202. \begin{figure}[tp]
  11203. \fbox{
  11204. \begin{minipage}{0.96\textwidth}
  11205. \small
  11206. \[
  11207. \begin{array}{lcl}
  11208. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11209. \MID \BYTEREG{\Reg} } \\
  11210. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  11211. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  11212. \MID \TAILJMP{\Arg}{\itm{int}}\\
  11213. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  11214. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  11215. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  11216. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11217. \end{array}
  11218. \]
  11219. \end{minipage}
  11220. }
  11221. \caption{The abstract syntax of \LangXIndCall{} (extends
  11222. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  11223. \label{fig:x86-3}
  11224. \end{figure}
  11225. An assignment of a function reference to a variable becomes a
  11226. load-effective-address instruction as follows, where $\itm{lhs}'$
  11227. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  11228. to \Arg{} in \LangXIndCallVar{}. \\
  11229. \begin{tabular}{lcl}
  11230. \begin{minipage}{0.35\textwidth}
  11231. \begin{lstlisting}
  11232. |$\itm{lhs}$| = (fun-ref |$f$|);
  11233. \end{lstlisting}
  11234. \end{minipage}
  11235. &
  11236. $\Rightarrow$\qquad\qquad
  11237. &
  11238. \begin{minipage}{0.3\textwidth}
  11239. \begin{lstlisting}
  11240. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  11241. \end{lstlisting}
  11242. \end{minipage}
  11243. \end{tabular} \\
  11244. Regarding function definitions, we need to remove the parameters and
  11245. instead perform parameter passing using the conventions discussed in
  11246. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  11247. registers. We recommend turning the parameters into local variables
  11248. and generating instructions at the beginning of the function to move
  11249. from the argument passing registers to these local variables.
  11250. \begin{lstlisting}
  11251. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  11252. |$\Rightarrow$|
  11253. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  11254. \end{lstlisting}
  11255. The $G'$ control-flow graph is the same as $G$ except that the
  11256. \code{start} block is modified to add the instructions for moving from
  11257. the argument registers to the parameter variables. So the \code{start}
  11258. block of $G$ shown on the left is changed to the code on the right.
  11259. \begin{center}
  11260. \begin{minipage}{0.3\textwidth}
  11261. \begin{lstlisting}
  11262. start:
  11263. |$\itm{instr}_1$|
  11264. |$\vdots$|
  11265. |$\itm{instr}_n$|
  11266. \end{lstlisting}
  11267. \end{minipage}
  11268. $\Rightarrow$
  11269. \begin{minipage}{0.3\textwidth}
  11270. \begin{lstlisting}
  11271. start:
  11272. movq %rdi, |$x_1$|
  11273. movq %rsi, |$x_2$|
  11274. |$\vdots$|
  11275. |$\itm{instr}_1$|
  11276. |$\vdots$|
  11277. |$\itm{instr}_n$|
  11278. \end{lstlisting}
  11279. \end{minipage}
  11280. \end{center}
  11281. By changing the parameters to local variables, we are giving the
  11282. register allocator control over which registers or stack locations to
  11283. use for them. If you implemented the move-biasing challenge
  11284. (Section~\ref{sec:move-biasing}), the register allocator will try to
  11285. assign the parameter variables to the corresponding argument register,
  11286. in which case the \code{patch\_instructions} pass will remove the
  11287. \code{movq} instruction. This happens in the example translation in
  11288. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  11289. the \code{add} function.
  11290. %
  11291. Also, note that the register allocator will perform liveness analysis
  11292. on this sequence of move instructions and build the interference
  11293. graph. So, for example, $x_1$ will be marked as interfering with
  11294. \code{rsi} and that will prevent the assignment of $x_1$ to
  11295. \code{rsi}, which is good, because that would overwrite the argument
  11296. that needs to move into $x_2$.
  11297. Next, consider the compilation of function calls. In the mirror image
  11298. of handling the parameters of function definitions, the arguments need
  11299. to be moved to the argument passing registers. The function call
  11300. itself is performed with an indirect function call. The return value
  11301. from the function is stored in \code{rax}, so it needs to be moved
  11302. into the \itm{lhs}.
  11303. \begin{lstlisting}
  11304. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  11305. |$\Rightarrow$|
  11306. movq |$\itm{arg}_1$|, %rdi
  11307. movq |$\itm{arg}_2$|, %rsi
  11308. |$\vdots$|
  11309. callq *|\itm{fun}|
  11310. movq %rax, |\itm{lhs}|
  11311. \end{lstlisting}
  11312. The \code{IndirectCallq} AST node includes an integer for the arity of
  11313. the function, i.e., the number of parameters. That information is
  11314. useful in the \code{uncover-live} pass for determining which
  11315. argument-passing registers are potentially read during the call.
  11316. For tail calls, the parameter passing is the same as non-tail calls:
  11317. generate instructions to move the arguments into to the argument
  11318. passing registers. After that we need to pop the frame from the
  11319. procedure call stack. However, we do not yet know how big the frame
  11320. is; that gets determined during register allocation. So instead of
  11321. generating those instructions here, we invent a new instruction that
  11322. means ``pop the frame and then do an indirect jump'', which we name
  11323. \code{TailJmp}. The abstract syntax for this instruction includes an
  11324. argument that specifies where to jump and an integer that represents
  11325. the arity of the function being called.
  11326. Recall that in Section~\ref{sec:explicate-control-Lvar} we recommended
  11327. using the label \code{start} for the initial block of a program, and
  11328. in Section~\ref{sec:select-Lvar} we recommended labeling the conclusion
  11329. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  11330. can be compiled to an assignment to \code{rax} followed by a jump to
  11331. \code{conclusion}. With the addition of function definitions, we will
  11332. have a starting block and conclusion for each function, but their
  11333. labels need to be unique. We recommend prepending the function's name
  11334. to \code{start} and \code{conclusion}, respectively, to obtain unique
  11335. labels. (Alternatively, one could \code{gensym} labels for the start
  11336. and conclusion and store them in the $\itm{info}$ field of the
  11337. function definition.)
  11338. \section{Register Allocation}
  11339. \label{sec:register-allocation-r4}
  11340. \subsection{Liveness Analysis}
  11341. \label{sec:liveness-analysis-r4}
  11342. \index{subject}{liveness analysis}
  11343. %% The rest of the passes need only minor modifications to handle the new
  11344. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  11345. %% \code{leaq}.
  11346. The \code{IndirectCallq} instruction should be treated like
  11347. \code{Callq} regarding its written locations $W$, in that they should
  11348. include all the caller-saved registers. Recall that the reason for
  11349. that is to force call-live variables to be assigned to callee-saved
  11350. registers or to be spilled to the stack.
  11351. Regarding the set of read locations $R$ the arity field of
  11352. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  11353. argument-passing registers should be considered as read by those
  11354. instructions.
  11355. \subsection{Build Interference Graph}
  11356. \label{sec:build-interference-r4}
  11357. With the addition of function definitions, we compute an interference
  11358. graph for each function (not just one for the whole program).
  11359. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  11360. spill vector-typed variables that are live during a call to the
  11361. \code{collect}. With the addition of functions to our language, we
  11362. need to revisit this issue. Many functions perform allocation and
  11363. therefore have calls to the collector inside of them. Thus, we should
  11364. not only spill a vector-typed variable when it is live during a call
  11365. to \code{collect}, but we should spill the variable if it is live
  11366. during any function call. Thus, in the \code{build\_interference} pass,
  11367. we recommend adding interference edges between call-live vector-typed
  11368. variables and the callee-saved registers (in addition to the usual
  11369. addition of edges between call-live variables and the caller-saved
  11370. registers).
  11371. \subsection{Allocate Registers}
  11372. The primary change to the \code{allocate\_registers} pass is adding an
  11373. auxiliary function for handling definitions (the \Def{} non-terminal
  11374. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  11375. logic is the same as described in
  11376. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  11377. allocation is performed many times, once for each function definition,
  11378. instead of just once for the whole program.
  11379. \section{Patch Instructions}
  11380. In \code{patch\_instructions}, you should deal with the x86
  11381. idiosyncrasy that the destination argument of \code{leaq} must be a
  11382. register. Additionally, you should ensure that the argument of
  11383. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  11384. code generation more convenient, because we trample many registers
  11385. before the tail call (as explained in the next section).
  11386. \section{Print x86}
  11387. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  11388. \code{IndirectCallq} are straightforward: output their concrete
  11389. syntax.
  11390. \begin{lstlisting}
  11391. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  11392. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  11393. \end{lstlisting}
  11394. The \code{TailJmp} node requires a bit work. A straightforward
  11395. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  11396. before the jump we need to pop the current frame. This sequence of
  11397. instructions is the same as the code for the conclusion of a function,
  11398. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  11399. Regarding function definitions, you will need to generate a prelude
  11400. and conclusion for each one. This code is similar to the prelude and
  11401. conclusion that you generated for the \code{main} function in
  11402. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  11403. should carry out the following steps.
  11404. \begin{enumerate}
  11405. \item Start with \code{.global} and \code{.align} directives followed
  11406. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  11407. example.)
  11408. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  11409. pointer.
  11410. \item Push to the stack all of the callee-saved registers that were
  11411. used for register allocation.
  11412. \item Move the stack pointer \code{rsp} down by the size of the stack
  11413. frame for this function, which depends on the number of regular
  11414. spills. (Aligned to 16 bytes.)
  11415. \item Move the root stack pointer \code{r15} up by the size of the
  11416. root-stack frame for this function, which depends on the number of
  11417. spilled vectors. \label{root-stack-init}
  11418. \item Initialize to zero all of the entries in the root-stack frame.
  11419. \item Jump to the start block.
  11420. \end{enumerate}
  11421. The prelude of the \code{main} function has one additional task: call
  11422. the \code{initialize} function to set up the garbage collector and
  11423. move the value of the global \code{rootstack\_begin} in
  11424. \code{r15}. This should happen before step \ref{root-stack-init}
  11425. above, which depends on \code{r15}.
  11426. The conclusion of every function should do the following.
  11427. \begin{enumerate}
  11428. \item Move the stack pointer back up by the size of the stack frame
  11429. for this function.
  11430. \item Restore the callee-saved registers by popping them from the
  11431. stack.
  11432. \item Move the root stack pointer back down by the size of the
  11433. root-stack frame for this function.
  11434. \item Restore \code{rbp} by popping it from the stack.
  11435. \item Return to the caller with the \code{retq} instruction.
  11436. \end{enumerate}
  11437. \begin{exercise}\normalfont
  11438. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  11439. Create 5 new programs that use functions, including examples that pass
  11440. functions and return functions from other functions, recursive
  11441. functions, functions that create vectors, and functions that make tail
  11442. calls. Test your compiler on these new programs and all of your
  11443. previously created test programs.
  11444. \end{exercise}
  11445. \begin{figure}[tbp]
  11446. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11447. \node (Rfun) at (0,2) {\large \LangFun{}};
  11448. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  11449. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  11450. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  11451. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  11452. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  11453. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  11454. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  11455. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11456. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11457. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11458. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11459. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11460. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11461. \path[->,bend left=15] (Rfun) edge [above] node
  11462. {\ttfamily\footnotesize shrink} (Rfun-1);
  11463. \path[->,bend left=15] (Rfun-1) edge [above] node
  11464. {\ttfamily\footnotesize uniquify} (Rfun-2);
  11465. \path[->,bend left=15] (Rfun-2) edge [right] node
  11466. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  11467. \path[->,bend left=15] (F1-1) edge [below] node
  11468. {\ttfamily\footnotesize limit\_functions} (F1-2);
  11469. \path[->,bend right=15] (F1-2) edge [above] node
  11470. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  11471. \path[->,bend right=15] (F1-3) edge [above] node
  11472. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  11473. \path[->,bend left=15] (F1-4) edge [right] node
  11474. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11475. \path[->,bend right=15] (C3-2) edge [left] node
  11476. {\ttfamily\footnotesize select\_instr.} (x86-2);
  11477. \path[->,bend left=15] (x86-2) edge [left] node
  11478. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11479. \path[->,bend right=15] (x86-2-1) edge [below] node
  11480. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11481. \path[->,bend right=15] (x86-2-2) edge [left] node
  11482. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11483. \path[->,bend left=15] (x86-3) edge [above] node
  11484. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11485. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  11486. \end{tikzpicture}
  11487. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  11488. \label{fig:Rfun-passes}
  11489. \end{figure}
  11490. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  11491. compiling \LangFun{} to x86.
  11492. \section{An Example Translation}
  11493. \label{sec:functions-example}
  11494. Figure~\ref{fig:add-fun} shows an example translation of a simple
  11495. function in \LangFun{} to x86. The figure also includes the results of the
  11496. \code{explicate\_control} and \code{select\_instructions} passes.
  11497. \begin{figure}[htbp]
  11498. \begin{tabular}{ll}
  11499. \begin{minipage}{0.5\textwidth}
  11500. % s3_2.rkt
  11501. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11502. (define (add [x : Integer] [y : Integer])
  11503. : Integer
  11504. (+ x y))
  11505. (add 40 2)
  11506. \end{lstlisting}
  11507. $\Downarrow$
  11508. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11509. (define (add86 [x87 : Integer]
  11510. [y88 : Integer]) : Integer
  11511. add86start:
  11512. return (+ x87 y88);
  11513. )
  11514. (define (main) : Integer ()
  11515. mainstart:
  11516. tmp89 = (fun-ref add86);
  11517. (tail-call tmp89 40 2)
  11518. )
  11519. \end{lstlisting}
  11520. \end{minipage}
  11521. &
  11522. $\Rightarrow$
  11523. \begin{minipage}{0.5\textwidth}
  11524. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11525. (define (add86) : Integer
  11526. add86start:
  11527. movq %rdi, x87
  11528. movq %rsi, y88
  11529. movq x87, %rax
  11530. addq y88, %rax
  11531. jmp add11389conclusion
  11532. )
  11533. (define (main) : Integer
  11534. mainstart:
  11535. leaq (fun-ref add86), tmp89
  11536. movq $40, %rdi
  11537. movq $2, %rsi
  11538. tail-jmp tmp89
  11539. )
  11540. \end{lstlisting}
  11541. $\Downarrow$
  11542. \end{minipage}
  11543. \end{tabular}
  11544. \begin{tabular}{ll}
  11545. \begin{minipage}{0.3\textwidth}
  11546. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11547. .globl add86
  11548. .align 16
  11549. add86:
  11550. pushq %rbp
  11551. movq %rsp, %rbp
  11552. jmp add86start
  11553. add86start:
  11554. movq %rdi, %rax
  11555. addq %rsi, %rax
  11556. jmp add86conclusion
  11557. add86conclusion:
  11558. popq %rbp
  11559. retq
  11560. \end{lstlisting}
  11561. \end{minipage}
  11562. &
  11563. \begin{minipage}{0.5\textwidth}
  11564. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11565. .globl main
  11566. .align 16
  11567. main:
  11568. pushq %rbp
  11569. movq %rsp, %rbp
  11570. movq $16384, %rdi
  11571. movq $16384, %rsi
  11572. callq initialize
  11573. movq rootstack_begin(%rip), %r15
  11574. jmp mainstart
  11575. mainstart:
  11576. leaq add86(%rip), %rcx
  11577. movq $40, %rdi
  11578. movq $2, %rsi
  11579. movq %rcx, %rax
  11580. popq %rbp
  11581. jmp *%rax
  11582. mainconclusion:
  11583. popq %rbp
  11584. retq
  11585. \end{lstlisting}
  11586. \end{minipage}
  11587. \end{tabular}
  11588. \caption{Example compilation of a simple function to x86.}
  11589. \label{fig:add-fun}
  11590. \end{figure}
  11591. % Challenge idea: inlining! (simple version)
  11592. % Further Reading
  11593. \fi % racketEd
  11594. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11595. \chapter{Lexically Scoped Functions}
  11596. \label{ch:Rlam}
  11597. \index{subject}{lambda}
  11598. \index{subject}{lexical scoping}
  11599. \if\edition\racketEd
  11600. This chapter studies lexically scoped functions as they appear in
  11601. functional languages such as Racket. By lexical scoping we mean that a
  11602. function's body may refer to variables whose binding site is outside
  11603. of the function, in an enclosing scope.
  11604. %
  11605. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  11606. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  11607. \key{lambda} form. The body of the \key{lambda}, refers to three
  11608. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  11609. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  11610. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  11611. parameter of function \code{f}. The \key{lambda} is returned from the
  11612. function \code{f}. The main expression of the program includes two
  11613. calls to \code{f} with different arguments for \code{x}, first
  11614. \code{5} then \code{3}. The functions returned from \code{f} are bound
  11615. to variables \code{g} and \code{h}. Even though these two functions
  11616. were created by the same \code{lambda}, they are really different
  11617. functions because they use different values for \code{x}. Applying
  11618. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  11619. \code{15} produces \code{22}. The result of this program is \code{42}.
  11620. \begin{figure}[btp]
  11621. % s4_6.rkt
  11622. \begin{lstlisting}
  11623. (define (f [x : Integer]) : (Integer -> Integer)
  11624. (let ([y 4])
  11625. (lambda: ([z : Integer]) : Integer
  11626. (+ x (+ y z)))))
  11627. (let ([g (f 5)])
  11628. (let ([h (f 3)])
  11629. (+ (g 11) (h 15))))
  11630. \end{lstlisting}
  11631. \caption{Example of a lexically scoped function.}
  11632. \label{fig:lexical-scoping}
  11633. \end{figure}
  11634. The approach that we take for implementing lexically scoped
  11635. functions is to compile them into top-level function definitions,
  11636. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  11637. provide special treatment for variable occurrences such as \code{x}
  11638. and \code{y} in the body of the \code{lambda} of
  11639. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  11640. refer to variables defined outside of it. To identify such variable
  11641. occurrences, we review the standard notion of free variable.
  11642. \begin{definition}
  11643. A variable is \emph{free in expression} $e$ if the variable occurs
  11644. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  11645. variable}
  11646. \end{definition}
  11647. For example, in the expression \code{(+ x (+ y z))} the variables
  11648. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  11649. only \code{x} and \code{y} are free in the following expression
  11650. because \code{z} is bound by the \code{lambda}.
  11651. \begin{lstlisting}
  11652. (lambda: ([z : Integer]) : Integer
  11653. (+ x (+ y z)))
  11654. \end{lstlisting}
  11655. So the free variables of a \code{lambda} are the ones that will need
  11656. special treatment. We need to arrange for some way to transport, at
  11657. runtime, the values of those variables from the point where the
  11658. \code{lambda} was created to the point where the \code{lambda} is
  11659. applied. An efficient solution to the problem, due to
  11660. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  11661. free variables together with the function pointer for the lambda's
  11662. code, an arrangement called a \emph{flat closure} (which we shorten to
  11663. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  11664. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  11665. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  11666. pointers. The function pointer resides at index $0$ and the
  11667. values for the free variables will fill in the rest of the vector.
  11668. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  11669. how closures work. It's a three-step dance. The program first calls
  11670. function \code{f}, which creates a closure for the \code{lambda}. The
  11671. closure is a vector whose first element is a pointer to the top-level
  11672. function that we will generate for the \code{lambda}, the second
  11673. element is the value of \code{x}, which is \code{5}, and the third
  11674. element is \code{4}, the value of \code{y}. The closure does not
  11675. contain an element for \code{z} because \code{z} is not a free
  11676. variable of the \code{lambda}. Creating the closure is step 1 of the
  11677. dance. The closure is returned from \code{f} and bound to \code{g}, as
  11678. shown in Figure~\ref{fig:closures}.
  11679. %
  11680. The second call to \code{f} creates another closure, this time with
  11681. \code{3} in the second slot (for \code{x}). This closure is also
  11682. returned from \code{f} but bound to \code{h}, which is also shown in
  11683. Figure~\ref{fig:closures}.
  11684. \begin{figure}[tbp]
  11685. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  11686. \caption{Example closure representation for the \key{lambda}'s
  11687. in Figure~\ref{fig:lexical-scoping}.}
  11688. \label{fig:closures}
  11689. \end{figure}
  11690. Continuing with the example, consider the application of \code{g} to
  11691. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  11692. obtain the function pointer in the first element of the closure and
  11693. call it, passing in the closure itself and then the regular arguments,
  11694. in this case \code{11}. This technique for applying a closure is step
  11695. 2 of the dance.
  11696. %
  11697. But doesn't this \code{lambda} only take 1 argument, for parameter
  11698. \code{z}? The third and final step of the dance is generating a
  11699. top-level function for a \code{lambda}. We add an additional
  11700. parameter for the closure and we insert a \code{let} at the beginning
  11701. of the function for each free variable, to bind those variables to the
  11702. appropriate elements from the closure parameter.
  11703. %
  11704. This three-step dance is known as \emph{closure conversion}. We
  11705. discuss the details of closure conversion in
  11706. Section~\ref{sec:closure-conversion} and the code generated from the
  11707. example in Section~\ref{sec:example-lambda}. But first we define the
  11708. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  11709. \section{The \LangLam{} Language}
  11710. \label{sec:r5}
  11711. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  11712. functions and lexical scoping, is defined in
  11713. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  11714. the \key{lambda} form to the grammar for \LangFun{}, which already has
  11715. syntax for function application.
  11716. \begin{figure}[tp]
  11717. \centering
  11718. \fbox{
  11719. \begin{minipage}{0.96\textwidth}
  11720. \small
  11721. \[
  11722. \begin{array}{lcl}
  11723. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  11724. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  11725. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  11726. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11727. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11728. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11729. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11730. \MID (\key{and}\;\Exp\;\Exp)
  11731. \MID (\key{or}\;\Exp\;\Exp)
  11732. \MID (\key{not}\;\Exp) } \\
  11733. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11734. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  11735. (\key{vector-ref}\;\Exp\;\Int)} \\
  11736. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11737. \MID (\Exp \; \Exp\ldots) } \\
  11738. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  11739. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  11740. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11741. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  11742. \end{array}
  11743. \]
  11744. \end{minipage}
  11745. }
  11746. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  11747. with \key{lambda}.}
  11748. \label{fig:Rlam-concrete-syntax}
  11749. \end{figure}
  11750. \begin{figure}[tp]
  11751. \centering
  11752. \fbox{
  11753. \begin{minipage}{0.96\textwidth}
  11754. \small
  11755. \[
  11756. \begin{array}{lcl}
  11757. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  11758. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11759. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11760. &\MID& \gray{ \BOOL{\itm{bool}}
  11761. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11762. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  11763. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  11764. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  11765. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  11766. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11767. \end{array}
  11768. \]
  11769. \end{minipage}
  11770. }
  11771. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  11772. \label{fig:Rlam-syntax}
  11773. \end{figure}
  11774. \index{subject}{interpreter}
  11775. \label{sec:interp-Rlambda}
  11776. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  11777. \LangLam{}. The case for \key{lambda} saves the current environment
  11778. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  11779. the environment from the \key{lambda}, the \code{lam-env}, when
  11780. interpreting the body of the \key{lambda}. The \code{lam-env}
  11781. environment is extended with the mapping of parameters to argument
  11782. values.
  11783. \begin{figure}[tbp]
  11784. \begin{lstlisting}
  11785. (define interp-Rlambda_class
  11786. (class interp-Rfun_class
  11787. (super-new)
  11788. (define/override (interp-op op)
  11789. (match op
  11790. ['procedure-arity
  11791. (lambda (v)
  11792. (match v
  11793. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  11794. [else (error 'interp-op "expected a function, not ~a" v)]))]
  11795. [else (super interp-op op)]))
  11796. (define/override ((interp-exp env) e)
  11797. (define recur (interp-exp env))
  11798. (match e
  11799. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  11800. `(function ,xs ,body ,env)]
  11801. [else ((super interp-exp env) e)]))
  11802. ))
  11803. (define (interp-Rlambda p)
  11804. (send (new interp-Rlambda_class) interp-program p))
  11805. \end{lstlisting}
  11806. \caption{Interpreter for \LangLam{}.}
  11807. \label{fig:interp-Rlambda}
  11808. \end{figure}
  11809. \label{sec:type-check-r5}
  11810. \index{subject}{type checking}
  11811. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  11812. \key{lambda} form. The body of the \key{lambda} is checked in an
  11813. environment that includes the current environment (because it is
  11814. lexically scoped) and also includes the \key{lambda}'s parameters. We
  11815. require the body's type to match the declared return type.
  11816. \begin{figure}[tbp]
  11817. \begin{lstlisting}
  11818. (define (type-check-Rlambda env)
  11819. (lambda (e)
  11820. (match e
  11821. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  11822. (define-values (new-body bodyT)
  11823. ((type-check-exp (append (map cons xs Ts) env)) body))
  11824. (define ty `(,@Ts -> ,rT))
  11825. (cond
  11826. [(equal? rT bodyT)
  11827. (values (HasType (Lambda params rT new-body) ty) ty)]
  11828. [else
  11829. (error "mismatch in return type" bodyT rT)])]
  11830. ...
  11831. )))
  11832. \end{lstlisting}
  11833. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  11834. \label{fig:type-check-Rlambda}
  11835. \end{figure}
  11836. \section{Assignment and Lexically Scoped Functions}
  11837. \label{sec:assignment-scoping}
  11838. [UNDER CONSTRUCTION: This section was just moved into this location
  11839. and may need to be updated. -Jeremy]
  11840. The combination of lexically-scoped functions and assignment
  11841. (i.e. \code{set!}) raises a challenge with our approach to
  11842. implementing lexically-scoped functions. Consider the following
  11843. example in which function \code{f} has a free variable \code{x} that
  11844. is changed after \code{f} is created but before the call to \code{f}.
  11845. % loop_test_11.rkt
  11846. \begin{lstlisting}
  11847. (let ([x 0])
  11848. (let ([y 0])
  11849. (let ([z 20])
  11850. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11851. (begin
  11852. (set! x 10)
  11853. (set! y 12)
  11854. (f y))))))
  11855. \end{lstlisting}
  11856. The correct output for this example is \code{42} because the call to
  11857. \code{f} is required to use the current value of \code{x} (which is
  11858. \code{10}). Unfortunately, the closure conversion pass
  11859. (Section~\ref{sec:closure-conversion}) generates code for the
  11860. \code{lambda} that copies the old value of \code{x} into a
  11861. closure. Thus, if we naively add support for assignment to our current
  11862. compiler, the output of this program would be \code{32}.
  11863. A first attempt at solving this problem would be to save a pointer to
  11864. \code{x} in the closure and change the occurrences of \code{x} inside
  11865. the lambda to dereference the pointer. Of course, this would require
  11866. assigning \code{x} to the stack and not to a register. However, the
  11867. problem goes a bit deeper. Consider the following example in which we
  11868. create a counter abstraction by creating a pair of functions that
  11869. share the free variable \code{x}.
  11870. % similar to loop_test_10.rkt
  11871. \begin{lstlisting}
  11872. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  11873. (vector
  11874. (lambda: () : Integer x)
  11875. (lambda: () : Void (set! x (+ 1 x)))))
  11876. (let ([counter (f 0)])
  11877. (let ([get (vector-ref counter 0)])
  11878. (let ([inc (vector-ref counter 1)])
  11879. (begin
  11880. (inc)
  11881. (get)))))
  11882. \end{lstlisting}
  11883. In this example, the lifetime of \code{x} extends beyond the lifetime
  11884. of the call to \code{f}. Thus, if we were to store \code{x} on the
  11885. stack frame for the call to \code{f}, it would be gone by the time we
  11886. call \code{inc} and \code{get}, leaving us with dangling pointers for
  11887. \code{x}. This example demonstrates that when a variable occurs free
  11888. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  11889. value of the variable needs to live on the heap. The verb ``box'' is
  11890. often used for allocating a single value on the heap, producing a
  11891. pointer, and ``unbox'' for dereferencing the pointer.
  11892. We recommend solving these problems by ``boxing'' the local variables
  11893. that are in the intersection of 1) variables that appear on the
  11894. left-hand-side of a \code{set!} and 2) variables that occur free
  11895. inside a \code{lambda}. We shall introduce a new pass named
  11896. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  11897. perform this translation. But before diving into the compiler passes,
  11898. we one more problem to discuss.
  11899. \section{Reveal Functions and the $F_2$ language}
  11900. \label{sec:reveal-functions-r5}
  11901. To support the \code{procedure-arity} operator we need to communicate
  11902. the arity of a function to the point of closure creation. We can
  11903. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  11904. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  11905. output of this pass is the language $F_2$, whose syntax is defined in
  11906. Figure~\ref{fig:f2-syntax}.
  11907. \begin{figure}[tp]
  11908. \centering
  11909. \fbox{
  11910. \begin{minipage}{0.96\textwidth}
  11911. \[
  11912. \begin{array}{lcl}
  11913. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  11914. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11915. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  11916. \end{array}
  11917. \]
  11918. \end{minipage}
  11919. }
  11920. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  11921. (Figure~\ref{fig:Rlam-syntax}).}
  11922. \label{fig:f2-syntax}
  11923. \end{figure}
  11924. \section{Convert Assignments}
  11925. \label{sec:convert-assignments}
  11926. [UNDER CONSTRUCTION: This section was just moved into this location
  11927. and may need to be updated. -Jeremy]
  11928. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  11929. the combination of assignments and lexically-scoped functions requires
  11930. that we box those variables that are both assigned-to and that appear
  11931. free inside a \code{lambda}. The purpose of the
  11932. \code{convert-assignments} pass is to carry out that transformation.
  11933. We recommend placing this pass after \code{uniquify} but before
  11934. \code{reveal-functions}.
  11935. Consider again the first example from
  11936. Section~\ref{sec:assignment-scoping}:
  11937. \begin{lstlisting}
  11938. (let ([x 0])
  11939. (let ([y 0])
  11940. (let ([z 20])
  11941. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11942. (begin
  11943. (set! x 10)
  11944. (set! y 12)
  11945. (f y))))))
  11946. \end{lstlisting}
  11947. The variables \code{x} and \code{y} are assigned-to. The variables
  11948. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  11949. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  11950. The boxing of \code{x} consists of three transformations: initialize
  11951. \code{x} with a vector, replace reads from \code{x} with
  11952. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  11953. \code{vector-set!}. The output of \code{convert-assignments} for this
  11954. example is as follows.
  11955. \begin{lstlisting}
  11956. (define (main) : Integer
  11957. (let ([x0 (vector 0)])
  11958. (let ([y1 0])
  11959. (let ([z2 20])
  11960. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  11961. (+ a3 (+ (vector-ref x0 0) z2)))])
  11962. (begin
  11963. (vector-set! x0 0 10)
  11964. (set! y1 12)
  11965. (f4 y1)))))))
  11966. \end{lstlisting}
  11967. \paragraph{Assigned \& Free}
  11968. We recommend defining an auxiliary function named
  11969. \code{assigned\&free} that takes an expression and simultaneously
  11970. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  11971. that occur free within lambda's, and 3) a new version of the
  11972. expression that records which bound variables occurred in the
  11973. intersection of $A$ and $F$. You can use the struct
  11974. \code{AssignedFree} to do this. Consider the case for
  11975. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  11976. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  11977. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  11978. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  11979. \begin{lstlisting}
  11980. (Let |$x$| |$rhs$| |$body$|)
  11981. |$\Rightarrow$|
  11982. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  11983. \end{lstlisting}
  11984. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  11985. The set of assigned variables for this \code{Let} is
  11986. $A_r \cup (A_b - \{x\})$
  11987. and the set of variables free in lambda's is
  11988. $F_r \cup (F_b - \{x\})$.
  11989. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  11990. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  11991. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  11992. and $F_r$.
  11993. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  11994. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  11995. recursively processing \itm{body}. Wrap each of parameter that occurs
  11996. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  11997. Let $P$ be the set of parameter names in \itm{params}. The result is
  11998. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  11999. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  12000. variables of an expression (see Chapter~\ref{ch:Rlam}).
  12001. \paragraph{Convert Assignments}
  12002. Next we discuss the \code{convert-assignment} pass with its auxiliary
  12003. functions for expressions and definitions. The function for
  12004. expressions, \code{cnvt-assign-exp}, should take an expression and a
  12005. set of assigned-and-free variables (obtained from the result of
  12006. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  12007. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  12008. \code{vector-ref}.
  12009. \begin{lstlisting}
  12010. (Var |$x$|)
  12011. |$\Rightarrow$|
  12012. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  12013. \end{lstlisting}
  12014. %
  12015. In the case for $\LET{\LP\code{AssignedFree}\,
  12016. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  12017. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  12018. \itm{body'} but with $x$ added to the set of assigned-and-free
  12019. variables. Translate the let-expression as follows to bind $x$ to a
  12020. boxed value.
  12021. \begin{lstlisting}
  12022. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  12023. |$\Rightarrow$|
  12024. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  12025. \end{lstlisting}
  12026. %
  12027. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  12028. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  12029. variables, translate the \code{set!} into a \code{vector-set!}
  12030. as follows.
  12031. \begin{lstlisting}
  12032. (SetBang |$x$| |$\itm{rhs}$|)
  12033. |$\Rightarrow$|
  12034. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  12035. \end{lstlisting}
  12036. %
  12037. The case for \code{Lambda} is non-trivial, but it is similar to the
  12038. case for function definitions, which we discuss next.
  12039. The auxiliary function for definitions, \code{cnvt-assign-def},
  12040. applies assignment conversion to function definitions.
  12041. We translate a function definition as follows.
  12042. \begin{lstlisting}
  12043. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  12044. |$\Rightarrow$|
  12045. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  12046. \end{lstlisting}
  12047. So it remains to explain \itm{params'} and $\itm{body}_4$.
  12048. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  12049. \code{assigned\&free} on $\itm{body_1}$.
  12050. Let $P$ be the parameter names in \itm{params}.
  12051. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  12052. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  12053. as the set of assigned-and-free variables.
  12054. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  12055. in a sequence of let-expressions that box the parameters
  12056. that are in $A_b \cap F_b$.
  12057. %
  12058. Regarding \itm{params'}, change the names of the parameters that are
  12059. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  12060. variables can retain the original names). Recall the second example in
  12061. Section~\ref{sec:assignment-scoping} involving a counter
  12062. abstraction. The following is the output of assignment version for
  12063. function \code{f}.
  12064. \begin{lstlisting}
  12065. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  12066. (vector
  12067. (lambda: () : Integer x1)
  12068. (lambda: () : Void (set! x1 (+ 1 x1)))))
  12069. |$\Rightarrow$|
  12070. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  12071. (let ([x1 (vector param_x1)])
  12072. (vector (lambda: () : Integer (vector-ref x1 0))
  12073. (lambda: () : Void
  12074. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  12075. \end{lstlisting}
  12076. \section{Closure Conversion}
  12077. \label{sec:closure-conversion}
  12078. \index{subject}{closure conversion}
  12079. The compiling of lexically-scoped functions into top-level function
  12080. definitions is accomplished in the pass \code{convert-to-closures}
  12081. that comes after \code{reveal-functions} and before
  12082. \code{limit-functions}.
  12083. As usual, we implement the pass as a recursive function over the
  12084. AST. All of the action is in the cases for \key{Lambda} and
  12085. \key{Apply}. We transform a \key{Lambda} expression into an expression
  12086. that creates a closure, that is, a vector whose first element is a
  12087. function pointer and the rest of the elements are the free variables
  12088. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  12089. using \code{vector} so that we can distinguish closures from vectors
  12090. in Section~\ref{sec:optimize-closures} and to record the arity. In
  12091. the generated code below, the \itm{name} is a unique symbol generated
  12092. to identify the function and the \itm{arity} is the number of
  12093. parameters (the length of \itm{ps}).
  12094. \begin{lstlisting}
  12095. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  12096. |$\Rightarrow$|
  12097. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  12098. \end{lstlisting}
  12099. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  12100. create a top-level function definition for each \key{Lambda}, as
  12101. shown below.\\
  12102. \begin{minipage}{0.8\textwidth}
  12103. \begin{lstlisting}
  12104. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  12105. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  12106. ...
  12107. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  12108. |\itm{body'}|)...))
  12109. \end{lstlisting}
  12110. \end{minipage}\\
  12111. The \code{clos} parameter refers to the closure. Translate the type
  12112. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  12113. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  12114. $\itm{fvts}$ are the types of the free variables in the lambda and the
  12115. underscore \code{\_} is a dummy type that we use because it is rather
  12116. difficult to give a type to the function in the closure's
  12117. type.\footnote{To give an accurate type to a closure, we would need to
  12118. add existential types to the type checker~\citep{Minamide:1996ys}.}
  12119. The dummy type is considered to be equal to any other type during type
  12120. checking. The sequence of \key{Let} forms bind the free variables to
  12121. their values obtained from the closure.
  12122. Closure conversion turns functions into vectors, so the type
  12123. annotations in the program must also be translated. We recommend
  12124. defining a auxiliary recursive function for this purpose. Function
  12125. types should be translated as follows.
  12126. \begin{lstlisting}
  12127. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  12128. |$\Rightarrow$|
  12129. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  12130. \end{lstlisting}
  12131. The above type says that the first thing in the vector is a function
  12132. pointer. The first parameter of the function pointer is a vector (a
  12133. closure) and the rest of the parameters are the ones from the original
  12134. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  12135. the closure omits the types of the free variables because 1) those
  12136. types are not available in this context and 2) we do not need them in
  12137. the code that is generated for function application.
  12138. We transform function application into code that retrieves the
  12139. function pointer from the closure and then calls the function, passing
  12140. in the closure as the first argument. We bind $e'$ to a temporary
  12141. variable to avoid code duplication.
  12142. \begin{lstlisting}
  12143. (Apply |$e$| |\itm{es}|)
  12144. |$\Rightarrow$|
  12145. (Let |\itm{tmp}| |$e'$|
  12146. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  12147. \end{lstlisting}
  12148. There is also the question of what to do with references top-level
  12149. function definitions. To maintain a uniform translation of function
  12150. application, we turn function references into closures.
  12151. \begin{tabular}{lll}
  12152. \begin{minipage}{0.3\textwidth}
  12153. \begin{lstlisting}
  12154. (FunRefArity |$f$| |$n$|)
  12155. \end{lstlisting}
  12156. \end{minipage}
  12157. &
  12158. $\Rightarrow$
  12159. &
  12160. \begin{minipage}{0.5\textwidth}
  12161. \begin{lstlisting}
  12162. (Closure |$n$| (FunRef |$f$|) '())
  12163. \end{lstlisting}
  12164. \end{minipage}
  12165. \end{tabular} \\
  12166. %
  12167. The top-level function definitions need to be updated as well to take
  12168. an extra closure parameter.
  12169. \section{An Example Translation}
  12170. \label{sec:example-lambda}
  12171. Figure~\ref{fig:lexical-functions-example} shows the result of
  12172. \code{reveal-functions} and \code{convert-to-closures} for the example
  12173. program demonstrating lexical scoping that we discussed at the
  12174. beginning of this chapter.
  12175. \begin{figure}[tbp]
  12176. \begin{minipage}{0.8\textwidth}
  12177. % tests/lambda_test_6.rkt
  12178. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12179. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  12180. (let ([y8 4])
  12181. (lambda: ([z9 : Integer]) : Integer
  12182. (+ x7 (+ y8 z9)))))
  12183. (define (main) : Integer
  12184. (let ([g0 ((fun-ref-arity f6 1) 5)])
  12185. (let ([h1 ((fun-ref-arity f6 1) 3)])
  12186. (+ (g0 11) (h1 15)))))
  12187. \end{lstlisting}
  12188. $\Rightarrow$
  12189. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12190. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  12191. (let ([y8 4])
  12192. (closure 1 (list (fun-ref lambda2) x7 y8))))
  12193. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  12194. (let ([x7 (vector-ref fvs3 1)])
  12195. (let ([y8 (vector-ref fvs3 2)])
  12196. (+ x7 (+ y8 z9)))))
  12197. (define (main) : Integer
  12198. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  12199. ((vector-ref clos5 0) clos5 5))])
  12200. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  12201. ((vector-ref clos6 0) clos6 3))])
  12202. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  12203. \end{lstlisting}
  12204. \end{minipage}
  12205. \caption{Example of closure conversion.}
  12206. \label{fig:lexical-functions-example}
  12207. \end{figure}
  12208. \begin{exercise}\normalfont
  12209. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  12210. Create 5 new programs that use \key{lambda} functions and make use of
  12211. lexical scoping. Test your compiler on these new programs and all of
  12212. your previously created test programs.
  12213. \end{exercise}
  12214. \section{Expose Allocation}
  12215. \label{sec:expose-allocation-r5}
  12216. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  12217. that allocates and initializes a vector, similar to the translation of
  12218. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  12219. The only difference is replacing the use of
  12220. \ALLOC{\itm{len}}{\itm{type}} with
  12221. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  12222. \section{Explicate Control and \LangCLam{}}
  12223. \label{sec:explicate-r5}
  12224. The output language of \code{explicate\_control} is \LangCLam{} whose
  12225. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  12226. difference with respect to \LangCFun{} is the addition of the
  12227. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  12228. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  12229. similar to the handling of other expressions such as primitive
  12230. operators.
  12231. \begin{figure}[tp]
  12232. \fbox{
  12233. \begin{minipage}{0.96\textwidth}
  12234. \small
  12235. \[
  12236. \begin{array}{lcl}
  12237. \Exp &::= & \ldots
  12238. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  12239. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12240. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12241. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12242. \MID \GOTO{\itm{label}} } \\
  12243. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12244. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  12245. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  12246. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  12247. \end{array}
  12248. \]
  12249. \end{minipage}
  12250. }
  12251. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  12252. \label{fig:c4-syntax}
  12253. \end{figure}
  12254. \section{Select Instructions}
  12255. \label{sec:select-instructions-Rlambda}
  12256. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  12257. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  12258. (Section~\ref{sec:select-instructions-gc}). The only difference is
  12259. that you should place the \itm{arity} in the tag that is stored at
  12260. position $0$ of the vector. Recall that in
  12261. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  12262. was not used. We store the arity in the $5$ bits starting at position
  12263. $58$.
  12264. Compile the \code{procedure-arity} operator into a sequence of
  12265. instructions that access the tag from position $0$ of the vector and
  12266. extract the $5$-bits starting at position $58$ from the tag.
  12267. \begin{figure}[p]
  12268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12269. \node (Rfun) at (0,2) {\large \LangFun{}};
  12270. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  12271. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  12272. \node (F1-0) at (9,2) {\large \LangFunRef{}};
  12273. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  12274. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  12275. \node (F1-3) at (6,0) {\large $F_1$};
  12276. \node (F1-4) at (3,0) {\large $F_1$};
  12277. \node (F1-5) at (0,0) {\large $F_1$};
  12278. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  12279. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12280. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12281. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12282. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12283. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12284. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12285. \path[->,bend left=15] (Rfun) edge [above] node
  12286. {\ttfamily\footnotesize shrink} (Rfun-2);
  12287. \path[->,bend left=15] (Rfun-2) edge [above] node
  12288. {\ttfamily\footnotesize uniquify} (Rfun-3);
  12289. \path[->,bend left=15] (Rfun-3) edge [above] node
  12290. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  12291. \path[->,bend left=15] (F1-0) edge [right] node
  12292. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  12293. \path[->,bend left=15] (F1-1) edge [below] node
  12294. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  12295. \path[->,bend right=15] (F1-2) edge [above] node
  12296. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  12297. \path[->,bend right=15] (F1-3) edge [above] node
  12298. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  12299. \path[->,bend right=15] (F1-4) edge [above] node
  12300. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  12301. \path[->,bend right=15] (F1-5) edge [right] node
  12302. {\ttfamily\footnotesize explicate\_control} (C3-2);
  12303. \path[->,bend left=15] (C3-2) edge [left] node
  12304. {\ttfamily\footnotesize select\_instr.} (x86-2);
  12305. \path[->,bend right=15] (x86-2) edge [left] node
  12306. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12307. \path[->,bend right=15] (x86-2-1) edge [below] node
  12308. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  12309. \path[->,bend right=15] (x86-2-2) edge [left] node
  12310. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  12311. \path[->,bend left=15] (x86-3) edge [above] node
  12312. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  12313. \path[->,bend left=15] (x86-4) edge [right] node
  12314. {\ttfamily\footnotesize print\_x86} (x86-5);
  12315. \end{tikzpicture}
  12316. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  12317. functions.}
  12318. \label{fig:Rlambda-passes}
  12319. \end{figure}
  12320. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  12321. for the compilation of \LangLam{}.
  12322. \clearpage
  12323. \section{Challenge: Optimize Closures}
  12324. \label{sec:optimize-closures}
  12325. In this chapter we compiled lexically-scoped functions into a
  12326. relatively efficient representation: flat closures. However, even this
  12327. representation comes with some overhead. For example, consider the
  12328. following program with a function \code{tail-sum} that does not have
  12329. any free variables and where all the uses of \code{tail-sum} are in
  12330. applications where we know that only \code{tail-sum} is being applied
  12331. (and not any other functions).
  12332. \begin{center}
  12333. \begin{minipage}{0.95\textwidth}
  12334. \begin{lstlisting}
  12335. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  12336. (if (eq? n 0)
  12337. r
  12338. (tail-sum (- n 1) (+ n r))))
  12339. (+ (tail-sum 5 0) 27)
  12340. \end{lstlisting}
  12341. \end{minipage}
  12342. \end{center}
  12343. As described in this chapter, we uniformly apply closure conversion to
  12344. all functions, obtaining the following output for this program.
  12345. \begin{center}
  12346. \begin{minipage}{0.95\textwidth}
  12347. \begin{lstlisting}
  12348. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  12349. (if (eq? n2 0)
  12350. r3
  12351. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  12352. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  12353. (define (main) : Integer
  12354. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  12355. ((vector-ref clos6 0) clos6 5 0)) 27))
  12356. \end{lstlisting}
  12357. \end{minipage}
  12358. \end{center}
  12359. In the previous Chapter, there would be no allocation in the program
  12360. and the calls to \code{tail-sum} would be direct calls. In contrast,
  12361. the above program allocates memory for each \code{closure} and the
  12362. calls to \code{tail-sum} are indirect. These two differences incur
  12363. considerable overhead in a program such as this one, where the
  12364. allocations and indirect calls occur inside a tight loop.
  12365. One might think that this problem is trivial to solve: can't we just
  12366. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  12367. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  12368. e'_n$)} instead of treating it like a call to a closure? We would
  12369. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  12370. %
  12371. However, this problem is not so trivial because a global function may
  12372. ``escape'' and become involved in applications that also involve
  12373. closures. Consider the following example in which the application
  12374. \code{(f 41)} needs to be compiled into a closure application, because
  12375. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  12376. function might also get bound to \code{f}.
  12377. \begin{lstlisting}
  12378. (define (add1 [x : Integer]) : Integer
  12379. (+ x 1))
  12380. (let ([y (read)])
  12381. (let ([f (if (eq? (read) 0)
  12382. add1
  12383. (lambda: ([x : Integer]) : Integer (- x y)))])
  12384. (f 41)))
  12385. \end{lstlisting}
  12386. If a global function name is used in any way other than as the
  12387. operator in a direct call, then we say that the function
  12388. \emph{escapes}. If a global function does not escape, then we do not
  12389. need to perform closure conversion on the function.
  12390. \begin{exercise}\normalfont
  12391. Implement an auxiliary function for detecting which global
  12392. functions escape. Using that function, implement an improved version
  12393. of closure conversion that does not apply closure conversion to
  12394. global functions that do not escape but instead compiles them as
  12395. regular functions. Create several new test cases that check whether
  12396. you properly detect whether global functions escape or not.
  12397. \end{exercise}
  12398. So far we have reduced the overhead of calling global functions, but
  12399. it would also be nice to reduce the overhead of calling a
  12400. \code{lambda} when we can determine at compile time which
  12401. \code{lambda} will be called. We refer to such calls as \emph{known
  12402. calls}. Consider the following example in which a \code{lambda} is
  12403. bound to \code{f} and then applied.
  12404. \begin{lstlisting}
  12405. (let ([y (read)])
  12406. (let ([f (lambda: ([x : Integer]) : Integer
  12407. (+ x y))])
  12408. (f 21)))
  12409. \end{lstlisting}
  12410. Closure conversion compiles \code{(f 21)} into an indirect call:
  12411. \begin{lstlisting}
  12412. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  12413. (let ([y2 (vector-ref fvs6 1)])
  12414. (+ x3 y2)))
  12415. (define (main) : Integer
  12416. (let ([y2 (read)])
  12417. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  12418. ((vector-ref f4 0) f4 21))))
  12419. \end{lstlisting}
  12420. but we can instead compile the application \code{(f 21)} into a direct call
  12421. to \code{lambda5}:
  12422. \begin{lstlisting}
  12423. (define (main) : Integer
  12424. (let ([y2 (read)])
  12425. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  12426. ((fun-ref lambda5) f4 21))))
  12427. \end{lstlisting}
  12428. The problem of determining which lambda will be called from a
  12429. particular application is quite challenging in general and the topic
  12430. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  12431. following exercise we recommend that you compile an application to a
  12432. direct call when the operator is a variable and the variable is
  12433. \code{let}-bound to a closure. This can be accomplished by maintaining
  12434. an environment mapping \code{let}-bound variables to function names.
  12435. Extend the environment whenever you encounter a closure on the
  12436. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  12437. to the name of the global function for the closure. This pass should
  12438. come after closure conversion.
  12439. \begin{exercise}\normalfont
  12440. Implement a compiler pass, named \code{optimize-known-calls}, that
  12441. compiles known calls into direct calls. Verify that your compiler is
  12442. successful in this regard on several example programs.
  12443. \end{exercise}
  12444. These exercises only scratches the surface of optimizing of
  12445. closures. A good next step for the interested reader is to look at the
  12446. work of \citet{Keep:2012ab}.
  12447. \section{Further Reading}
  12448. The notion of lexically scoped anonymous functions predates modern
  12449. computers by about a decade. They were invented by
  12450. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  12451. foundation for logic. Anonymous functions were included in the
  12452. LISP~\citep{McCarthy:1960dz} programming language but were initially
  12453. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  12454. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  12455. compile Scheme programs. However, environments were represented as
  12456. linked lists, so variable lookup was linear in the size of the
  12457. environment. In this chapter we represent environments using flat
  12458. closures, which were invented by
  12459. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  12460. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  12461. closures, variable lookup is constant time but the time to create a
  12462. closure is proportional to the number of its free variables. Flat
  12463. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  12464. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  12465. \fi
  12466. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12467. \chapter{Dynamic Typing}
  12468. \label{ch:Rdyn}
  12469. \index{subject}{dynamic typing}
  12470. \if\edition\racketEd
  12471. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  12472. typed language that is a subset of Racket. This is in contrast to the
  12473. previous chapters, which have studied the compilation of Typed
  12474. Racket. In dynamically typed languages such as \LangDyn{}, a given
  12475. expression may produce a value of a different type each time it is
  12476. executed. Consider the following example with a conditional \code{if}
  12477. expression that may return a Boolean or an integer depending on the
  12478. input to the program.
  12479. % part of dynamic_test_25.rkt
  12480. \begin{lstlisting}
  12481. (not (if (eq? (read) 1) #f 0))
  12482. \end{lstlisting}
  12483. Languages that allow expressions to produce different kinds of values
  12484. are called \emph{polymorphic}, a word composed of the Greek roots
  12485. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  12486. are several kinds of polymorphism in programming languages, such as
  12487. subtype polymorphism and parametric
  12488. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  12489. study in this chapter does not have a special name but it is the kind
  12490. that arises in dynamically typed languages.
  12491. Another characteristic of dynamically typed languages is that
  12492. primitive operations, such as \code{not}, are often defined to operate
  12493. on many different types of values. In fact, in Racket, the \code{not}
  12494. operator produces a result for any kind of value: given \code{\#f} it
  12495. returns \code{\#t} and given anything else it returns \code{\#f}.
  12496. Furthermore, even when primitive operations restrict their inputs to
  12497. values of a certain type, this restriction is enforced at runtime
  12498. instead of during compilation. For example, the following vector
  12499. reference results in a run-time contract violation because the index
  12500. must be in integer, not a Boolean such as \code{\#t}.
  12501. \begin{lstlisting}
  12502. (vector-ref (vector 42) #t)
  12503. \end{lstlisting}
  12504. \begin{figure}[tp]
  12505. \centering
  12506. \fbox{
  12507. \begin{minipage}{0.97\textwidth}
  12508. \[
  12509. \begin{array}{rcl}
  12510. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  12511. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12512. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  12513. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  12514. &\MID& \key{\#t} \MID \key{\#f}
  12515. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  12516. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  12517. \MID \CUNIOP{\key{not}}{\Exp} \\
  12518. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  12519. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  12520. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  12521. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  12522. &\MID& \LP\Exp \; \Exp\ldots\RP
  12523. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  12524. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  12525. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  12526. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  12527. \LangDynM{} &::=& \Def\ldots\; \Exp
  12528. \end{array}
  12529. \]
  12530. \end{minipage}
  12531. }
  12532. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  12533. \label{fig:r7-concrete-syntax}
  12534. \end{figure}
  12535. \begin{figure}[tp]
  12536. \centering
  12537. \fbox{
  12538. \begin{minipage}{0.96\textwidth}
  12539. \small
  12540. \[
  12541. \begin{array}{lcl}
  12542. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  12543. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  12544. &\MID& \BOOL{\itm{bool}}
  12545. \MID \IF{\Exp}{\Exp}{\Exp} \\
  12546. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  12547. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  12548. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  12549. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  12550. \end{array}
  12551. \]
  12552. \end{minipage}
  12553. }
  12554. \caption{The abstract syntax of \LangDyn{}.}
  12555. \label{fig:r7-syntax}
  12556. \end{figure}
  12557. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  12558. defined in Figures~\ref{fig:r7-concrete-syntax} and
  12559. \ref{fig:r7-syntax}.
  12560. %
  12561. There is no type checker for \LangDyn{} because it is not a statically
  12562. typed language (it's dynamically typed!).
  12563. The definitional interpreter for \LangDyn{} is presented in
  12564. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  12565. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  12566. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  12567. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  12568. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  12569. value} that combines an underlying value with a tag that identifies
  12570. what kind of value it is. We define the following struct
  12571. to represented tagged values.
  12572. \begin{lstlisting}
  12573. (struct Tagged (value tag) #:transparent)
  12574. \end{lstlisting}
  12575. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  12576. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  12577. but don't always capture all the information that a type does. For
  12578. example, a vector of type \code{(Vector Any Any)} is tagged with
  12579. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  12580. is tagged with \code{Procedure}.
  12581. Next consider the match case for \code{vector-ref}. The
  12582. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  12583. is used to ensure that the first argument is a vector and the second
  12584. is an integer. If they are not, a \code{trapped-error} is raised.
  12585. Recall from Section~\ref{sec:interp_Lint} that when a definition
  12586. interpreter raises a \code{trapped-error} error, the compiled code
  12587. must also signal an error by exiting with return code \code{255}. A
  12588. \code{trapped-error} is also raised if the index is not less than
  12589. length of the vector.
  12590. \begin{figure}[tbp]
  12591. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12592. (define ((interp-Rdyn-exp env) ast)
  12593. (define recur (interp-Rdyn-exp env))
  12594. (match ast
  12595. [(Var x) (lookup x env)]
  12596. [(Int n) (Tagged n 'Integer)]
  12597. [(Bool b) (Tagged b 'Boolean)]
  12598. [(Lambda xs rt body)
  12599. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  12600. [(Prim 'vector es)
  12601. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  12602. [(Prim 'vector-ref (list e1 e2))
  12603. (define vec (recur e1)) (define i (recur e2))
  12604. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  12605. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  12606. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  12607. (vector-ref (Tagged-value vec) (Tagged-value i))]
  12608. [(Prim 'vector-set! (list e1 e2 e3))
  12609. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  12610. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  12611. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  12612. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  12613. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  12614. (Tagged (void) 'Void)]
  12615. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  12616. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  12617. [(Prim 'or (list e1 e2))
  12618. (define v1 (recur e1))
  12619. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  12620. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  12621. [(Prim op (list e1))
  12622. #:when (set-member? type-predicates op)
  12623. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  12624. [(Prim op es)
  12625. (define args (map recur es))
  12626. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  12627. (unless (for/or ([expected-tags (op-tags op)])
  12628. (equal? expected-tags tags))
  12629. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  12630. (tag-value
  12631. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  12632. [(If q t f)
  12633. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  12634. [(Apply f es)
  12635. (define new-f (recur f)) (define args (map recur es))
  12636. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  12637. (match f-val
  12638. [`(function ,xs ,body ,lam-env)
  12639. (unless (eq? (length xs) (length args))
  12640. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  12641. (define new-env (append (map cons xs args) lam-env))
  12642. ((interp-Rdyn-exp new-env) body)]
  12643. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  12644. \end{lstlisting}
  12645. \caption{Interpreter for the \LangDyn{} language.}
  12646. \label{fig:interp-Rdyn}
  12647. \end{figure}
  12648. \begin{figure}[tbp]
  12649. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12650. (define (interp-op op)
  12651. (match op
  12652. ['+ fx+]
  12653. ['- fx-]
  12654. ['read read-fixnum]
  12655. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  12656. ['< (lambda (v1 v2)
  12657. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  12658. ['<= (lambda (v1 v2)
  12659. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  12660. ['> (lambda (v1 v2)
  12661. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  12662. ['>= (lambda (v1 v2)
  12663. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  12664. ['boolean? boolean?]
  12665. ['integer? fixnum?]
  12666. ['void? void?]
  12667. ['vector? vector?]
  12668. ['vector-length vector-length]
  12669. ['procedure? (match-lambda
  12670. [`(functions ,xs ,body ,env) #t] [else #f])]
  12671. [else (error 'interp-op "unknown operator" op)]))
  12672. (define (op-tags op)
  12673. (match op
  12674. ['+ '((Integer Integer))]
  12675. ['- '((Integer Integer) (Integer))]
  12676. ['read '(())]
  12677. ['not '((Boolean))]
  12678. ['< '((Integer Integer))]
  12679. ['<= '((Integer Integer))]
  12680. ['> '((Integer Integer))]
  12681. ['>= '((Integer Integer))]
  12682. ['vector-length '((Vector))]))
  12683. (define type-predicates
  12684. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  12685. (define (tag-value v)
  12686. (cond [(boolean? v) (Tagged v 'Boolean)]
  12687. [(fixnum? v) (Tagged v 'Integer)]
  12688. [(procedure? v) (Tagged v 'Procedure)]
  12689. [(vector? v) (Tagged v 'Vector)]
  12690. [(void? v) (Tagged v 'Void)]
  12691. [else (error 'tag-value "unidentified value ~a" v)]))
  12692. (define (check-tag val expected ast)
  12693. (define tag (Tagged-tag val))
  12694. (unless (eq? tag expected)
  12695. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  12696. \end{lstlisting}
  12697. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  12698. \label{fig:interp-Rdyn-aux}
  12699. \end{figure}
  12700. \clearpage
  12701. \section{Representation of Tagged Values}
  12702. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  12703. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  12704. values at the bit level. Because almost every operation in \LangDyn{}
  12705. involves manipulating tagged values, the representation must be
  12706. efficient. Recall that all of our values are 64 bits. We shall steal
  12707. the 3 right-most bits to encode the tag. We use $001$ to identify
  12708. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  12709. and $101$ for the void value. We define the following auxiliary
  12710. function for mapping types to tag codes.
  12711. \begin{align*}
  12712. \itm{tagof}(\key{Integer}) &= 001 \\
  12713. \itm{tagof}(\key{Boolean}) &= 100 \\
  12714. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  12715. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  12716. \itm{tagof}(\key{Void}) &= 101
  12717. \end{align*}
  12718. This stealing of 3 bits comes at some price: our integers are reduced
  12719. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  12720. affect vectors and procedures because those values are addresses, and
  12721. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  12722. they are always $000$. Thus, we do not lose information by overwriting
  12723. the rightmost 3 bits with the tag and we can simply zero-out the tag
  12724. to recover the original address.
  12725. To make tagged values into first-class entities, we can give them a
  12726. type, called \code{Any}, and define operations such as \code{Inject}
  12727. and \code{Project} for creating and using them, yielding the \LangAny{}
  12728. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  12729. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  12730. in greater detail.
  12731. \section{The \LangAny{} Language}
  12732. \label{sec:Rany-lang}
  12733. \begin{figure}[tp]
  12734. \centering
  12735. \fbox{
  12736. \begin{minipage}{0.96\textwidth}
  12737. \small
  12738. \[
  12739. \begin{array}{lcl}
  12740. \Type &::= & \ldots \MID \key{Any} \\
  12741. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  12742. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  12743. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  12744. \MID \code{procedure?} \MID \code{void?} \\
  12745. \Exp &::=& \ldots
  12746. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  12747. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  12748. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  12749. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12750. \end{array}
  12751. \]
  12752. \end{minipage}
  12753. }
  12754. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  12755. \label{fig:Rany-syntax}
  12756. \end{figure}
  12757. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  12758. (The concrete syntax of \LangAny{} is in the Appendix,
  12759. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  12760. converts the value produced by expression $e$ of type $T$ into a
  12761. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  12762. produced by expression $e$ into a value of type $T$ or else halts the
  12763. program if the type tag is not equivalent to $T$.
  12764. %
  12765. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  12766. restricted to a flat type $\FType$, which simplifies the
  12767. implementation and corresponds with what is needed for compiling \LangDyn{}.
  12768. The \code{any-vector} operators adapt the vector operations so that
  12769. they can be applied to a value of type \code{Any}. They also
  12770. generalize the vector operations in that the index is not restricted
  12771. to be a literal integer in the grammar but is allowed to be any
  12772. expression.
  12773. The type predicates such as \key{boolean?} expect their argument to
  12774. produce a tagged value; they return \key{\#t} if the tag corresponds
  12775. to the predicate and they return \key{\#f} otherwise.
  12776. The type checker for \LangAny{} is shown in
  12777. Figures~\ref{fig:type-check-Rany-part-1} and
  12778. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  12779. Figure~\ref{fig:type-check-Rany-aux}.
  12780. %
  12781. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  12782. auxiliary functions \code{apply-inject} and \code{apply-project} are
  12783. in Figure~\ref{fig:apply-project}.
  12784. \begin{figure}[btp]
  12785. \begin{lstlisting}[basicstyle=\ttfamily\small]
  12786. (define type-check-Rany_class
  12787. (class type-check-Rlambda_class
  12788. (super-new)
  12789. (inherit check-type-equal?)
  12790. (define/override (type-check-exp env)
  12791. (lambda (e)
  12792. (define recur (type-check-exp env))
  12793. (match e
  12794. [(Inject e1 ty)
  12795. (unless (flat-ty? ty)
  12796. (error 'type-check "may only inject from flat type, not ~a" ty))
  12797. (define-values (new-e1 e-ty) (recur e1))
  12798. (check-type-equal? e-ty ty e)
  12799. (values (Inject new-e1 ty) 'Any)]
  12800. [(Project e1 ty)
  12801. (unless (flat-ty? ty)
  12802. (error 'type-check "may only project to flat type, not ~a" ty))
  12803. (define-values (new-e1 e-ty) (recur e1))
  12804. (check-type-equal? e-ty 'Any e)
  12805. (values (Project new-e1 ty) ty)]
  12806. [(Prim 'any-vector-length (list e1))
  12807. (define-values (e1^ t1) (recur e1))
  12808. (check-type-equal? t1 'Any e)
  12809. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  12810. [(Prim 'any-vector-ref (list e1 e2))
  12811. (define-values (e1^ t1) (recur e1))
  12812. (define-values (e2^ t2) (recur e2))
  12813. (check-type-equal? t1 'Any e)
  12814. (check-type-equal? t2 'Integer e)
  12815. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  12816. [(Prim 'any-vector-set! (list e1 e2 e3))
  12817. (define-values (e1^ t1) (recur e1))
  12818. (define-values (e2^ t2) (recur e2))
  12819. (define-values (e3^ t3) (recur e3))
  12820. (check-type-equal? t1 'Any e)
  12821. (check-type-equal? t2 'Integer e)
  12822. (check-type-equal? t3 'Any e)
  12823. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  12824. \end{lstlisting}
  12825. \caption{Type checker for the \LangAny{} language, part 1.}
  12826. \label{fig:type-check-Rany-part-1}
  12827. \end{figure}
  12828. \begin{figure}[btp]
  12829. \begin{lstlisting}[basicstyle=\ttfamily\small]
  12830. [(ValueOf e ty)
  12831. (define-values (new-e e-ty) (recur e))
  12832. (values (ValueOf new-e ty) ty)]
  12833. [(Prim pred (list e1))
  12834. #:when (set-member? (type-predicates) pred)
  12835. (define-values (new-e1 e-ty) (recur e1))
  12836. (check-type-equal? e-ty 'Any e)
  12837. (values (Prim pred (list new-e1)) 'Boolean)]
  12838. [(If cnd thn els)
  12839. (define-values (cnd^ Tc) (recur cnd))
  12840. (define-values (thn^ Tt) (recur thn))
  12841. (define-values (els^ Te) (recur els))
  12842. (check-type-equal? Tc 'Boolean cnd)
  12843. (check-type-equal? Tt Te e)
  12844. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  12845. [(Exit) (values (Exit) '_)]
  12846. [(Prim 'eq? (list arg1 arg2))
  12847. (define-values (e1 t1) (recur arg1))
  12848. (define-values (e2 t2) (recur arg2))
  12849. (match* (t1 t2)
  12850. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  12851. [(other wise) (check-type-equal? t1 t2 e)])
  12852. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  12853. [else ((super type-check-exp env) e)])))
  12854. ))
  12855. \end{lstlisting}
  12856. \caption{Type checker for the \LangAny{} language, part 2.}
  12857. \label{fig:type-check-Rany-part-2}
  12858. \end{figure}
  12859. \begin{figure}[tbp]
  12860. \begin{lstlisting}
  12861. (define/override (operator-types)
  12862. (append
  12863. '((integer? . ((Any) . Boolean))
  12864. (vector? . ((Any) . Boolean))
  12865. (procedure? . ((Any) . Boolean))
  12866. (void? . ((Any) . Boolean))
  12867. (tag-of-any . ((Any) . Integer))
  12868. (make-any . ((_ Integer) . Any))
  12869. )
  12870. (super operator-types)))
  12871. (define/public (type-predicates)
  12872. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  12873. (define/public (combine-types t1 t2)
  12874. (match (list t1 t2)
  12875. [(list '_ t2) t2]
  12876. [(list t1 '_) t1]
  12877. [(list `(Vector ,ts1 ...)
  12878. `(Vector ,ts2 ...))
  12879. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  12880. (combine-types t1 t2)))]
  12881. [(list `(,ts1 ... -> ,rt1)
  12882. `(,ts2 ... -> ,rt2))
  12883. `(,@(for/list ([t1 ts1] [t2 ts2])
  12884. (combine-types t1 t2))
  12885. -> ,(combine-types rt1 rt2))]
  12886. [else t1]))
  12887. (define/public (flat-ty? ty)
  12888. (match ty
  12889. [(or `Integer `Boolean '_ `Void) #t]
  12890. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  12891. [`(,ts ... -> ,rt)
  12892. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  12893. [else #f]))
  12894. \end{lstlisting}
  12895. \caption{Auxiliary methods for type checking \LangAny{}.}
  12896. \label{fig:type-check-Rany-aux}
  12897. \end{figure}
  12898. \begin{figure}[btp]
  12899. \begin{lstlisting}
  12900. (define interp-Rany_class
  12901. (class interp-Rlambda_class
  12902. (super-new)
  12903. (define/override (interp-op op)
  12904. (match op
  12905. ['boolean? (match-lambda
  12906. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  12907. [else #f])]
  12908. ['integer? (match-lambda
  12909. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  12910. [else #f])]
  12911. ['vector? (match-lambda
  12912. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  12913. [else #f])]
  12914. ['procedure? (match-lambda
  12915. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  12916. [else #f])]
  12917. ['eq? (match-lambda*
  12918. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  12919. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  12920. [ls (apply (super interp-op op) ls)])]
  12921. ['any-vector-ref (lambda (v i)
  12922. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  12923. ['any-vector-set! (lambda (v i a)
  12924. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  12925. ['any-vector-length (lambda (v)
  12926. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  12927. [else (super interp-op op)]))
  12928. (define/override ((interp-exp env) e)
  12929. (define recur (interp-exp env))
  12930. (match e
  12931. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  12932. [(Project e ty2) (apply-project (recur e) ty2)]
  12933. [else ((super interp-exp env) e)]))
  12934. ))
  12935. (define (interp-Rany p)
  12936. (send (new interp-Rany_class) interp-program p))
  12937. \end{lstlisting}
  12938. \caption{Interpreter for \LangAny{}.}
  12939. \label{fig:interp-Rany}
  12940. \end{figure}
  12941. \begin{figure}[tbp]
  12942. \begin{lstlisting}
  12943. (define/public (apply-inject v tg) (Tagged v tg))
  12944. (define/public (apply-project v ty2)
  12945. (define tag2 (any-tag ty2))
  12946. (match v
  12947. [(Tagged v1 tag1)
  12948. (cond
  12949. [(eq? tag1 tag2)
  12950. (match ty2
  12951. [`(Vector ,ts ...)
  12952. (define l1 ((interp-op 'vector-length) v1))
  12953. (cond
  12954. [(eq? l1 (length ts)) v1]
  12955. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  12956. l1 (length ts))])]
  12957. [`(,ts ... -> ,rt)
  12958. (match v1
  12959. [`(function ,xs ,body ,env)
  12960. (cond [(eq? (length xs) (length ts)) v1]
  12961. [else
  12962. (error 'apply-project "arity mismatch ~a != ~a"
  12963. (length xs) (length ts))])]
  12964. [else (error 'apply-project "expected function not ~a" v1)])]
  12965. [else v1])]
  12966. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  12967. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  12968. \end{lstlisting}
  12969. \caption{Auxiliary functions for injection and projection.}
  12970. \label{fig:apply-project}
  12971. \end{figure}
  12972. \clearpage
  12973. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  12974. \label{sec:compile-r7}
  12975. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  12976. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  12977. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  12978. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  12979. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  12980. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  12981. the Boolean \code{\#t}, which must be injected to produce an
  12982. expression of type \key{Any}.
  12983. %
  12984. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  12985. addition, is representative of compilation for many primitive
  12986. operations: the arguments have type \key{Any} and must be projected to
  12987. \key{Integer} before the addition can be performed.
  12988. The compilation of \key{lambda} (third row of
  12989. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  12990. produce type annotations: we simply use \key{Any}.
  12991. %
  12992. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  12993. has to account for some differences in behavior between \LangDyn{} and
  12994. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  12995. kind of values can be used in various places. For example, the
  12996. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  12997. the arguments need not be of the same type (in that case the
  12998. result is \code{\#f}).
  12999. \begin{figure}[btp]
  13000. \centering
  13001. \begin{tabular}{|lll|} \hline
  13002. \begin{minipage}{0.27\textwidth}
  13003. \begin{lstlisting}
  13004. #t
  13005. \end{lstlisting}
  13006. \end{minipage}
  13007. &
  13008. $\Rightarrow$
  13009. &
  13010. \begin{minipage}{0.65\textwidth}
  13011. \begin{lstlisting}
  13012. (inject #t Boolean)
  13013. \end{lstlisting}
  13014. \end{minipage}
  13015. \\[2ex]\hline
  13016. \begin{minipage}{0.27\textwidth}
  13017. \begin{lstlisting}
  13018. (+ |$e_1$| |$e_2$|)
  13019. \end{lstlisting}
  13020. \end{minipage}
  13021. &
  13022. $\Rightarrow$
  13023. &
  13024. \begin{minipage}{0.65\textwidth}
  13025. \begin{lstlisting}
  13026. (inject
  13027. (+ (project |$e'_1$| Integer)
  13028. (project |$e'_2$| Integer))
  13029. Integer)
  13030. \end{lstlisting}
  13031. \end{minipage}
  13032. \\[2ex]\hline
  13033. \begin{minipage}{0.27\textwidth}
  13034. \begin{lstlisting}
  13035. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  13036. \end{lstlisting}
  13037. \end{minipage}
  13038. &
  13039. $\Rightarrow$
  13040. &
  13041. \begin{minipage}{0.65\textwidth}
  13042. \begin{lstlisting}
  13043. (inject
  13044. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  13045. (Any|$\ldots$|Any -> Any))
  13046. \end{lstlisting}
  13047. \end{minipage}
  13048. \\[2ex]\hline
  13049. \begin{minipage}{0.27\textwidth}
  13050. \begin{lstlisting}
  13051. (|$e_0$| |$e_1 \ldots e_n$|)
  13052. \end{lstlisting}
  13053. \end{minipage}
  13054. &
  13055. $\Rightarrow$
  13056. &
  13057. \begin{minipage}{0.65\textwidth}
  13058. \begin{lstlisting}
  13059. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  13060. \end{lstlisting}
  13061. \end{minipage}
  13062. \\[2ex]\hline
  13063. \begin{minipage}{0.27\textwidth}
  13064. \begin{lstlisting}
  13065. (vector-ref |$e_1$| |$e_2$|)
  13066. \end{lstlisting}
  13067. \end{minipage}
  13068. &
  13069. $\Rightarrow$
  13070. &
  13071. \begin{minipage}{0.65\textwidth}
  13072. \begin{lstlisting}
  13073. (any-vector-ref |$e_1'$| |$e_2'$|)
  13074. \end{lstlisting}
  13075. \end{minipage}
  13076. \\[2ex]\hline
  13077. \begin{minipage}{0.27\textwidth}
  13078. \begin{lstlisting}
  13079. (if |$e_1$| |$e_2$| |$e_3$|)
  13080. \end{lstlisting}
  13081. \end{minipage}
  13082. &
  13083. $\Rightarrow$
  13084. &
  13085. \begin{minipage}{0.65\textwidth}
  13086. \begin{lstlisting}
  13087. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  13088. \end{lstlisting}
  13089. \end{minipage}
  13090. \\[2ex]\hline
  13091. \begin{minipage}{0.27\textwidth}
  13092. \begin{lstlisting}
  13093. (eq? |$e_1$| |$e_2$|)
  13094. \end{lstlisting}
  13095. \end{minipage}
  13096. &
  13097. $\Rightarrow$
  13098. &
  13099. \begin{minipage}{0.65\textwidth}
  13100. \begin{lstlisting}
  13101. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  13102. \end{lstlisting}
  13103. \end{minipage}
  13104. \\[2ex]\hline
  13105. \begin{minipage}{0.27\textwidth}
  13106. \begin{lstlisting}
  13107. (not |$e_1$|)
  13108. \end{lstlisting}
  13109. \end{minipage}
  13110. &
  13111. $\Rightarrow$
  13112. &
  13113. \begin{minipage}{0.65\textwidth}
  13114. \begin{lstlisting}
  13115. (if (eq? |$e'_1$| (inject #f Boolean))
  13116. (inject #t Boolean) (inject #f Boolean))
  13117. \end{lstlisting}
  13118. \end{minipage}
  13119. \\[2ex]\hline
  13120. \end{tabular}
  13121. \caption{Cast Insertion}
  13122. \label{fig:compile-r7-Rany}
  13123. \end{figure}
  13124. \section{Reveal Casts}
  13125. \label{sec:reveal-casts-Rany}
  13126. % TODO: define R'_6
  13127. In the \code{reveal-casts} pass we recommend compiling \code{project}
  13128. into an \code{if} expression that checks whether the value's tag
  13129. matches the target type; if it does, the value is converted to a value
  13130. of the target type by removing the tag; if it does not, the program
  13131. exits. To perform these actions we need a new primitive operation,
  13132. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  13133. The \code{tag-of-any} operation retrieves the type tag from a tagged
  13134. value of type \code{Any}. The \code{ValueOf} form retrieves the
  13135. underlying value from a tagged value. The \code{ValueOf} form
  13136. includes the type for the underlying value which is used by the type
  13137. checker. Finally, the \code{Exit} form ends the execution of the
  13138. program.
  13139. If the target type of the projection is \code{Boolean} or
  13140. \code{Integer}, then \code{Project} can be translated as follows.
  13141. \begin{center}
  13142. \begin{minipage}{1.0\textwidth}
  13143. \begin{lstlisting}
  13144. (Project |$e$| |$\FType$|)
  13145. |$\Rightarrow$|
  13146. (Let |$\itm{tmp}$| |$e'$|
  13147. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  13148. (Int |$\itm{tagof}(\FType)$|)))
  13149. (ValueOf |$\itm{tmp}$| |$\FType$|)
  13150. (Exit)))
  13151. \end{lstlisting}
  13152. \end{minipage}
  13153. \end{center}
  13154. If the target type of the projection is a vector or function type,
  13155. then there is a bit more work to do. For vectors, check that the
  13156. length of the vector type matches the length of the vector (using the
  13157. \code{vector-length} primitive). For functions, check that the number
  13158. of parameters in the function type matches the function's arity (using
  13159. \code{procedure-arity}).
  13160. Regarding \code{inject}, we recommend compiling it to a slightly
  13161. lower-level primitive operation named \code{make-any}. This operation
  13162. takes a tag instead of a type.
  13163. \begin{center}
  13164. \begin{minipage}{1.0\textwidth}
  13165. \begin{lstlisting}
  13166. (Inject |$e$| |$\FType$|)
  13167. |$\Rightarrow$|
  13168. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  13169. \end{lstlisting}
  13170. \end{minipage}
  13171. \end{center}
  13172. The type predicates (\code{boolean?}, etc.) can be translated into
  13173. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  13174. translation of \code{Project}.
  13175. The \code{any-vector-ref} and \code{any-vector-set!} operations
  13176. combine the projection action with the vector operation. Also, the
  13177. read and write operations allow arbitrary expressions for the index so
  13178. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  13179. cannot guarantee that the index is within bounds. Thus, we insert code
  13180. to perform bounds checking at runtime. The translation for
  13181. \code{any-vector-ref} is as follows and the other two operations are
  13182. translated in a similar way.
  13183. \begin{lstlisting}
  13184. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  13185. |$\Rightarrow$|
  13186. (Let |$v$| |$e'_1$|
  13187. (Let |$i$| |$e'_2$|
  13188. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  13189. (If (Prim '< (list (Var |$i$|)
  13190. (Prim 'any-vector-length (list (Var |$v$|)))))
  13191. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  13192. (Exit))))
  13193. \end{lstlisting}
  13194. \section{Remove Complex Operands}
  13195. \label{sec:rco-Rany}
  13196. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  13197. The subexpression of \code{ValueOf} must be atomic.
  13198. \section{Explicate Control and \LangCAny{}}
  13199. \label{sec:explicate-Rany}
  13200. The output of \code{explicate\_control} is the \LangCAny{} language whose
  13201. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  13202. form that we added to \LangAny{} remains an expression and the \code{Exit}
  13203. expression becomes a $\Tail$. Also, note that the index argument of
  13204. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  13205. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  13206. \begin{figure}[tp]
  13207. \fbox{
  13208. \begin{minipage}{0.96\textwidth}
  13209. \small
  13210. \[
  13211. \begin{array}{lcl}
  13212. \Exp &::= & \ldots
  13213. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  13214. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  13215. &\MID& \VALUEOF{\Exp}{\FType} \\
  13216. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  13217. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  13218. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  13219. \MID \GOTO{\itm{label}} } \\
  13220. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  13221. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  13222. \MID \LP\key{Exit}\RP \\
  13223. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  13224. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  13225. \end{array}
  13226. \]
  13227. \end{minipage}
  13228. }
  13229. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  13230. \label{fig:c5-syntax}
  13231. \end{figure}
  13232. \section{Select Instructions}
  13233. \label{sec:select-Rany}
  13234. In the \code{select\_instructions} pass we translate the primitive
  13235. operations on the \code{Any} type to x86 instructions that involve
  13236. manipulating the 3 tag bits of the tagged value.
  13237. \paragraph{Make-any}
  13238. We recommend compiling the \key{make-any} primitive as follows if the
  13239. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  13240. shifts the destination to the left by the number of bits specified its
  13241. source argument (in this case $3$, the length of the tag) and it
  13242. preserves the sign of the integer. We use the \key{orq} instruction to
  13243. combine the tag and the value to form the tagged value. \\
  13244. \begin{lstlisting}
  13245. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  13246. |$\Rightarrow$|
  13247. movq |$e'$|, |\itm{lhs'}|
  13248. salq $3, |\itm{lhs'}|
  13249. orq $|$\itm{tag}$|, |\itm{lhs'}|
  13250. \end{lstlisting}
  13251. The instruction selection for vectors and procedures is different
  13252. because their is no need to shift them to the left. The rightmost 3
  13253. bits are already zeros as described at the beginning of this
  13254. chapter. So we just combine the value and the tag using \key{orq}. \\
  13255. \begin{lstlisting}
  13256. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  13257. |$\Rightarrow$|
  13258. movq |$e'$|, |\itm{lhs'}|
  13259. orq $|$\itm{tag}$|, |\itm{lhs'}|
  13260. \end{lstlisting}
  13261. \paragraph{Tag-of-any}
  13262. Recall that the \code{tag-of-any} operation extracts the type tag from
  13263. a value of type \code{Any}. The type tag is the bottom three bits, so
  13264. we obtain the tag by taking the bitwise-and of the value with $111$
  13265. ($7$ in decimal).
  13266. \begin{lstlisting}
  13267. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  13268. |$\Rightarrow$|
  13269. movq |$e'$|, |\itm{lhs'}|
  13270. andq $7, |\itm{lhs'}|
  13271. \end{lstlisting}
  13272. \paragraph{ValueOf}
  13273. Like \key{make-any}, the instructions for \key{ValueOf} are different
  13274. depending on whether the type $T$ is a pointer (vector or procedure)
  13275. or not (Integer or Boolean). The following shows the instruction
  13276. selection for Integer and Boolean. We produce an untagged value by
  13277. shifting it to the right by 3 bits.
  13278. \begin{lstlisting}
  13279. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  13280. |$\Rightarrow$|
  13281. movq |$e'$|, |\itm{lhs'}|
  13282. sarq $3, |\itm{lhs'}|
  13283. \end{lstlisting}
  13284. %
  13285. In the case for vectors and procedures, there is no need to
  13286. shift. Instead we just need to zero-out the rightmost 3 bits. We
  13287. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  13288. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  13289. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  13290. then apply \code{andq} with the tagged value to get the desired
  13291. result. \\
  13292. \begin{lstlisting}
  13293. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  13294. |$\Rightarrow$|
  13295. movq $|$-8$|, |\itm{lhs'}|
  13296. andq |$e'$|, |\itm{lhs'}|
  13297. \end{lstlisting}
  13298. %% \paragraph{Type Predicates} We leave it to the reader to
  13299. %% devise a sequence of instructions to implement the type predicates
  13300. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  13301. \paragraph{Any-vector-length}
  13302. \begin{lstlisting}
  13303. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  13304. |$\Longrightarrow$|
  13305. movq |$\neg 111$|, %r11
  13306. andq |$a_1'$|, %r11
  13307. movq 0(%r11), %r11
  13308. andq $126, %r11
  13309. sarq $1, %r11
  13310. movq %r11, |$\itm{lhs'}$|
  13311. \end{lstlisting}
  13312. \paragraph{Any-vector-ref}
  13313. The index may be an arbitrary atom so instead of computing the offset
  13314. at compile time, instructions need to be generated to compute the
  13315. offset at runtime as follows. Note the use of the new instruction
  13316. \code{imulq}.
  13317. \begin{center}
  13318. \begin{minipage}{0.96\textwidth}
  13319. \begin{lstlisting}
  13320. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  13321. |$\Longrightarrow$|
  13322. movq |$\neg 111$|, %r11
  13323. andq |$a_1'$|, %r11
  13324. movq |$a_2'$|, %rax
  13325. addq $1, %rax
  13326. imulq $8, %rax
  13327. addq %rax, %r11
  13328. movq 0(%r11) |$\itm{lhs'}$|
  13329. \end{lstlisting}
  13330. \end{minipage}
  13331. \end{center}
  13332. \paragraph{Any-vector-set!}
  13333. The code generation for \code{any-vector-set!} is similar to the other
  13334. \code{any-vector} operations.
  13335. \section{Register Allocation for \LangAny{}}
  13336. \label{sec:register-allocation-Rany}
  13337. \index{subject}{register allocation}
  13338. There is an interesting interaction between tagged values and garbage
  13339. collection that has an impact on register allocation. A variable of
  13340. type \code{Any} might refer to a vector and therefore it might be a
  13341. root that needs to be inspected and copied during garbage
  13342. collection. Thus, we need to treat variables of type \code{Any} in a
  13343. similar way to variables of type \code{Vector} for purposes of
  13344. register allocation. In particular,
  13345. \begin{itemize}
  13346. \item If a variable of type \code{Any} is live during a function call,
  13347. then it must be spilled. This can be accomplished by changing
  13348. \code{build\_interference} to mark all variables of type \code{Any}
  13349. that are live after a \code{callq} as interfering with all the
  13350. registers.
  13351. \item If a variable of type \code{Any} is spilled, it must be spilled
  13352. to the root stack instead of the normal procedure call stack.
  13353. \end{itemize}
  13354. Another concern regarding the root stack is that the garbage collector
  13355. needs to differentiate between (1) plain old pointers to tuples, (2) a
  13356. tagged value that points to a tuple, and (3) a tagged value that is
  13357. not a tuple. We enable this differentiation by choosing not to use the
  13358. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  13359. reserved for identifying plain old pointers to tuples. That way, if
  13360. one of the first three bits is set, then we have a tagged value and
  13361. inspecting the tag can differentiation between vectors ($010$) and the
  13362. other kinds of values.
  13363. \begin{exercise}\normalfont
  13364. Expand your compiler to handle \LangAny{} as discussed in the last few
  13365. sections. Create 5 new programs that use the \code{Any} type and the
  13366. new operations (\code{inject}, \code{project}, \code{boolean?},
  13367. etc.). Test your compiler on these new programs and all of your
  13368. previously created test programs.
  13369. \end{exercise}
  13370. \begin{exercise}\normalfont
  13371. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  13372. Create tests for \LangDyn{} by adapting ten of your previous test programs
  13373. by removing type annotations. Add 5 more tests programs that
  13374. specifically rely on the language being dynamically typed. That is,
  13375. they should not be legal programs in a statically typed language, but
  13376. nevertheless, they should be valid \LangDyn{} programs that run to
  13377. completion without error.
  13378. \end{exercise}
  13379. \begin{figure}[p]
  13380. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13381. \node (Rfun) at (0,4) {\large \LangDyn{}};
  13382. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  13383. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  13384. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  13385. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  13386. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  13387. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  13388. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  13389. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  13390. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  13391. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  13392. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  13393. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13394. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13395. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13396. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13397. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13398. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13399. \path[->,bend left=15] (Rfun) edge [above] node
  13400. {\ttfamily\footnotesize shrink} (Rfun-2);
  13401. \path[->,bend left=15] (Rfun-2) edge [above] node
  13402. {\ttfamily\footnotesize uniquify} (Rfun-3);
  13403. \path[->,bend left=15] (Rfun-3) edge [above] node
  13404. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  13405. \path[->,bend right=15] (Rfun-4) edge [left] node
  13406. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  13407. \path[->,bend left=15] (Rfun-5) edge [above] node
  13408. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  13409. \path[->,bend left=15] (Rfun-6) edge [left] node
  13410. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  13411. \path[->,bend left=15] (Rfun-7) edge [below] node
  13412. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  13413. \path[->,bend right=15] (F1-2) edge [above] node
  13414. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  13415. \path[->,bend right=15] (F1-3) edge [above] node
  13416. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13417. \path[->,bend right=15] (F1-4) edge [above] node
  13418. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13419. \path[->,bend right=15] (F1-5) edge [right] node
  13420. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13421. \path[->,bend left=15] (C3-2) edge [left] node
  13422. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13423. \path[->,bend right=15] (x86-2) edge [left] node
  13424. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13425. \path[->,bend right=15] (x86-2-1) edge [below] node
  13426. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13427. \path[->,bend right=15] (x86-2-2) edge [left] node
  13428. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13429. \path[->,bend left=15] (x86-3) edge [above] node
  13430. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13431. \path[->,bend left=15] (x86-4) edge [right] node
  13432. {\ttfamily\footnotesize print\_x86} (x86-5);
  13433. \end{tikzpicture}
  13434. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  13435. \label{fig:Rdyn-passes}
  13436. \end{figure}
  13437. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  13438. for the compilation of \LangDyn{}.
  13439. % Further Reading
  13440. \fi % racketEd
  13441. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13442. \chapter{Objects}
  13443. \label{ch:Robject}
  13444. \index{subject}{objects}
  13445. \index{subject}{classes}
  13446. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13447. \chapter{Gradual Typing}
  13448. \label{ch:Rgrad}
  13449. \index{subject}{gradual typing}
  13450. \if\edition\racketEd
  13451. This chapter studies a language, \LangGrad{}, in which the programmer
  13452. can choose between static and dynamic type checking in different parts
  13453. of a program, thereby mixing the statically typed \LangLoop{} language
  13454. with the dynamically typed \LangDyn{}. There are several approaches to
  13455. mixing static and dynamic typing, including multi-language
  13456. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  13457. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  13458. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  13459. programmer controls the amount of static versus dynamic checking by
  13460. adding or removing type annotations on parameters and
  13461. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  13462. %
  13463. The concrete syntax of \LangGrad{} is defined in
  13464. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  13465. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  13466. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  13467. non-terminals that make type annotations optional. The return types
  13468. are not optional in the abstract syntax; the parser fills in
  13469. \code{Any} when the return type is not specified in the concrete
  13470. syntax.
  13471. \begin{figure}[tp]
  13472. \centering
  13473. \fbox{
  13474. \begin{minipage}{0.96\textwidth}
  13475. \small
  13476. \[
  13477. \begin{array}{lcl}
  13478. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  13479. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  13480. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  13481. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  13482. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  13483. &\MID& \gray{\key{\#t} \MID \key{\#f}
  13484. \MID (\key{and}\;\Exp\;\Exp)
  13485. \MID (\key{or}\;\Exp\;\Exp)
  13486. \MID (\key{not}\;\Exp) } \\
  13487. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  13488. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  13489. (\key{vector-ref}\;\Exp\;\Int)} \\
  13490. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  13491. \MID (\Exp \; \Exp\ldots) } \\
  13492. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  13493. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  13494. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  13495. \MID \CBEGIN{\Exp\ldots}{\Exp}
  13496. \MID \CWHILE{\Exp}{\Exp} } \\
  13497. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  13498. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  13499. \end{array}
  13500. \]
  13501. \end{minipage}
  13502. }
  13503. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  13504. \label{fig:Rgrad-concrete-syntax}
  13505. \end{figure}
  13506. \begin{figure}[tp]
  13507. \centering
  13508. \fbox{
  13509. \begin{minipage}{0.96\textwidth}
  13510. \small
  13511. \[
  13512. \begin{array}{lcl}
  13513. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  13514. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  13515. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  13516. &\MID& \gray{ \BOOL{\itm{bool}}
  13517. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  13518. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  13519. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  13520. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  13521. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  13522. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  13523. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  13524. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13525. \end{array}
  13526. \]
  13527. \end{minipage}
  13528. }
  13529. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  13530. \label{fig:Rgrad-syntax}
  13531. \end{figure}
  13532. Both the type checker and the interpreter for \LangGrad{} require some
  13533. interesting changes to enable gradual typing, which we discuss in the
  13534. next two sections in the context of the \code{map-vec} example from
  13535. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  13536. revised the \code{map-vec} example, omitting the type annotations from
  13537. the \code{add1} function.
  13538. \begin{figure}[btp]
  13539. % gradual_test_9.rkt
  13540. \begin{lstlisting}
  13541. (define (map-vec [f : (Integer -> Integer)]
  13542. [v : (Vector Integer Integer)])
  13543. : (Vector Integer Integer)
  13544. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13545. (define (add1 x) (+ x 1))
  13546. (vector-ref (map-vec add1 (vector 0 41)) 1)
  13547. \end{lstlisting}
  13548. \caption{A partially-typed version of the \code{map-vec} example.}
  13549. \label{fig:gradual-map-vec}
  13550. \end{figure}
  13551. \section{Type Checking \LangGrad{} and \LangCast{}}
  13552. \label{sec:gradual-type-check}
  13553. The type checker for \LangGrad{} uses the \code{Any} type for missing
  13554. parameter and return types. For example, the \code{x} parameter of
  13555. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  13556. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  13557. consider the \code{+} operator inside \code{add1}. It expects both
  13558. arguments to have type \code{Integer}, but its first argument \code{x}
  13559. has type \code{Any}. In a gradually typed language, such differences
  13560. are allowed so long as the types are \emph{consistent}, that is, they
  13561. are equal except in places where there is an \code{Any} type. The type
  13562. \code{Any} is consistent with every other type.
  13563. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  13564. \begin{figure}[tbp]
  13565. \begin{lstlisting}
  13566. (define/public (consistent? t1 t2)
  13567. (match* (t1 t2)
  13568. [('Integer 'Integer) #t]
  13569. [('Boolean 'Boolean) #t]
  13570. [('Void 'Void) #t]
  13571. [('Any t2) #t]
  13572. [(t1 'Any) #t]
  13573. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13574. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  13575. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13576. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  13577. (consistent? rt1 rt2))]
  13578. [(other wise) #f]))
  13579. \end{lstlisting}
  13580. \caption{The consistency predicate on types.}
  13581. \label{fig:consistent}
  13582. \end{figure}
  13583. Returning to the \code{map-vec} example of
  13584. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  13585. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  13586. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  13587. because the two types are consistent. In particular, \code{->} is
  13588. equal to \code{->} and because \code{Any} is consistent with
  13589. \code{Integer}.
  13590. Next consider a program with an error, such as applying the
  13591. \code{map-vec} to a function that sometimes returns a Boolean, as
  13592. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  13593. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  13594. consistent with the type of parameter \code{f} of \code{map-vec}, that
  13595. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  13596. Integer)}. One might say that a gradual type checker is optimistic
  13597. in that it accepts programs that might execute without a runtime type
  13598. error.
  13599. %
  13600. Unfortunately, running this program with input \code{1} triggers an
  13601. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  13602. performs checking at runtime to ensure the integrity of the static
  13603. types, such as the \code{(Integer -> Integer)} annotation on parameter
  13604. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  13605. new \code{Cast} form that is inserted by the type checker. Thus, the
  13606. output of the type checker is a program in the \LangCast{} language, which
  13607. adds \code{Cast} to \LangLoop{}, as shown in
  13608. Figure~\ref{fig:Rgrad-prime-syntax}.
  13609. \begin{figure}[tp]
  13610. \centering
  13611. \fbox{
  13612. \begin{minipage}{0.96\textwidth}
  13613. \small
  13614. \[
  13615. \begin{array}{lcl}
  13616. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  13617. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13618. \end{array}
  13619. \]
  13620. \end{minipage}
  13621. }
  13622. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  13623. \label{fig:Rgrad-prime-syntax}
  13624. \end{figure}
  13625. \begin{figure}[tbp]
  13626. \begin{lstlisting}
  13627. (define (map-vec [f : (Integer -> Integer)]
  13628. [v : (Vector Integer Integer)])
  13629. : (Vector Integer Integer)
  13630. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13631. (define (add1 x) (+ x 1))
  13632. (define (true) #t)
  13633. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  13634. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  13635. \end{lstlisting}
  13636. \caption{A variant of the \code{map-vec} example with an error.}
  13637. \label{fig:map-vec-maybe-add1}
  13638. \end{figure}
  13639. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  13640. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  13641. inserted every time the type checker sees two types that are
  13642. consistent but not equal. In the \code{add1} function, \code{x} is
  13643. cast to \code{Integer} and the result of the \code{+} is cast to
  13644. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  13645. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  13646. \begin{figure}[btp]
  13647. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13648. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13649. : (Vector Integer Integer)
  13650. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13651. (define (add1 [x : Any]) : Any
  13652. (cast (+ (cast x Any Integer) 1) Integer Any))
  13653. (define (true) : Any (cast #t Boolean Any))
  13654. (define (maybe-add1 [x : Any]) : Any
  13655. (if (eq? 0 (read)) (add1 x) (true)))
  13656. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  13657. (vector 0 41)) 0)
  13658. \end{lstlisting}
  13659. \caption{Output of type checking \code{map-vec}
  13660. and \code{maybe-add1}.}
  13661. \label{fig:map-vec-cast}
  13662. \end{figure}
  13663. The type checker for \LangGrad{} is defined in
  13664. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  13665. and \ref{fig:type-check-Rgradual-3}.
  13666. \begin{figure}[tbp]
  13667. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13668. (define type-check-gradual_class
  13669. (class type-check-Rwhile_class
  13670. (super-new)
  13671. (inherit operator-types type-predicates)
  13672. (define/override (type-check-exp env)
  13673. (lambda (e)
  13674. (define recur (type-check-exp env))
  13675. (match e
  13676. [(Prim 'vector-length (list e1))
  13677. (define-values (e1^ t) (recur e1))
  13678. (match t
  13679. [`(Vector ,ts ...)
  13680. (values (Prim 'vector-length (list e1^)) 'Integer)]
  13681. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  13682. [(Prim 'vector-ref (list e1 e2))
  13683. (define-values (e1^ t1) (recur e1))
  13684. (define-values (e2^ t2) (recur e2))
  13685. (check-consistent? t2 'Integer e)
  13686. (match t1
  13687. [`(Vector ,ts ...)
  13688. (match e2^
  13689. [(Int i)
  13690. (unless (and (0 . <= . i) (i . < . (length ts)))
  13691. (error 'type-check "invalid index ~a in ~a" i e))
  13692. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  13693. [else (define e1^^ (make-cast e1^ t1 'Any))
  13694. (define e2^^ (make-cast e2^ t2 'Integer))
  13695. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  13696. ['Any
  13697. (define e2^^ (make-cast e2^ t2 'Integer))
  13698. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  13699. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  13700. [(Prim 'vector-set! (list e1 e2 e3) )
  13701. (define-values (e1^ t1) (recur e1))
  13702. (define-values (e2^ t2) (recur e2))
  13703. (define-values (e3^ t3) (recur e3))
  13704. (check-consistent? t2 'Integer e)
  13705. (match t1
  13706. [`(Vector ,ts ...)
  13707. (match e2^
  13708. [(Int i)
  13709. (unless (and (0 . <= . i) (i . < . (length ts)))
  13710. (error 'type-check "invalid index ~a in ~a" i e))
  13711. (check-consistent? (list-ref ts i) t3 e)
  13712. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  13713. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  13714. [else
  13715. (define e1^^ (make-cast e1^ t1 'Any))
  13716. (define e2^^ (make-cast e2^ t2 'Integer))
  13717. (define e3^^ (make-cast e3^ t3 'Any))
  13718. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  13719. ['Any
  13720. (define e2^^ (make-cast e2^ t2 'Integer))
  13721. (define e3^^ (make-cast e3^ t3 'Any))
  13722. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  13723. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  13724. \end{lstlisting}
  13725. \caption{Type checker for the \LangGrad{} language, part 1.}
  13726. \label{fig:type-check-Rgradual-1}
  13727. \end{figure}
  13728. \begin{figure}[tbp]
  13729. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13730. [(Prim 'eq? (list e1 e2))
  13731. (define-values (e1^ t1) (recur e1))
  13732. (define-values (e2^ t2) (recur e2))
  13733. (check-consistent? t1 t2 e)
  13734. (define T (meet t1 t2))
  13735. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  13736. 'Boolean)]
  13737. [(Prim 'not (list e1))
  13738. (define-values (e1^ t1) (recur e1))
  13739. (match t1
  13740. ['Any
  13741. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  13742. (Bool #t) (Bool #f)))]
  13743. [else
  13744. (define-values (t-ret new-es^)
  13745. (type-check-op 'not (list t1) (list e1^) e))
  13746. (values (Prim 'not new-es^) t-ret)])]
  13747. [(Prim 'and (list e1 e2))
  13748. (recur (If e1 e2 (Bool #f)))]
  13749. [(Prim 'or (list e1 e2))
  13750. (define tmp (gensym 'tmp))
  13751. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  13752. [(Prim op es)
  13753. #:when (not (set-member? explicit-prim-ops op))
  13754. (define-values (new-es ts)
  13755. (for/lists (exprs types) ([e es])
  13756. (recur e)))
  13757. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  13758. (values (Prim op new-es^) t-ret)]
  13759. [(If e1 e2 e3)
  13760. (define-values (e1^ T1) (recur e1))
  13761. (define-values (e2^ T2) (recur e2))
  13762. (define-values (e3^ T3) (recur e3))
  13763. (check-consistent? T2 T3 e)
  13764. (match T1
  13765. ['Boolean
  13766. (define Tif (join T2 T3))
  13767. (values (If e1^ (make-cast e2^ T2 Tif)
  13768. (make-cast e3^ T3 Tif)) Tif)]
  13769. ['Any
  13770. (define Tif (meet T2 T3))
  13771. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  13772. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  13773. Tif)]
  13774. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  13775. [(HasType e1 T)
  13776. (define-values (e1^ T1) (recur e1))
  13777. (check-consistent? T1 T)
  13778. (values (make-cast e1^ T1 T) T)]
  13779. [(SetBang x e1)
  13780. (define-values (e1^ T1) (recur e1))
  13781. (define varT (dict-ref env x))
  13782. (check-consistent? T1 varT e)
  13783. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  13784. [(WhileLoop e1 e2)
  13785. (define-values (e1^ T1) (recur e1))
  13786. (check-consistent? T1 'Boolean e)
  13787. (define-values (e2^ T2) ((type-check-exp env) e2))
  13788. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  13789. \end{lstlisting}
  13790. \caption{Type checker for the \LangGrad{} language, part 2.}
  13791. \label{fig:type-check-Rgradual-2}
  13792. \end{figure}
  13793. \begin{figure}[tbp]
  13794. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13795. [(Apply e1 e2s)
  13796. (define-values (e1^ T1) (recur e1))
  13797. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  13798. (match T1
  13799. [`(,T1ps ... -> ,T1rt)
  13800. (for ([T2 T2s] [Tp T1ps])
  13801. (check-consistent? T2 Tp e))
  13802. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  13803. (make-cast e2 src tgt)))
  13804. (values (Apply e1^ e2s^^) T1rt)]
  13805. [`Any
  13806. (define e1^^ (make-cast e1^ 'Any
  13807. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  13808. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  13809. (make-cast e2 src 'Any)))
  13810. (values (Apply e1^^ e2s^^) 'Any)]
  13811. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  13812. [(Lambda params Tr e1)
  13813. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  13814. (match p
  13815. [`[,x : ,T] (values x T)]
  13816. [(? symbol? x) (values x 'Any)])))
  13817. (define-values (e1^ T1)
  13818. ((type-check-exp (append (map cons xs Ts) env)) e1))
  13819. (check-consistent? Tr T1 e)
  13820. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  13821. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  13822. [else ((super type-check-exp env) e)]
  13823. )))
  13824. \end{lstlisting}
  13825. \caption{Type checker for the \LangGrad{} language, part 3.}
  13826. \label{fig:type-check-Rgradual-3}
  13827. \end{figure}
  13828. \begin{figure}[tbp]
  13829. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13830. (define/public (join t1 t2)
  13831. (match* (t1 t2)
  13832. [('Integer 'Integer) 'Integer]
  13833. [('Boolean 'Boolean) 'Boolean]
  13834. [('Void 'Void) 'Void]
  13835. [('Any t2) t2]
  13836. [(t1 'Any) t1]
  13837. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13838. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  13839. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13840. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  13841. -> ,(join rt1 rt2))]))
  13842. (define/public (meet t1 t2)
  13843. (match* (t1 t2)
  13844. [('Integer 'Integer) 'Integer]
  13845. [('Boolean 'Boolean) 'Boolean]
  13846. [('Void 'Void) 'Void]
  13847. [('Any t2) 'Any]
  13848. [(t1 'Any) 'Any]
  13849. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13850. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  13851. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13852. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  13853. -> ,(meet rt1 rt2))]))
  13854. (define/public (make-cast e src tgt)
  13855. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  13856. (define/public (check-consistent? t1 t2 e)
  13857. (unless (consistent? t1 t2)
  13858. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  13859. (define/override (type-check-op op arg-types args e)
  13860. (match (dict-ref (operator-types) op)
  13861. [`(,param-types . ,return-type)
  13862. (for ([at arg-types] [pt param-types])
  13863. (check-consistent? at pt e))
  13864. (values return-type
  13865. (for/list ([e args] [s arg-types] [t param-types])
  13866. (make-cast e s t)))]
  13867. [else (error 'type-check-op "unrecognized ~a" op)]))
  13868. (define explicit-prim-ops
  13869. (set-union
  13870. (type-predicates)
  13871. (set 'procedure-arity 'eq?
  13872. 'vector 'vector-length 'vector-ref 'vector-set!
  13873. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  13874. (define/override (fun-def-type d)
  13875. (match d
  13876. [(Def f params rt info body)
  13877. (define ps
  13878. (for/list ([p params])
  13879. (match p
  13880. [`[,x : ,T] T]
  13881. [(? symbol?) 'Any]
  13882. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  13883. `(,@ps -> ,rt)]
  13884. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  13885. \end{lstlisting}
  13886. \caption{Auxiliary functions for type checking \LangGrad{}.}
  13887. \label{fig:type-check-Rgradual-aux}
  13888. \end{figure}
  13889. \clearpage
  13890. \section{Interpreting \LangCast{}}
  13891. \label{sec:interp-casts}
  13892. The runtime behavior of first-order casts is straightforward, that is,
  13893. casts involving simple types such as \code{Integer} and
  13894. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  13895. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  13896. puts the integer into a tagged value
  13897. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  13898. \code{Integer} is accomplished with the \code{Project} operator, that
  13899. is, by checking the value's tag and either retrieving the underlying
  13900. integer or signaling an error if it the tag is not the one for
  13901. integers (Figure~\ref{fig:apply-project}).
  13902. %
  13903. Things get more interesting for higher-order casts, that is, casts
  13904. involving function or vector types.
  13905. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  13906. Any)} to \code{(Integer -> Integer)}. When a function flows through
  13907. this cast at runtime, we can't know in general whether the function
  13908. will always return an integer.\footnote{Predicting the return value of
  13909. a function is equivalent to the halting problem, which is
  13910. undecidable.} The \LangCast{} interpreter therefore delays the checking
  13911. of the cast until the function is applied. This is accomplished by
  13912. wrapping \code{maybe-add1} in a new function that casts its parameter
  13913. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  13914. casts the return value from \code{Any} to \code{Integer}.
  13915. Turning our attention to casts involving vector types, we consider the
  13916. example in Figure~\ref{fig:map-vec-bang} that defines a
  13917. partially-typed version of \code{map-vec} whose parameter \code{v} has
  13918. type \code{(Vector Any Any)} and that updates \code{v} in place
  13919. instead of returning a new vector. So we name this function
  13920. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  13921. the type checker inserts a cast from \code{(Vector Integer Integer)}
  13922. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  13923. cast between vector types would be a build a new vector whose elements
  13924. are the result of casting each of the original elements to the
  13925. appropriate target type. However, this approach is only valid for
  13926. immutable vectors; and our vectors are mutable. In the example of
  13927. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  13928. the updates inside of \code{map-vec!} would happen to the new vector
  13929. and not the original one.
  13930. \begin{figure}[tbp]
  13931. % gradual_test_11.rkt
  13932. \begin{lstlisting}
  13933. (define (map-vec! [f : (Any -> Any)]
  13934. [v : (Vector Any Any)]) : Void
  13935. (begin
  13936. (vector-set! v 0 (f (vector-ref v 0)))
  13937. (vector-set! v 1 (f (vector-ref v 1)))))
  13938. (define (add1 x) (+ x 1))
  13939. (let ([v (vector 0 41)])
  13940. (begin (map-vec! add1 v) (vector-ref v 1)))
  13941. \end{lstlisting}
  13942. \caption{An example involving casts on vectors.}
  13943. \label{fig:map-vec-bang}
  13944. \end{figure}
  13945. Instead the interpreter needs to create a new kind of value, a
  13946. \emph{vector proxy}, that intercepts every vector operation. On a
  13947. read, the proxy reads from the underlying vector and then applies a
  13948. cast to the resulting value. On a write, the proxy casts the argument
  13949. value and then performs the write to the underlying vector. For the
  13950. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  13951. \code{0} from \code{Integer} to \code{Any}. For the first
  13952. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  13953. to \code{Integer}.
  13954. The final category of cast that we need to consider are casts between
  13955. the \code{Any} type and either a function or a vector
  13956. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  13957. in which parameter \code{v} does not have a type annotation, so it is
  13958. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  13959. type \code{(Vector Integer Integer)} so the type checker inserts a
  13960. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  13961. thought is to use \code{Inject}, but that doesn't work because
  13962. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  13963. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  13964. to \code{Any}.
  13965. \begin{figure}[tbp]
  13966. \begin{lstlisting}
  13967. (define (map-vec! [f : (Any -> Any)] v) : Void
  13968. (begin
  13969. (vector-set! v 0 (f (vector-ref v 0)))
  13970. (vector-set! v 1 (f (vector-ref v 1)))))
  13971. (define (add1 x) (+ x 1))
  13972. (let ([v (vector 0 41)])
  13973. (begin (map-vec! add1 v) (vector-ref v 1)))
  13974. \end{lstlisting}
  13975. \caption{Casting a vector to \code{Any}.}
  13976. \label{fig:map-vec-any}
  13977. \end{figure}
  13978. The \LangCast{} interpreter uses an auxiliary function named
  13979. \code{apply-cast} to cast a value from a source type to a target type,
  13980. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  13981. of the kinds of casts that we've discussed in this section.
  13982. \begin{figure}[tbp]
  13983. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13984. (define/public (apply-cast v s t)
  13985. (match* (s t)
  13986. [(t1 t2) #:when (equal? t1 t2) v]
  13987. [('Any t2)
  13988. (match t2
  13989. [`(,ts ... -> ,rt)
  13990. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  13991. (define v^ (apply-project v any->any))
  13992. (apply-cast v^ any->any `(,@ts -> ,rt))]
  13993. [`(Vector ,ts ...)
  13994. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  13995. (define v^ (apply-project v vec-any))
  13996. (apply-cast v^ vec-any `(Vector ,@ts))]
  13997. [else (apply-project v t2)])]
  13998. [(t1 'Any)
  13999. (match t1
  14000. [`(,ts ... -> ,rt)
  14001. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  14002. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  14003. (apply-inject v^ (any-tag any->any))]
  14004. [`(Vector ,ts ...)
  14005. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  14006. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  14007. (apply-inject v^ (any-tag vec-any))]
  14008. [else (apply-inject v (any-tag t1))])]
  14009. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14010. (define x (gensym 'x))
  14011. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  14012. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  14013. (define cast-writes
  14014. (for/list ([t1 ts1] [t2 ts2])
  14015. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  14016. `(vector-proxy ,(vector v (apply vector cast-reads)
  14017. (apply vector cast-writes)))]
  14018. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14019. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  14020. `(function ,xs ,(Cast
  14021. (Apply (Value v)
  14022. (for/list ([x xs][t1 ts1][t2 ts2])
  14023. (Cast (Var x) t2 t1)))
  14024. rt1 rt2) ())]
  14025. ))
  14026. \end{lstlisting}
  14027. \caption{The \code{apply-cast} auxiliary method.}
  14028. \label{fig:apply-cast}
  14029. \end{figure}
  14030. The interpreter for \LangCast{} is defined in
  14031. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  14032. dispatching to \code{apply-cast}. To handle the addition of vector
  14033. proxies, we update the vector primitives in \code{interp-op} using the
  14034. functions in Figure~\ref{fig:guarded-vector}.
  14035. \begin{figure}[tbp]
  14036. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14037. (define interp-Rcast_class
  14038. (class interp-Rwhile_class
  14039. (super-new)
  14040. (inherit apply-fun apply-inject apply-project)
  14041. (define/override (interp-op op)
  14042. (match op
  14043. ['vector-length guarded-vector-length]
  14044. ['vector-ref guarded-vector-ref]
  14045. ['vector-set! guarded-vector-set!]
  14046. ['any-vector-ref (lambda (v i)
  14047. (match v [`(tagged ,v^ ,tg)
  14048. (guarded-vector-ref v^ i)]))]
  14049. ['any-vector-set! (lambda (v i a)
  14050. (match v [`(tagged ,v^ ,tg)
  14051. (guarded-vector-set! v^ i a)]))]
  14052. ['any-vector-length (lambda (v)
  14053. (match v [`(tagged ,v^ ,tg)
  14054. (guarded-vector-length v^)]))]
  14055. [else (super interp-op op)]
  14056. ))
  14057. (define/override ((interp-exp env) e)
  14058. (define (recur e) ((interp-exp env) e))
  14059. (match e
  14060. [(Value v) v]
  14061. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  14062. [else ((super interp-exp env) e)]))
  14063. ))
  14064. (define (interp-Rcast p)
  14065. (send (new interp-Rcast_class) interp-program p))
  14066. \end{lstlisting}
  14067. \caption{The interpreter for \LangCast{}.}
  14068. \label{fig:interp-Rcast}
  14069. \end{figure}
  14070. \begin{figure}[tbp]
  14071. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14072. (define (guarded-vector-ref vec i)
  14073. (match vec
  14074. [`(vector-proxy ,proxy)
  14075. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  14076. (define rd (vector-ref (vector-ref proxy 1) i))
  14077. (apply-fun rd (list val) 'guarded-vector-ref)]
  14078. [else (vector-ref vec i)]))
  14079. (define (guarded-vector-set! vec i arg)
  14080. (match vec
  14081. [`(vector-proxy ,proxy)
  14082. (define wr (vector-ref (vector-ref proxy 2) i))
  14083. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  14084. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  14085. [else (vector-set! vec i arg)]))
  14086. (define (guarded-vector-length vec)
  14087. (match vec
  14088. [`(vector-proxy ,proxy)
  14089. (guarded-vector-length (vector-ref proxy 0))]
  14090. [else (vector-length vec)]))
  14091. \end{lstlisting}
  14092. \caption{The guarded-vector auxiliary functions.}
  14093. \label{fig:guarded-vector}
  14094. \end{figure}
  14095. \section{Lower Casts}
  14096. \label{sec:lower-casts}
  14097. The next step in the journey towards x86 is the \code{lower-casts}
  14098. pass that translates the casts in \LangCast{} to the lower-level
  14099. \code{Inject} and \code{Project} operators and a new operator for
  14100. creating vector proxies, extending the \LangLoop{} language to create
  14101. \LangProxy{}. We recommend creating an auxiliary function named
  14102. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  14103. and a target type, and translates it to expression in \LangProxy{} that has
  14104. the same behavior as casting the expression from the source to the
  14105. target type in the interpreter.
  14106. The \code{lower-cast} function can follow a code structure similar to
  14107. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  14108. the interpreter for \LangCast{} because it must handle the same cases as
  14109. \code{apply-cast} and it needs to mimic the behavior of
  14110. \code{apply-cast}. The most interesting cases are those concerning the
  14111. casts between two vector types and between two function types.
  14112. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  14113. type to another vector type is accomplished by creating a proxy that
  14114. intercepts the operations on the underlying vector. Here we make the
  14115. creation of the proxy explicit with the \code{vector-proxy} primitive
  14116. operation. It takes three arguments, the first is an expression for
  14117. the vector, the second is a vector of functions for casting an element
  14118. that is being read from the vector, and the third is a vector of
  14119. functions for casting an element that is being written to the vector.
  14120. You can create the functions using \code{Lambda}. Also, as we shall
  14121. see in the next section, we need to differentiate these vectors from
  14122. the user-created ones, so we recommend using a new primitive operator
  14123. named \code{raw-vector} instead of \code{vector} to create these
  14124. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  14125. the output of \code{lower-casts} on the example in
  14126. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  14127. integers to a vector of \code{Any}.
  14128. \begin{figure}[tbp]
  14129. \begin{lstlisting}
  14130. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  14131. (begin
  14132. (vector-set! v 0 (f (vector-ref v 0)))
  14133. (vector-set! v 1 (f (vector-ref v 1)))))
  14134. (define (add1 [x : Any]) : Any
  14135. (inject (+ (project x Integer) 1) Integer))
  14136. (let ([v (vector 0 41)])
  14137. (begin
  14138. (map-vec! add1 (vector-proxy v
  14139. (raw-vector (lambda: ([x9 : Integer]) : Any
  14140. (inject x9 Integer))
  14141. (lambda: ([x9 : Integer]) : Any
  14142. (inject x9 Integer)))
  14143. (raw-vector (lambda: ([x9 : Any]) : Integer
  14144. (project x9 Integer))
  14145. (lambda: ([x9 : Any]) : Integer
  14146. (project x9 Integer)))))
  14147. (vector-ref v 1)))
  14148. \end{lstlisting}
  14149. \caption{Output of \code{lower-casts} on the example in
  14150. Figure~\ref{fig:map-vec-bang}.}
  14151. \label{fig:map-vec-bang-lower-cast}
  14152. \end{figure}
  14153. A cast from one function type to another function type is accomplished
  14154. by generating a \code{Lambda} whose parameter and return types match
  14155. the target function type. The body of the \code{Lambda} should cast
  14156. the parameters from the target type to the source type (yes,
  14157. backwards! functions are contravariant\index{subject}{contravariant} in the
  14158. parameters), then call the underlying function, and finally cast the
  14159. result from the source return type to the target return type.
  14160. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  14161. \code{lower-casts} pass on the \code{map-vec} example in
  14162. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  14163. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  14164. \begin{figure}[tbp]
  14165. \begin{lstlisting}
  14166. (define (map-vec [f : (Integer -> Integer)]
  14167. [v : (Vector Integer Integer)])
  14168. : (Vector Integer Integer)
  14169. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14170. (define (add1 [x : Any]) : Any
  14171. (inject (+ (project x Integer) 1) Integer))
  14172. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  14173. (project (add1 (inject x9 Integer)) Integer))
  14174. (vector 0 41)) 1)
  14175. \end{lstlisting}
  14176. \caption{Output of \code{lower-casts} on the example in
  14177. Figure~\ref{fig:gradual-map-vec}.}
  14178. \label{fig:map-vec-lower-cast}
  14179. \end{figure}
  14180. \section{Differentiate Proxies}
  14181. \label{sec:differentiate-proxies}
  14182. So far the job of differentiating vectors and vector proxies has been
  14183. the job of the interpreter. For example, the interpreter for \LangCast{}
  14184. implements \code{vector-ref} using the \code{guarded-vector-ref}
  14185. function in Figure~\ref{fig:guarded-vector}. In the
  14186. \code{differentiate-proxies} pass we shift this responsibility to the
  14187. generated code.
  14188. We begin by designing the output language $R^p_8$. In
  14189. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  14190. proxies. In $R^p_8$ we return the \code{Vector} type to
  14191. its original meaning, as the type of real vectors, and we introduce a
  14192. new type, \code{PVector}, whose values can be either real vectors or
  14193. vector proxies. This new type comes with a suite of new primitive
  14194. operations for creating and using values of type \code{PVector}. We
  14195. don't need to introduce a new type to represent vector proxies. A
  14196. proxy is represented by a vector containing three things: 1) the
  14197. underlying vector, 2) a vector of functions for casting elements that
  14198. are read from the vector, and 3) a vector of functions for casting
  14199. values to be written to the vector. So we define the following
  14200. abbreviation for the type of a vector proxy:
  14201. \[
  14202. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  14203. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  14204. \to (\key{PVector}~ T' \ldots)
  14205. \]
  14206. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  14207. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  14208. %
  14209. Next we describe each of the new primitive operations.
  14210. \begin{description}
  14211. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  14212. (\key{PVector} $T \ldots$)]\ \\
  14213. %
  14214. This operation brands a vector as a value of the \code{PVector} type.
  14215. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  14216. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  14217. %
  14218. This operation brands a vector proxy as value of the \code{PVector} type.
  14219. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  14220. \code{Boolean}] \ \\
  14221. %
  14222. returns true if the value is a vector proxy and false if it is a
  14223. real vector.
  14224. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  14225. (\key{Vector} $T \ldots$)]\ \\
  14226. %
  14227. Assuming that the input is a vector (and not a proxy), this
  14228. operation returns the vector.
  14229. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  14230. $\to$ \code{Boolean}]\ \\
  14231. %
  14232. Given a vector proxy, this operation returns the length of the
  14233. underlying vector.
  14234. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  14235. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  14236. %
  14237. Given a vector proxy, this operation returns the $i$th element of
  14238. the underlying vector.
  14239. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  14240. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  14241. proxy, this operation writes a value to the $i$th element of the
  14242. underlying vector.
  14243. \end{description}
  14244. Now to discuss the translation that differentiates vectors from
  14245. proxies. First, every type annotation in the program must be
  14246. translated (recursively) to replace \code{Vector} with \code{PVector}.
  14247. Next, we must insert uses of \code{PVector} operations in the
  14248. appropriate places. For example, we wrap every vector creation with an
  14249. \code{inject-vector}.
  14250. \begin{lstlisting}
  14251. (vector |$e_1 \ldots e_n$|)
  14252. |$\Rightarrow$|
  14253. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  14254. \end{lstlisting}
  14255. The \code{raw-vector} operator that we introduced in the previous
  14256. section does not get injected.
  14257. \begin{lstlisting}
  14258. (raw-vector |$e_1 \ldots e_n$|)
  14259. |$\Rightarrow$|
  14260. (vector |$e'_1 \ldots e'_n$|)
  14261. \end{lstlisting}
  14262. The \code{vector-proxy} primitive translates as follows.
  14263. \begin{lstlisting}
  14264. (vector-proxy |$e_1~e_2~e_3$|)
  14265. |$\Rightarrow$|
  14266. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  14267. \end{lstlisting}
  14268. We translate the vector operations into conditional expressions that
  14269. check whether the value is a proxy and then dispatch to either the
  14270. appropriate proxy vector operation or the regular vector operation.
  14271. For example, the following is the translation for \code{vector-ref}.
  14272. \begin{lstlisting}
  14273. (vector-ref |$e_1$| |$i$|)
  14274. |$\Rightarrow$|
  14275. (let ([|$v~e_1$|])
  14276. (if (proxy? |$v$|)
  14277. (proxy-vector-ref |$v$| |$i$|)
  14278. (vector-ref (project-vector |$v$|) |$i$|)
  14279. \end{lstlisting}
  14280. Note in the case of a real vector, we must apply \code{project-vector}
  14281. before the \code{vector-ref}.
  14282. \section{Reveal Casts}
  14283. \label{sec:reveal-casts-gradual}
  14284. Recall that the \code{reveal-casts} pass
  14285. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  14286. \code{Inject} and \code{Project} into lower-level operations. In
  14287. particular, \code{Project} turns into a conditional expression that
  14288. inspects the tag and retrieves the underlying value. Here we need to
  14289. augment the translation of \code{Project} to handle the situation when
  14290. the target type is \code{PVector}. Instead of using
  14291. \code{vector-length} we need to use \code{proxy-vector-length}.
  14292. \begin{lstlisting}
  14293. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  14294. |$\Rightarrow$|
  14295. (let |$\itm{tmp}$| |$e'$|
  14296. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  14297. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  14298. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  14299. (exit)))
  14300. \end{lstlisting}
  14301. \section{Closure Conversion}
  14302. \label{sec:closure-conversion-gradual}
  14303. The closure conversion pass only requires one minor adjustment. The
  14304. auxiliary function that translates type annotations needs to be
  14305. updated to handle the \code{PVector} type.
  14306. \section{Explicate Control}
  14307. \label{sec:explicate-control-gradual}
  14308. Update the \code{explicate\_control} pass to handle the new primitive
  14309. operations on the \code{PVector} type.
  14310. \section{Select Instructions}
  14311. \label{sec:select-instructions-gradual}
  14312. Recall that the \code{select\_instructions} pass is responsible for
  14313. lowering the primitive operations into x86 instructions. So we need
  14314. to translate the new \code{PVector} operations to x86. To do so, the
  14315. first question we need to answer is how will we differentiate the two
  14316. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  14317. We need just one bit to accomplish this, and use the bit in position
  14318. $57$ of the 64-bit tag at the front of every vector (see
  14319. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  14320. for \code{inject-vector} we leave it that way.
  14321. \begin{lstlisting}
  14322. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  14323. |$\Rightarrow$|
  14324. movq |$e'_1$|, |$\itm{lhs'}$|
  14325. \end{lstlisting}
  14326. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  14327. \begin{lstlisting}
  14328. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  14329. |$\Rightarrow$|
  14330. movq |$e'_1$|, %r11
  14331. movq |$(1 << 57)$|, %rax
  14332. orq 0(%r11), %rax
  14333. movq %rax, 0(%r11)
  14334. movq %r11, |$\itm{lhs'}$|
  14335. \end{lstlisting}
  14336. The \code{proxy?} operation consumes the information so carefully
  14337. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  14338. isolates the $57$th bit to tell whether the value is a real vector or
  14339. a proxy.
  14340. \begin{lstlisting}
  14341. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  14342. |$\Rightarrow$|
  14343. movq |$e_1'$|, %r11
  14344. movq 0(%r11), %rax
  14345. sarq $57, %rax
  14346. andq $1, %rax
  14347. movq %rax, |$\itm{lhs'}$|
  14348. \end{lstlisting}
  14349. The \code{project-vector} operation is straightforward to translate,
  14350. so we leave it up to the reader.
  14351. Regarding the \code{proxy-vector} operations, the runtime provides
  14352. procedures that implement them (they are recursive functions!) so
  14353. here we simply need to translate these vector operations into the
  14354. appropriate function call. For example, here is the translation for
  14355. \code{proxy-vector-ref}.
  14356. \begin{lstlisting}
  14357. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  14358. |$\Rightarrow$|
  14359. movq |$e_1'$|, %rdi
  14360. movq |$e_2'$|, %rsi
  14361. callq proxy_vector_ref
  14362. movq %rax, |$\itm{lhs'}$|
  14363. \end{lstlisting}
  14364. We have another batch of vector operations to deal with, those for the
  14365. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  14366. \code{any-vector-ref} when there is a \code{vector-ref} on something
  14367. of type \code{Any}, and similarly for \code{any-vector-set!} and
  14368. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  14369. Section~\ref{sec:select-Rany} we selected instructions for these
  14370. operations based on the idea that the underlying value was a real
  14371. vector. But in the current setting, the underlying value is of type
  14372. \code{PVector}. So \code{any-vector-ref} can be translates to
  14373. pseudo-x86 as follows. We begin by projecting the underlying value out
  14374. of the tagged value and then call the \code{proxy\_vector\_ref}
  14375. procedure in the runtime.
  14376. \begin{lstlisting}
  14377. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  14378. movq |$\neg 111$|, %rdi
  14379. andq |$e_1'$|, %rdi
  14380. movq |$e_2'$|, %rsi
  14381. callq proxy_vector_ref
  14382. movq %rax, |$\itm{lhs'}$|
  14383. \end{lstlisting}
  14384. The \code{any-vector-set!} and \code{any-vector-length} operators can
  14385. be translated in a similar way.
  14386. \begin{exercise}\normalfont
  14387. Implement a compiler for the gradually-typed \LangGrad{} language by
  14388. extending and adapting your compiler for \LangLoop{}. Create 10 new
  14389. partially-typed test programs. In addition to testing with these
  14390. new programs, also test your compiler on all the tests for \LangLoop{}
  14391. and tests for \LangDyn{}. Sometimes you may get a type checking error
  14392. on the \LangDyn{} programs but you can adapt them by inserting
  14393. a cast to the \code{Any} type around each subexpression
  14394. causing a type error. While \LangDyn{} doesn't have explicit casts,
  14395. you can induce one by wrapping the subexpression \code{e}
  14396. with a call to an un-annotated identity function, like this:
  14397. \code{((lambda (x) x) e)}.
  14398. \end{exercise}
  14399. \begin{figure}[p]
  14400. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14401. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  14402. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  14403. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  14404. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  14405. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  14406. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  14407. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  14408. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  14409. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  14410. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  14411. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  14412. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  14413. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  14414. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  14415. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14416. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14417. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14418. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14419. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14420. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14421. \path[->,bend right=15] (Rgradual) edge [above] node
  14422. {\ttfamily\footnotesize type\_check} (Rgradualp);
  14423. \path[->,bend right=15] (Rgradualp) edge [above] node
  14424. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  14425. \path[->,bend right=15] (Rwhilepp) edge [right] node
  14426. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  14427. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  14428. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  14429. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  14430. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  14431. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  14432. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  14433. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  14434. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  14435. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  14436. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14437. \path[->,bend left=15] (F1-1) edge [below] node
  14438. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14439. \path[->,bend right=15] (F1-2) edge [above] node
  14440. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14441. \path[->,bend right=15] (F1-3) edge [above] node
  14442. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14443. \path[->,bend right=15] (F1-4) edge [above] node
  14444. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14445. \path[->,bend right=15] (F1-5) edge [right] node
  14446. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14447. \path[->,bend left=15] (C3-2) edge [left] node
  14448. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14449. \path[->,bend right=15] (x86-2) edge [left] node
  14450. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14451. \path[->,bend right=15] (x86-2-1) edge [below] node
  14452. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14453. \path[->,bend right=15] (x86-2-2) edge [left] node
  14454. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14455. \path[->,bend left=15] (x86-3) edge [above] node
  14456. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14457. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  14458. \end{tikzpicture}
  14459. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  14460. \label{fig:Rgradual-passes}
  14461. \end{figure}
  14462. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  14463. for the compilation of \LangGrad{}.
  14464. \section{Further Reading}
  14465. This chapter just scratches the surface of gradual typing. The basic
  14466. approach described here is missing two key ingredients that one would
  14467. want in a implementation of gradual typing: blame
  14468. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  14469. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  14470. problem addressed by blame tracking is that when a cast on a
  14471. higher-order value fails, it often does so at a point in the program
  14472. that is far removed from the original cast. Blame tracking is a
  14473. technique for propagating extra information through casts and proxies
  14474. so that when a cast fails, the error message can point back to the
  14475. original location of the cast in the source program.
  14476. The problem addressed by space-efficient casts also relates to
  14477. higher-order casts. It turns out that in partially typed programs, a
  14478. function or vector can flow through very-many casts at runtime. With
  14479. the approach described in this chapter, each cast adds another
  14480. \code{lambda} wrapper or a vector proxy. Not only does this take up
  14481. considerable space, but it also makes the function calls and vector
  14482. operations slow. For example, a partially-typed version of quicksort
  14483. could, in the worst case, build a chain of proxies of length $O(n)$
  14484. around the vector, changing the overall time complexity of the
  14485. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  14486. solution to this problem by representing casts using the coercion
  14487. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  14488. long chains of proxies by compressing them into a concise normal
  14489. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  14490. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  14491. the Grift compiler.
  14492. \begin{center}
  14493. \url{https://github.com/Gradual-Typing/Grift}
  14494. \end{center}
  14495. There are also interesting interactions between gradual typing and
  14496. other language features, such as parametetric polymorphism,
  14497. information-flow types, and type inference, to name a few. We
  14498. recommend the reader to the online gradual typing bibliography:
  14499. \begin{center}
  14500. \url{http://samth.github.io/gradual-typing-bib/}
  14501. \end{center}
  14502. % TODO: challenge problem:
  14503. % type analysis and type specialization?
  14504. % coercions?
  14505. \fi
  14506. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14507. \chapter{Parametric Polymorphism}
  14508. \label{ch:Rpoly}
  14509. \index{subject}{parametric polymorphism}
  14510. \index{subject}{generics}
  14511. \if\edition\racketEd
  14512. This chapter studies the compilation of parametric
  14513. polymorphism\index{subject}{parametric polymorphism}
  14514. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  14515. Racket. Parametric polymorphism enables improved code reuse by
  14516. parameterizing functions and data structures with respect to the types
  14517. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  14518. revisits the \code{map-vec} example but this time gives it a more
  14519. fitting type. This \code{map-vec} function is parameterized with
  14520. respect to the element type of the vector. The type of \code{map-vec}
  14521. is the following polymorphic type as specified by the \code{All} and
  14522. the type parameter \code{a}.
  14523. \begin{lstlisting}
  14524. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14525. \end{lstlisting}
  14526. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  14527. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  14528. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  14529. \code{a}, but we could have just as well applied \code{map-vec} to a
  14530. vector of Booleans (and a function on Booleans).
  14531. \begin{figure}[tbp]
  14532. % poly_test_2.rkt
  14533. \begin{lstlisting}
  14534. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  14535. (define (map-vec f v)
  14536. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14537. (define (add1 [x : Integer]) : Integer (+ x 1))
  14538. (vector-ref (map-vec add1 (vector 0 41)) 1)
  14539. \end{lstlisting}
  14540. \caption{The \code{map-vec} example using parametric polymorphism.}
  14541. \label{fig:map-vec-poly}
  14542. \end{figure}
  14543. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  14544. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  14545. syntax. We add a second form for function definitions in which a type
  14546. declaration comes before the \code{define}. In the abstract syntax,
  14547. the return type in the \code{Def} is \code{Any}, but that should be
  14548. ignored in favor of the return type in the type declaration. (The
  14549. \code{Any} comes from using the same parser as in
  14550. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  14551. enables the use of an \code{All} type for a function, thereby making
  14552. it polymorphic. The grammar for types is extended to include
  14553. polymorphic types and type variables.
  14554. \begin{figure}[tp]
  14555. \centering
  14556. \fbox{
  14557. \begin{minipage}{0.96\textwidth}
  14558. \small
  14559. \[
  14560. \begin{array}{lcl}
  14561. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14562. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  14563. &\MID& \LP\key{:}~\Var~\Type\RP \\
  14564. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  14565. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  14566. \end{array}
  14567. \]
  14568. \end{minipage}
  14569. }
  14570. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  14571. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  14572. \label{fig:Rpoly-concrete-syntax}
  14573. \end{figure}
  14574. \begin{figure}[tp]
  14575. \centering
  14576. \fbox{
  14577. \begin{minipage}{0.96\textwidth}
  14578. \small
  14579. \[
  14580. \begin{array}{lcl}
  14581. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14582. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  14583. &\MID& \DECL{\Var}{\Type} \\
  14584. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  14585. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14586. \end{array}
  14587. \]
  14588. \end{minipage}
  14589. }
  14590. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  14591. (Figure~\ref{fig:Rwhile-syntax}).}
  14592. \label{fig:Rpoly-syntax}
  14593. \end{figure}
  14594. By including polymorphic types in the $\Type$ non-terminal we choose
  14595. to make them first-class which has interesting repercussions on the
  14596. compiler. Many languages with polymorphism, such as
  14597. C++~\citep{stroustrup88:_param_types} and Standard
  14598. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  14599. it is useful to see an example of first-class polymorphism. In
  14600. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  14601. whose parameter is a polymorphic function. The occurrence of a
  14602. polymorphic type underneath a function type is enabled by the normal
  14603. recursive structure of the grammar for $\Type$ and the categorization
  14604. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  14605. applies the polymorphic function to a Boolean and to an integer.
  14606. \begin{figure}[tbp]
  14607. \begin{lstlisting}
  14608. (: apply-twice ((All (b) (b -> b)) -> Integer))
  14609. (define (apply-twice f)
  14610. (if (f #t) (f 42) (f 777)))
  14611. (: id (All (a) (a -> a)))
  14612. (define (id x) x)
  14613. (apply-twice id)
  14614. \end{lstlisting}
  14615. \caption{An example illustrating first-class polymorphism.}
  14616. \label{fig:apply-twice}
  14617. \end{figure}
  14618. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  14619. three new responsibilities (compared to \LangLoop{}). The type checking of
  14620. function application is extended to handle the case where the operator
  14621. expression is a polymorphic function. In that case the type arguments
  14622. are deduced by matching the type of the parameters with the types of
  14623. the arguments.
  14624. %
  14625. The \code{match-types} auxiliary function carries out this deduction
  14626. by recursively descending through a parameter type \code{pt} and the
  14627. corresponding argument type \code{at}, making sure that they are equal
  14628. except when there is a type parameter on the left (in the parameter
  14629. type). If it's the first time that the type parameter has been
  14630. encountered, then the algorithm deduces an association of the type
  14631. parameter to the corresponding type on the right (in the argument
  14632. type). If it's not the first time that the type parameter has been
  14633. encountered, the algorithm looks up its deduced type and makes sure
  14634. that it is equal to the type on the right.
  14635. %
  14636. Once the type arguments are deduced, the operator expression is
  14637. wrapped in an \code{Inst} AST node (for instantiate) that records the
  14638. type of the operator, but more importantly, records the deduced type
  14639. arguments. The return type of the application is the return type of
  14640. the polymorphic function, but with the type parameters replaced by the
  14641. deduced type arguments, using the \code{subst-type} function.
  14642. The second responsibility of the type checker is extending the
  14643. function \code{type-equal?} to handle the \code{All} type. This is
  14644. not quite a simple as equal on other types, such as function and
  14645. vector types, because two polymorphic types can be syntactically
  14646. different even though they are equivalent types. For example,
  14647. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  14648. Two polymorphic types should be considered equal if they differ only
  14649. in the choice of the names of the type parameters. The
  14650. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  14651. renames the type parameters of the first type to match the type
  14652. parameters of the second type.
  14653. The third responsibility of the type checker is making sure that only
  14654. defined type variables appear in type annotations. The
  14655. \code{check-well-formed} function defined in
  14656. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  14657. sure that each type variable has been defined.
  14658. The output language of the type checker is \LangInst{}, defined in
  14659. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  14660. declaration and polymorphic function into a single definition, using
  14661. the \code{Poly} form, to make polymorphic functions more convenient to
  14662. process in next pass of the compiler.
  14663. \begin{figure}[tp]
  14664. \centering
  14665. \fbox{
  14666. \begin{minipage}{0.96\textwidth}
  14667. \small
  14668. \[
  14669. \begin{array}{lcl}
  14670. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14671. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  14672. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  14673. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  14674. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14675. \end{array}
  14676. \]
  14677. \end{minipage}
  14678. }
  14679. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  14680. (Figure~\ref{fig:Rwhile-syntax}).}
  14681. \label{fig:Rpoly-prime-syntax}
  14682. \end{figure}
  14683. The output of the type checker on the polymorphic \code{map-vec}
  14684. example is listed in Figure~\ref{fig:map-vec-type-check}.
  14685. \begin{figure}[tbp]
  14686. % poly_test_2.rkt
  14687. \begin{lstlisting}
  14688. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  14689. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  14690. (define (add1 [x : Integer]) : Integer (+ x 1))
  14691. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14692. (Integer))
  14693. add1 (vector 0 41)) 1)
  14694. \end{lstlisting}
  14695. \caption{Output of the type checker on the \code{map-vec} example.}
  14696. \label{fig:map-vec-type-check}
  14697. \end{figure}
  14698. \begin{figure}[tbp]
  14699. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14700. (define type-check-poly-class
  14701. (class type-check-Rwhile-class
  14702. (super-new)
  14703. (inherit check-type-equal?)
  14704. (define/override (type-check-apply env e1 es)
  14705. (define-values (e^ ty) ((type-check-exp env) e1))
  14706. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  14707. ((type-check-exp env) e)))
  14708. (match ty
  14709. [`(,ty^* ... -> ,rt)
  14710. (for ([arg-ty ty*] [param-ty ty^*])
  14711. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  14712. (values e^ es^ rt)]
  14713. [`(All ,xs (,tys ... -> ,rt))
  14714. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  14715. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  14716. (match-types env^^ param-ty arg-ty)))
  14717. (define targs
  14718. (for/list ([x xs])
  14719. (match (dict-ref env^^ x (lambda () #f))
  14720. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  14721. x (Apply e1 es))]
  14722. [ty ty])))
  14723. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  14724. [else (error 'type-check "expected a function, not ~a" ty)]))
  14725. (define/override ((type-check-exp env) e)
  14726. (match e
  14727. [(Lambda `([,xs : ,Ts] ...) rT body)
  14728. (for ([T Ts]) ((check-well-formed env) T))
  14729. ((check-well-formed env) rT)
  14730. ((super type-check-exp env) e)]
  14731. [(HasType e1 ty)
  14732. ((check-well-formed env) ty)
  14733. ((super type-check-exp env) e)]
  14734. [else ((super type-check-exp env) e)]))
  14735. (define/override ((type-check-def env) d)
  14736. (verbose 'type-check "poly/def" d)
  14737. (match d
  14738. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  14739. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  14740. (for ([p ps]) ((check-well-formed ts-env) p))
  14741. ((check-well-formed ts-env) rt)
  14742. (define new-env (append ts-env (map cons xs ps) env))
  14743. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14744. (check-type-equal? ty^ rt body)
  14745. (Generic ts (Def f p:t* rt info body^))]
  14746. [else ((super type-check-def env) d)]))
  14747. (define/override (type-check-program p)
  14748. (match p
  14749. [(Program info body)
  14750. (type-check-program (ProgramDefsExp info '() body))]
  14751. [(ProgramDefsExp info ds body)
  14752. (define ds^ (combine-decls-defs ds))
  14753. (define new-env (for/list ([d ds^])
  14754. (cons (def-name d) (fun-def-type d))))
  14755. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  14756. (define-values (body^ ty) ((type-check-exp new-env) body))
  14757. (check-type-equal? ty 'Integer body)
  14758. (ProgramDefsExp info ds^^ body^)]))
  14759. ))
  14760. \end{lstlisting}
  14761. \caption{Type checker for the \LangPoly{} language.}
  14762. \label{fig:type-check-Lvar0}
  14763. \end{figure}
  14764. \begin{figure}[tbp]
  14765. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14766. (define/override (type-equal? t1 t2)
  14767. (match* (t1 t2)
  14768. [(`(All ,xs ,T1) `(All ,ys ,T2))
  14769. (define env (map cons xs ys))
  14770. (type-equal? (subst-type env T1) T2)]
  14771. [(other wise)
  14772. (super type-equal? t1 t2)]))
  14773. (define/public (match-types env pt at)
  14774. (match* (pt at)
  14775. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  14776. [('Void 'Void) env] [('Any 'Any) env]
  14777. [(`(Vector ,pts ...) `(Vector ,ats ...))
  14778. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  14779. (match-types env^ pt1 at1))]
  14780. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  14781. (define env^ (match-types env prt art))
  14782. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  14783. (match-types env^^ pt1 at1))]
  14784. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  14785. (define env^ (append (map cons pxs axs) env))
  14786. (match-types env^ pt1 at1)]
  14787. [((? symbol? x) at)
  14788. (match (dict-ref env x (lambda () #f))
  14789. [#f (error 'type-check "undefined type variable ~a" x)]
  14790. ['Type (cons (cons x at) env)]
  14791. [t^ (check-type-equal? at t^ 'matching) env])]
  14792. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  14793. (define/public (subst-type env pt)
  14794. (match pt
  14795. ['Integer 'Integer] ['Boolean 'Boolean]
  14796. ['Void 'Void] ['Any 'Any]
  14797. [`(Vector ,ts ...)
  14798. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  14799. [`(,ts ... -> ,rt)
  14800. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  14801. [`(All ,xs ,t)
  14802. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  14803. [(? symbol? x) (dict-ref env x)]
  14804. [else (error 'type-check "expected a type not ~a" pt)]))
  14805. (define/public (combine-decls-defs ds)
  14806. (match ds
  14807. ['() '()]
  14808. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  14809. (unless (equal? name f)
  14810. (error 'type-check "name mismatch, ~a != ~a" name f))
  14811. (match type
  14812. [`(All ,xs (,ps ... -> ,rt))
  14813. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  14814. (cons (Generic xs (Def name params^ rt info body))
  14815. (combine-decls-defs ds^))]
  14816. [`(,ps ... -> ,rt)
  14817. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  14818. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  14819. [else (error 'type-check "expected a function type, not ~a" type) ])]
  14820. [`(,(Def f params rt info body) . ,ds^)
  14821. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  14822. \end{lstlisting}
  14823. \caption{Auxiliary functions for type checking \LangPoly{}.}
  14824. \label{fig:type-check-Lvar0-aux}
  14825. \end{figure}
  14826. \begin{figure}[tbp]
  14827. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  14828. (define/public ((check-well-formed env) ty)
  14829. (match ty
  14830. ['Integer (void)]
  14831. ['Boolean (void)]
  14832. ['Void (void)]
  14833. [(? symbol? a)
  14834. (match (dict-ref env a (lambda () #f))
  14835. ['Type (void)]
  14836. [else (error 'type-check "undefined type variable ~a" a)])]
  14837. [`(Vector ,ts ...)
  14838. (for ([t ts]) ((check-well-formed env) t))]
  14839. [`(,ts ... -> ,t)
  14840. (for ([t ts]) ((check-well-formed env) t))
  14841. ((check-well-formed env) t)]
  14842. [`(All ,xs ,t)
  14843. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  14844. ((check-well-formed env^) t)]
  14845. [else (error 'type-check "unrecognized type ~a" ty)]))
  14846. \end{lstlisting}
  14847. \caption{Well-formed types.}
  14848. \label{fig:well-formed-types}
  14849. \end{figure}
  14850. % TODO: interpreter for R'_10
  14851. \section{Compiling Polymorphism}
  14852. \label{sec:compiling-poly}
  14853. Broadly speaking, there are four approaches to compiling parametric
  14854. polymorphism, which we describe below.
  14855. \begin{description}
  14856. \item[Monomorphization] generates a different version of a polymorphic
  14857. function for each set of type arguments that it is used with,
  14858. producing type-specialized code. This approach results in the most
  14859. efficient code but requires whole-program compilation (no separate
  14860. compilation) and increases code size. For our current purposes
  14861. monomorphization is a non-starter because, with first-class
  14862. polymorphism, it is sometimes not possible to determine which
  14863. generic functions are used with which type arguments during
  14864. compilation. (It can be done at runtime, with just-in-time
  14865. compilation.) This approach is used to compile C++
  14866. templates~\citep{stroustrup88:_param_types} and polymorphic
  14867. functions in NESL~\citep{Blelloch:1993aa} and
  14868. ML~\citep{Weeks:2006aa}.
  14869. \item[Uniform representation] generates one version of each
  14870. polymorphic function but requires all values have a common ``boxed''
  14871. format, such as the tagged values of type \code{Any} in
  14872. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  14873. similarly to code in a dynamically typed language (like \LangDyn{}),
  14874. in which primitive operators require their arguments to be projected
  14875. from \code{Any} and their results are injected into \code{Any}. (In
  14876. object-oriented languages, the projection is accomplished via
  14877. virtual method dispatch.) The uniform representation approach is
  14878. compatible with separate compilation and with first-class
  14879. polymorphism. However, it produces the least-efficient code because
  14880. it introduces overhead in the entire program, including
  14881. non-polymorphic code. This approach is used in implementations of
  14882. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  14883. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  14884. Java~\citep{Bracha:1998fk}.
  14885. \item[Mixed representation] generates one version of each polymorphic
  14886. function, using a boxed representation for type
  14887. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  14888. and conversions are performed at the boundaries between monomorphic
  14889. and polymorphic (e.g. when a polymorphic function is instantiated
  14890. and called). This approach is compatible with separate compilation
  14891. and first-class polymorphism and maintains the efficiency of
  14892. monomorphic code. The tradeoff is increased overhead at the boundary
  14893. between monomorphic and polymorphic code. This approach is used in
  14894. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  14895. Java 5 with the addition of autoboxing.
  14896. \item[Type passing] uses the unboxed representation in both
  14897. monomorphic and polymorphic code. Each polymorphic function is
  14898. compiled to a single function with extra parameters that describe
  14899. the type arguments. The type information is used by the generated
  14900. code to know how to access the unboxed values at runtime. This
  14901. approach is used in implementation of the Napier88
  14902. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  14903. passing is compatible with separate compilation and first-class
  14904. polymorphism and maintains the efficiency for monomorphic
  14905. code. There is runtime overhead in polymorphic code from dispatching
  14906. on type information.
  14907. \end{description}
  14908. In this chapter we use the mixed representation approach, partly
  14909. because of its favorable attributes, and partly because it is
  14910. straightforward to implement using the tools that we have already
  14911. built to support gradual typing. To compile polymorphic functions, we
  14912. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  14913. \LangCast{}.
  14914. \section{Erase Types}
  14915. \label{sec:erase-types}
  14916. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  14917. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  14918. shows the output of the \code{erase-types} pass on the polymorphic
  14919. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  14920. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  14921. \code{All} types are removed from the type of \code{map-vec}.
  14922. \begin{figure}[tbp]
  14923. \begin{lstlisting}
  14924. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  14925. : (Vector Any Any)
  14926. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14927. (define (add1 [x : Integer]) : Integer (+ x 1))
  14928. (vector-ref ((cast map-vec
  14929. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  14930. ((Integer -> Integer) (Vector Integer Integer)
  14931. -> (Vector Integer Integer)))
  14932. add1 (vector 0 41)) 1)
  14933. \end{lstlisting}
  14934. \caption{The polymorphic \code{map-vec} example after type erasure.}
  14935. \label{fig:map-vec-erase}
  14936. \end{figure}
  14937. This process of type erasure creates a challenge at points of
  14938. instantiation. For example, consider the instantiation of
  14939. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  14940. The type of \code{map-vec} is
  14941. \begin{lstlisting}
  14942. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14943. \end{lstlisting}
  14944. and it is instantiated to
  14945. \begin{lstlisting}
  14946. ((Integer -> Integer) (Vector Integer Integer)
  14947. -> (Vector Integer Integer))
  14948. \end{lstlisting}
  14949. After erasure, the type of \code{map-vec} is
  14950. \begin{lstlisting}
  14951. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  14952. \end{lstlisting}
  14953. but we need to convert it to the instantiated type. This is easy to
  14954. do in the target language \LangCast{} with a single \code{cast}. In
  14955. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  14956. has been compiled to a \code{cast} from the type of \code{map-vec} to
  14957. the instantiated type. The source and target type of a cast must be
  14958. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  14959. because both the source and target are obtained from the same
  14960. polymorphic type of \code{map-vec}, replacing the type parameters with
  14961. \code{Any} in the former and with the deduced type arguments in the
  14962. later. (Recall that the \code{Any} type is consistent with any type.)
  14963. To implement the \code{erase-types} pass, we recommend defining a
  14964. recursive auxiliary function named \code{erase-type} that applies the
  14965. following two transformations. It replaces type variables with
  14966. \code{Any}
  14967. \begin{lstlisting}
  14968. |$x$|
  14969. |$\Rightarrow$|
  14970. Any
  14971. \end{lstlisting}
  14972. and it removes the polymorphic \code{All} types.
  14973. \begin{lstlisting}
  14974. (All |$xs$| |$T_1$|)
  14975. |$\Rightarrow$|
  14976. |$T'_1$|
  14977. \end{lstlisting}
  14978. Apply the \code{erase-type} function to all of the type annotations in
  14979. the program.
  14980. Regarding the translation of expressions, the case for \code{Inst} is
  14981. the interesting one. We translate it into a \code{Cast}, as shown
  14982. below. The type of the subexpression $e$ is the polymorphic type
  14983. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  14984. $T$, the type $T'$. The target type $T''$ is the result of
  14985. substituting the arguments types $ts$ for the type parameters $xs$ in
  14986. $T$ followed by doing type erasure.
  14987. \begin{lstlisting}
  14988. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  14989. |$\Rightarrow$|
  14990. (Cast |$e'$| |$T'$| |$T''$|)
  14991. \end{lstlisting}
  14992. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  14993. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  14994. Finally, each polymorphic function is translated to a regular
  14995. functions in which type erasure has been applied to all the type
  14996. annotations and the body.
  14997. \begin{lstlisting}
  14998. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  14999. |$\Rightarrow$|
  15000. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  15001. \end{lstlisting}
  15002. \begin{exercise}\normalfont
  15003. Implement a compiler for the polymorphic language \LangPoly{} by
  15004. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  15005. programs that use polymorphic functions. Some of them should make
  15006. use of first-class polymorphism.
  15007. \end{exercise}
  15008. \begin{figure}[p]
  15009. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15010. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  15011. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  15012. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  15013. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  15014. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  15015. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  15016. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  15017. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  15018. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  15019. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  15020. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  15021. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  15022. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  15023. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  15024. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  15025. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15026. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15027. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15028. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15029. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15030. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15031. \path[->,bend right=15] (Rpoly) edge [above] node
  15032. {\ttfamily\footnotesize type\_check} (Rpolyp);
  15033. \path[->,bend right=15] (Rpolyp) edge [above] node
  15034. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  15035. \path[->,bend right=15] (Rgradualp) edge [above] node
  15036. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  15037. \path[->,bend right=15] (Rwhilepp) edge [right] node
  15038. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  15039. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  15040. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  15041. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  15042. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  15043. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  15044. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  15045. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  15046. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  15047. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  15048. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15049. \path[->,bend left=15] (F1-1) edge [below] node
  15050. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15051. \path[->,bend right=15] (F1-2) edge [above] node
  15052. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15053. \path[->,bend right=15] (F1-3) edge [above] node
  15054. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15055. \path[->,bend right=15] (F1-4) edge [above] node
  15056. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15057. \path[->,bend right=15] (F1-5) edge [right] node
  15058. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15059. \path[->,bend left=15] (C3-2) edge [left] node
  15060. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15061. \path[->,bend right=15] (x86-2) edge [left] node
  15062. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15063. \path[->,bend right=15] (x86-2-1) edge [below] node
  15064. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15065. \path[->,bend right=15] (x86-2-2) edge [left] node
  15066. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15067. \path[->,bend left=15] (x86-3) edge [above] node
  15068. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15069. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  15070. \end{tikzpicture}
  15071. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  15072. \label{fig:Rpoly-passes}
  15073. \end{figure}
  15074. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  15075. for the compilation of \LangPoly{}.
  15076. % TODO: challenge problem: specialization of instantiations
  15077. % Further Reading
  15078. \fi
  15079. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15080. \clearpage
  15081. \appendix
  15082. \chapter{Appendix}
  15083. \if\edition\racketEd
  15084. \section{Interpreters}
  15085. \label{appendix:interp}
  15086. \index{subject}{interpreter}
  15087. We provide interpreters for each of the source languages \LangInt{},
  15088. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  15089. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  15090. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  15091. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  15092. and x86 are in the \key{interp.rkt} file.
  15093. \section{Utility Functions}
  15094. \label{appendix:utilities}
  15095. The utility functions described in this section are in the
  15096. \key{utilities.rkt} file of the support code.
  15097. \paragraph{\code{interp-tests}}
  15098. The \key{interp-tests} function runs the compiler passes and the
  15099. interpreters on each of the specified tests to check whether each pass
  15100. is correct. The \key{interp-tests} function has the following
  15101. parameters:
  15102. \begin{description}
  15103. \item[name (a string)] a name to identify the compiler,
  15104. \item[typechecker] a function of exactly one argument that either
  15105. raises an error using the \code{error} function when it encounters a
  15106. type error, or returns \code{\#f} when it encounters a type
  15107. error. If there is no type error, the type checker returns the
  15108. program.
  15109. \item[passes] a list with one entry per pass. An entry is a list with
  15110. four things:
  15111. \begin{enumerate}
  15112. \item a string giving the name of the pass,
  15113. \item the function that implements the pass (a translator from AST
  15114. to AST),
  15115. \item a function that implements the interpreter (a function from
  15116. AST to result value) for the output language,
  15117. \item and a type checker for the output language. Type checkers for
  15118. the $R$ and $C$ languages are provided in the support code. For
  15119. example, the type checkers for \LangVar{} and \LangCVar{} are in
  15120. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  15121. type checker entry is optional. The support code does not provide
  15122. type checkers for the x86 languages.
  15123. \end{enumerate}
  15124. \item[source-interp] an interpreter for the source language. The
  15125. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  15126. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  15127. \item[tests] a list of test numbers that specifies which tests to
  15128. run. (see below)
  15129. \end{description}
  15130. %
  15131. The \key{interp-tests} function assumes that the subdirectory
  15132. \key{tests} has a collection of Racket programs whose names all start
  15133. with the family name, followed by an underscore and then the test
  15134. number, ending with the file extension \key{.rkt}. Also, for each test
  15135. program that calls \code{read} one or more times, there is a file with
  15136. the same name except that the file extension is \key{.in} that
  15137. provides the input for the Racket program. If the test program is
  15138. expected to fail type checking, then there should be an empty file of
  15139. the same name but with extension \key{.tyerr}.
  15140. \paragraph{\code{compiler-tests}}
  15141. runs the compiler passes to generate x86 (a \key{.s} file) and then
  15142. runs the GNU C compiler (gcc) to generate machine code. It runs the
  15143. machine code and checks that the output is $42$. The parameters to the
  15144. \code{compiler-tests} function are similar to those of the
  15145. \code{interp-tests} function, and consist of
  15146. \begin{itemize}
  15147. \item a compiler name (a string),
  15148. \item a type checker,
  15149. \item description of the passes,
  15150. \item name of a test-family, and
  15151. \item a list of test numbers.
  15152. \end{itemize}
  15153. \paragraph{\code{compile-file}}
  15154. takes a description of the compiler passes (see the comment for
  15155. \key{interp-tests}) and returns a function that, given a program file
  15156. name (a string ending in \key{.rkt}), applies all of the passes and
  15157. writes the output to a file whose name is the same as the program file
  15158. name but with \key{.rkt} replaced with \key{.s}.
  15159. \paragraph{\code{read-program}}
  15160. takes a file path and parses that file (it must be a Racket program)
  15161. into an abstract syntax tree.
  15162. \paragraph{\code{parse-program}}
  15163. takes an S-expression representation of an abstract syntax tree and converts it into
  15164. the struct-based representation.
  15165. \paragraph{\code{assert}}
  15166. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  15167. and displays the message \key{msg} if the Boolean \key{bool} is false.
  15168. \paragraph{\code{lookup}}
  15169. % remove discussion of lookup? -Jeremy
  15170. takes a key and an alist, and returns the first value that is
  15171. associated with the given key, if there is one. If not, an error is
  15172. triggered. The alist may contain both immutable pairs (built with
  15173. \key{cons}) and mutable pairs (built with \key{mcons}).
  15174. %The \key{map2} function ...
  15175. \fi %\racketEd
  15176. \section{x86 Instruction Set Quick-Reference}
  15177. \label{sec:x86-quick-reference}
  15178. \index{subject}{x86}
  15179. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  15180. do. We write $A \to B$ to mean that the value of $A$ is written into
  15181. location $B$. Address offsets are given in bytes. The instruction
  15182. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  15183. registers (such as \code{\%rax}), or memory references (such as
  15184. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  15185. reference per instruction. Other operands must be immediates or
  15186. registers.
  15187. \begin{table}[tbp]
  15188. \centering
  15189. \begin{tabular}{l|l}
  15190. \textbf{Instruction} & \textbf{Operation} \\ \hline
  15191. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  15192. \texttt{negq} $A$ & $- A \to A$ \\
  15193. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  15194. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  15195. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  15196. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  15197. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  15198. \texttt{retq} & Pops the return address and jumps to it \\
  15199. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  15200. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  15201. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  15202. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  15203. be an immediate) \\
  15204. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  15205. matches the condition code of the instruction, otherwise go to the
  15206. next instructions. The condition codes are \key{e} for ``equal'',
  15207. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  15208. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  15209. \texttt{jl} $L$ & \\
  15210. \texttt{jle} $L$ & \\
  15211. \texttt{jg} $L$ & \\
  15212. \texttt{jge} $L$ & \\
  15213. \texttt{jmp} $L$ & Jump to label $L$ \\
  15214. \texttt{movq} $A$, $B$ & $A \to B$ \\
  15215. \texttt{movzbq} $A$, $B$ &
  15216. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  15217. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  15218. and the extra bytes of $B$ are set to zero.} \\
  15219. & \\
  15220. & \\
  15221. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  15222. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  15223. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  15224. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  15225. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  15226. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  15227. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  15228. description of the condition codes. $A$ must be a single byte register
  15229. (e.g., \texttt{al} or \texttt{cl}).} \\
  15230. \texttt{setl} $A$ & \\
  15231. \texttt{setle} $A$ & \\
  15232. \texttt{setg} $A$ & \\
  15233. \texttt{setge} $A$ &
  15234. \end{tabular}
  15235. \vspace{5pt}
  15236. \caption{Quick-reference for the x86 instructions used in this book.}
  15237. \label{tab:x86-instr}
  15238. \end{table}
  15239. \if\edition\racketEd
  15240. \cleardoublepage
  15241. \section{Concrete Syntax for Intermediate Languages}
  15242. The concrete syntax of \LangAny{} is defined in
  15243. Figure~\ref{fig:Rany-concrete-syntax}.
  15244. \begin{figure}[tp]
  15245. \centering
  15246. \fbox{
  15247. \begin{minipage}{0.97\textwidth}\small
  15248. \[
  15249. \begin{array}{lcl}
  15250. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  15251. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  15252. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  15253. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15254. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15255. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15256. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  15257. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  15258. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  15259. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  15260. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  15261. \MID \LP\key{void?}\;\Exp\RP \\
  15262. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  15263. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  15264. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  15265. \end{array}
  15266. \]
  15267. \end{minipage}
  15268. }
  15269. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  15270. (Figure~\ref{fig:Rlam-syntax}).}
  15271. \label{fig:Rany-concrete-syntax}
  15272. \end{figure}
  15273. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  15274. defined in Figures~\ref{fig:c0-concrete-syntax},
  15275. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  15276. and \ref{fig:c3-concrete-syntax}, respectively.
  15277. \begin{figure}[tbp]
  15278. \fbox{
  15279. \begin{minipage}{0.96\textwidth}
  15280. \[
  15281. \begin{array}{lcl}
  15282. \Atm &::=& \Int \MID \Var \\
  15283. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  15284. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  15285. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  15286. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  15287. \end{array}
  15288. \]
  15289. \end{minipage}
  15290. }
  15291. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  15292. \label{fig:c0-concrete-syntax}
  15293. \end{figure}
  15294. \begin{figure}[tbp]
  15295. \fbox{
  15296. \begin{minipage}{0.96\textwidth}
  15297. \small
  15298. \[
  15299. \begin{array}{lcl}
  15300. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  15301. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  15302. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  15303. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  15304. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  15305. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  15306. \MID \key{goto}~\itm{label}\key{;}\\
  15307. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  15308. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  15309. \end{array}
  15310. \]
  15311. \end{minipage}
  15312. }
  15313. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  15314. \label{fig:c1-concrete-syntax}
  15315. \end{figure}
  15316. \begin{figure}[tbp]
  15317. \fbox{
  15318. \begin{minipage}{0.96\textwidth}
  15319. \small
  15320. \[
  15321. \begin{array}{lcl}
  15322. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  15323. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  15324. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  15325. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  15326. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  15327. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  15328. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  15329. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  15330. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  15331. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  15332. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  15333. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  15334. \end{array}
  15335. \]
  15336. \end{minipage}
  15337. }
  15338. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  15339. \label{fig:c2-concrete-syntax}
  15340. \end{figure}
  15341. \begin{figure}[tp]
  15342. \fbox{
  15343. \begin{minipage}{0.96\textwidth}
  15344. \small
  15345. \[
  15346. \begin{array}{lcl}
  15347. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  15348. \\
  15349. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  15350. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  15351. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  15352. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  15353. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  15354. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  15355. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  15356. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  15357. \MID \LP\key{collect} \,\itm{int}\RP }\\
  15358. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  15359. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  15360. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  15361. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  15362. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  15363. \LangCFunM{} & ::= & \Def\ldots
  15364. \end{array}
  15365. \]
  15366. \end{minipage}
  15367. }
  15368. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  15369. \label{fig:c3-concrete-syntax}
  15370. \end{figure}
  15371. \fi % racketEd
  15372. \backmatter
  15373. \addtocontents{toc}{\vspace{11pt}}
  15374. %% \addtocontents{toc}{\vspace{11pt}}
  15375. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  15376. \nocite{*}\let\bibname\refname
  15377. \addcontentsline{toc}{fmbm}{\refname}
  15378. \printbibliography
  15379. \printindex{authors}{Author Index}
  15380. \printindex{subject}{Subject Index}
  15381. \end{document}
  15382. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  15383. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  15384. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  15385. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  15386. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  15387. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  15388. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  15389. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  15390. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  15391. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  15392. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  15393. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  15394. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  15395. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  15396. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  15397. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  15398. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  15399. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  15400. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  15401. % LocalWords: morekeywords fullflexible