book.tex 629 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299
  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 \\ An Incremental Approach in \python{Python}\racket{Racket}}
  83. \halftitlepage
  84. \Title{Essentials of Compilation}
  85. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  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 of \LangVar{}, we explain
  1590. why we implement it in an object-oriented style. Throughout this book
  1591. we define many interpreters, one for each of language that we
  1592. study. Because each language builds on the prior one, there is a lot
  1593. of commonality between these interpreters. We want to write down the
  1594. common parts just once instead of many times. A naive approach would
  1595. be for the interpreter of \LangVar{} to handle the
  1596. \racket{cases for variables and \code{let}}
  1597. \python{case for variables}
  1598. but dispatch to \LangInt{}
  1599. for the rest of the cases. The following code sketches this idea. (We
  1600. explain the \code{env} parameter soon, in
  1601. Section~\ref{sec:interp-Lvar}.)
  1602. \begin{center}
  1603. {\if\edition\racketEd
  1604. \begin{minipage}{0.45\textwidth}
  1605. \begin{lstlisting}
  1606. (define ((interp_Lint env) e)
  1607. (match e
  1608. [(Prim '- (list e1))
  1609. (fx- 0 ((interp_Lint env) e1))]
  1610. ...))
  1611. \end{lstlisting}
  1612. \end{minipage}
  1613. \begin{minipage}{0.45\textwidth}
  1614. \begin{lstlisting}
  1615. (define ((interp_Lvar env) e)
  1616. (match e
  1617. [(Var x)
  1618. (dict-ref env x)]
  1619. [(Let x e body)
  1620. (define v ((interp_exp env) e))
  1621. (define env^ (dict-set env x v))
  1622. ((interp_exp env^) body)]
  1623. [else ((interp_Lint env) e)]))
  1624. \end{lstlisting}
  1625. \end{minipage}
  1626. \fi}
  1627. {\if\edition\pythonEd
  1628. \begin{minipage}{0.45\textwidth}
  1629. \begin{lstlisting}
  1630. def interp_Lint(e, env):
  1631. match e:
  1632. case UnaryOp(USub(), e1):
  1633. return - interp_Lint(e1, env)
  1634. ...
  1635. \end{lstlisting}
  1636. \end{minipage}
  1637. \begin{minipage}{0.45\textwidth}
  1638. \begin{lstlisting}
  1639. def interp_Lvar(e, env):
  1640. match e:
  1641. case Name(id):
  1642. return env[id]
  1643. case _:
  1644. return interp_Lint(e, env)
  1645. \end{lstlisting}
  1646. \end{minipage}
  1647. \fi}
  1648. \end{center}
  1649. The problem with this approach is that it does not handle situations
  1650. in which an \LangVar{} feature, such as a variable, is nested inside
  1651. an \LangInt{} feature, like the \code{-} operator, as in the following
  1652. program.
  1653. %
  1654. {\if\edition\racketEd
  1655. \begin{lstlisting}
  1656. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1657. \end{lstlisting}
  1658. \fi}
  1659. {\if\edition\pythonEd
  1660. \begin{lstlisting}
  1661. y = 10
  1662. print(-y)
  1663. \end{lstlisting}
  1664. \fi}
  1665. %
  1666. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1667. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1668. then it recursively calls \code{interp\_Lint} again on its argument.
  1669. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1670. 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 \LangInt{} and
  1677. \LangVar{} 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 \LangVar{}
  1687. inherits from the class for \LangInt{} and the method
  1688. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1689. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1690. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1691. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1692. \code{interp\_exp} in \LangInt{}.
  1693. \begin{center}
  1694. \hspace{-20pt}
  1695. {\if\edition\racketEd
  1696. \begin{minipage}{0.45\textwidth}
  1697. \begin{lstlisting}
  1698. (define interp_Lint_class
  1699. (class object%
  1700. (define/public ((interp_exp env) e)
  1701. (match e
  1702. [(Prim '- (list e))
  1703. (fx- 0 ((interp_exp env) e))]
  1704. ...))
  1705. ...))
  1706. \end{lstlisting}
  1707. \end{minipage}
  1708. \begin{minipage}{0.45\textwidth}
  1709. \begin{lstlisting}
  1710. (define interp_Lvar_class
  1711. (class interp_Lint_class
  1712. (define/override ((interp_exp env) e)
  1713. (match e
  1714. [(Var x)
  1715. (dict-ref env x)]
  1716. [(Let x e body)
  1717. (define v ((interp_exp env) e))
  1718. (define env^ (dict-set env x v))
  1719. ((interp_exp env^) body)]
  1720. [else
  1721. (super (interp_exp env) e)]))
  1722. ...
  1723. ))
  1724. \end{lstlisting}
  1725. \end{minipage}
  1726. \fi}
  1727. {\if\edition\pythonEd
  1728. \begin{minipage}{0.45\textwidth}
  1729. \begin{lstlisting}
  1730. class InterpLint:
  1731. def interp_exp(e):
  1732. match e:
  1733. case UnaryOp(USub(), e1):
  1734. return -self.interp_exp(e1)
  1735. ...
  1736. ...
  1737. \end{lstlisting}
  1738. \end{minipage}
  1739. \begin{minipage}{0.45\textwidth}
  1740. \begin{lstlisting}
  1741. def InterpLvar(InterpLint):
  1742. def interp_exp(e):
  1743. match e:
  1744. case Name(id):
  1745. return env[id]
  1746. case _:
  1747. return super().interp_exp(e)
  1748. ...
  1749. \end{lstlisting}
  1750. \end{minipage}
  1751. \fi}
  1752. \end{center}
  1753. Getting back to the troublesome example, repeated here:
  1754. {\if\edition\racketEd
  1755. \begin{lstlisting}
  1756. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1757. \end{lstlisting}
  1758. \fi}
  1759. {\if\edition\pythonEd
  1760. \begin{lstlisting}
  1761. y = 10
  1762. print(-y)
  1763. \end{lstlisting}
  1764. \fi}
  1765. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1766. \racket{on this expression,}
  1767. \python{on the \code{-y} expression,}
  1768. %
  1769. call it \code{e0}, by creating an object of the \LangVar{} class
  1770. and calling the \code{interp\_exp} method.
  1771. {\if\edition\racketEd
  1772. \begin{lstlisting}
  1773. (send (new interp_Lvar_class) interp_exp e0)
  1774. \end{lstlisting}
  1775. \fi}
  1776. {\if\edition\pythonEd
  1777. \begin{lstlisting}
  1778. InterpLvar().interp_exp(e0)
  1779. \end{lstlisting}
  1780. \fi}
  1781. \noindent To process the \code{-} operator, the default case of
  1782. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1783. method in \LangInt{}. But then for the recursive method call, it
  1784. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1785. \code{Var} node is handled correctly. Thus, method overriding gives us
  1786. the open recursion that we need to implement our interpreters in an
  1787. extensible way.
  1788. \subsection{Definitional Interpreter for \LangVar{}}
  1789. \label{sec:interp-Lvar}
  1790. {\if\edition\racketEd
  1791. \begin{figure}[tp]
  1792. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1793. \small
  1794. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1795. An \emph{association list} (alist) is a list of key-value pairs.
  1796. For example, we can map people to their ages with an alist.
  1797. \index{subject}{alist}\index{subject}{association list}
  1798. \begin{lstlisting}[basicstyle=\ttfamily]
  1799. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1800. \end{lstlisting}
  1801. The \emph{dictionary} interface is for mapping keys to values.
  1802. Every alist implements this interface. \index{subject}{dictionary} The package
  1803. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1804. provides many functions for working with dictionaries. Here
  1805. are a few of them:
  1806. \begin{description}
  1807. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1808. returns the value associated with the given $\itm{key}$.
  1809. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1810. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1811. but otherwise is the same as $\itm{dict}$.
  1812. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1813. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1814. of keys and values in $\itm{dict}$. For example, the following
  1815. creates a new alist in which the ages are incremented.
  1816. \end{description}
  1817. \vspace{-10pt}
  1818. \begin{lstlisting}[basicstyle=\ttfamily]
  1819. (for/list ([(k v) (in-dict ages)])
  1820. (cons k (add1 v)))
  1821. \end{lstlisting}
  1822. \end{tcolorbox}
  1823. %\end{wrapfigure}
  1824. \caption{Association lists implement the dictionary interface.}
  1825. \label{fig:alist}
  1826. \end{figure}
  1827. \fi}
  1828. Having justified the use of classes and methods to implement
  1829. interpreters, we revisit the definitional interpreter for \LangInt{}
  1830. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1831. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1832. interpreter for \LangVar{} adds two new \key{match} cases for
  1833. variables and \racket{\key{let}}\python{assignment}. For
  1834. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1835. value bound to a variable to all the uses of the variable. To
  1836. accomplish this, we maintain a mapping from variables to values
  1837. called an \emph{environment}\index{subject}{environment}.
  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. %
  1845. to represent the environment.
  1846. %
  1847. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1848. and the \code{racket/dict} package.}
  1849. %
  1850. The \code{interp\_exp} function takes the current environment,
  1851. \code{env}, as an extra parameter. When the interpreter encounters a
  1852. variable, it looks up the corresponding value in the dictionary.
  1853. %
  1854. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1855. initializing expression, extends the environment with the result
  1856. value bound to the variable, using \code{dict-set}, then evaluates
  1857. the body of the \key{Let}.}
  1858. %
  1859. \python{When the interpreter encounters an assignment, it evaluates
  1860. the initializing expression and then associates the resulting value
  1861. with the variable in the environment.}
  1862. \begin{figure}[tp]
  1863. {\if\edition\racketEd
  1864. \begin{lstlisting}
  1865. (define interp_Lint_class
  1866. (class object%
  1867. (super-new)
  1868. (define/public ((interp_exp env) e)
  1869. (match e
  1870. [(Int n) n]
  1871. [(Prim 'read '())
  1872. (define r (read))
  1873. (cond [(fixnum? r) r]
  1874. [else (error 'interp_exp "expected an integer" r)])]
  1875. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1876. [(Prim '+ (list e1 e2))
  1877. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1878. (define/public (interp_program p)
  1879. (match p
  1880. [(Program '() e) ((interp_exp '()) e)]))
  1881. ))
  1882. \end{lstlisting}
  1883. \fi}
  1884. {\if\edition\pythonEd
  1885. \begin{lstlisting}
  1886. class InterpLint:
  1887. def interp_exp(self, e, env):
  1888. match e:
  1889. case BinOp(left, Add(), right):
  1890. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1891. case UnaryOp(USub(), v):
  1892. return - self.interp_exp(v, env)
  1893. case Constant(value):
  1894. return value
  1895. case Call(Name('input_int'), []):
  1896. return int(input())
  1897. def interp_stmts(self, ss, env):
  1898. if len(ss) == 0:
  1899. return
  1900. match ss[0]:
  1901. case Expr(Call(Name('print'), [arg])):
  1902. print(self.interp_exp(arg, env), end='')
  1903. return self.interp_stmts(ss[1:], env)
  1904. case Expr(value):
  1905. self.interp_exp(value, env)
  1906. return self.interp_stmts(ss[1:], env)
  1907. def interp(self, p):
  1908. match p:
  1909. case Module(body):
  1910. self.interp_stmts(body, {})
  1911. def interp_Lint(p):
  1912. return InterpLint().interp(p)
  1913. \end{lstlisting}
  1914. \fi}
  1915. \caption{Interpreter for \LangInt{} as a class.}
  1916. \label{fig:interp-Lint-class}
  1917. \end{figure}
  1918. \begin{figure}[tp]
  1919. {\if\edition\racketEd
  1920. \begin{lstlisting}
  1921. (define interp_Lvar_class
  1922. (class interp_Lint_class
  1923. (super-new)
  1924. (define/override ((interp_exp env) e)
  1925. (match e
  1926. [(Var x) (dict-ref env x)]
  1927. [(Let x e body)
  1928. (define new-env (dict-set env x ((interp_exp env) e)))
  1929. ((interp_exp new-env) body)]
  1930. [else ((super interp-exp env) e)]))
  1931. ))
  1932. (define (interp_Lvar p)
  1933. (send (new interp_Lvar_class) interp_program p))
  1934. \end{lstlisting}
  1935. \fi}
  1936. {\if\edition\pythonEd
  1937. \begin{lstlisting}
  1938. class InterpLvar(InterpLint):
  1939. def interp_exp(self, e, env):
  1940. match e:
  1941. case Name(id):
  1942. return env[id]
  1943. case _:
  1944. return super().interp_exp(e, env)
  1945. def interp_stmts(self, ss, env):
  1946. if len(ss) == 0:
  1947. return
  1948. match ss[0]:
  1949. case Assign([lhs], value):
  1950. env[lhs.id] = self.interp_exp(value, env)
  1951. return self.interp_stmts(ss[1:], env)
  1952. case _:
  1953. return super().interp_stmts(ss, env)
  1954. def interp_Lvar(p):
  1955. return InterpLvar().interp(p)
  1956. \end{lstlisting}
  1957. \fi}
  1958. \caption{Interpreter for the \LangVar{} language.}
  1959. \label{fig:interp-Lvar}
  1960. \end{figure}
  1961. The goal for this chapter is to implement a compiler that translates
  1962. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1963. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1964. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  1965. That is, they output the same integer $n$. We depict this correctness
  1966. criteria in the following diagram.
  1967. \[
  1968. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1969. \node (p1) at (0, 0) {$P_1$};
  1970. \node (p2) at (4, 0) {$P_2$};
  1971. \node (o) at (4, -2) {$n$};
  1972. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1973. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  1974. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1975. \end{tikzpicture}
  1976. \]
  1977. In the next section we introduce the \LangXInt{} subset of x86 that
  1978. suffices for compiling \LangVar{}.
  1979. \section{The \LangXInt{} Assembly Language}
  1980. \label{sec:x86}
  1981. \index{subject}{x86}
  1982. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1983. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1984. assembler.
  1985. %
  1986. A program begins with a \code{main} label followed by a sequence of
  1987. instructions. The \key{globl} directive says that the \key{main}
  1988. procedure is externally visible, which is necessary so that the
  1989. operating system can call it.
  1990. %
  1991. An x86 program is stored in the computer's memory. For our purposes,
  1992. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1993. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1994. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1995. the address of the next instruction to be executed. For most
  1996. instructions, the program counter is incremented after the instruction
  1997. is executed, so it points to the next instruction in memory. Most x86
  1998. instructions take two operands, where each operand is either an
  1999. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2000. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2001. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2002. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2003. && \key{r8} \MID \key{r9} \MID \key{r10}
  2004. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2005. \MID \key{r14} \MID \key{r15}}
  2006. \begin{figure}[tp]
  2007. \fbox{
  2008. \begin{minipage}{0.96\textwidth}
  2009. {\if\edition\racketEd
  2010. \[
  2011. \begin{array}{lcl}
  2012. \Reg &::=& \allregisters{} \\
  2013. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2014. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2015. \key{subq} \; \Arg\key{,} \Arg \MID
  2016. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2017. && \key{callq} \; \mathit{label} \MID
  2018. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  2019. && \itm{label}\key{:}\; \Instr \\
  2020. \LangXIntM{} &::= & \key{.globl main}\\
  2021. & & \key{main:} \; \Instr\ldots
  2022. \end{array}
  2023. \]
  2024. \fi}
  2025. {\if\edition\pythonEd
  2026. \[
  2027. \begin{array}{lcl}
  2028. \Reg &::=& \allregisters{} \\
  2029. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2030. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2031. \key{subq} \; \Arg\key{,} \Arg \MID
  2032. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2033. && \key{callq} \; \mathit{label} \MID
  2034. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2035. \LangXIntM{} &::= & \key{.globl main}\\
  2036. & & \key{main:} \; \Instr^{*}
  2037. \end{array}
  2038. \]
  2039. \fi}
  2040. \end{minipage}
  2041. }
  2042. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2043. \label{fig:x86-int-concrete}
  2044. \end{figure}
  2045. A register is a special kind of variable that holds a 64-bit
  2046. value. There are 16 general-purpose registers in the computer and
  2047. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2048. is written with a \key{\%} followed by the register name, such as
  2049. \key{\%rax}.
  2050. An immediate value is written using the notation \key{\$}$n$ where $n$
  2051. is an integer.
  2052. %
  2053. %
  2054. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2055. which obtains the address stored in register $r$ and then adds $n$
  2056. bytes to the address. The resulting address is used to load or store
  2057. to memory depending on whether it occurs as a source or destination
  2058. argument of an instruction.
  2059. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2060. source $s$ and destination $d$, applies the arithmetic operation, then
  2061. writes the result back to the destination $d$. \index{subject}{instruction}
  2062. %
  2063. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2064. stores the result in $d$.
  2065. %
  2066. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2067. specified by the label and $\key{retq}$ returns from a procedure to
  2068. its caller.
  2069. %
  2070. We discuss procedure calls in more detail later in this chapter and in
  2071. Chapter~\ref{ch:Rfun}.
  2072. %
  2073. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2074. counter to the address of the instruction after the specified
  2075. label.}
  2076. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2077. all of the x86 instructions used in this book.
  2078. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2079. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2080. \lstinline{movq $10, %rax}
  2081. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2082. adds $32$ to the $10$ in \key{rax} and
  2083. puts the result, $42$, back into \key{rax}.
  2084. %
  2085. The last instruction, \key{retq}, finishes the \key{main} function by
  2086. returning the integer in \key{rax} to the operating system. The
  2087. operating system interprets this integer as the program's exit
  2088. code. By convention, an exit code of 0 indicates that a program
  2089. completed successfully, and all other exit codes indicate various
  2090. errors.
  2091. %
  2092. \racket{Nevertheless, in this book we return the result of the program
  2093. as the exit code.}
  2094. \begin{figure}[tbp]
  2095. \begin{lstlisting}
  2096. .globl main
  2097. main:
  2098. movq $10, %rax
  2099. addq $32, %rax
  2100. retq
  2101. \end{lstlisting}
  2102. \caption{An x86 program that computes
  2103. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2104. \label{fig:p0-x86}
  2105. \end{figure}
  2106. We exhibit the use of memory for storing intermediate results in the
  2107. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2108. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2109. uses a region of memory called the \emph{procedure call stack} (or
  2110. \emph{stack} for
  2111. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2112. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2113. for each procedure call. The memory layout for an individual frame is
  2114. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2115. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2116. item at the top of the stack. The stack grows downward in memory, so
  2117. we increase the size of the stack by subtracting from the stack
  2118. pointer. In the context of a procedure call, the \emph{return
  2119. address}\index{subject}{return address} is the instruction after the
  2120. call instruction on the caller side. The function call instruction,
  2121. \code{callq}, pushes the return address onto the stack prior to
  2122. jumping to the procedure. The register \key{rbp} is the \emph{base
  2123. pointer}\index{subject}{base pointer} and is used to access variables
  2124. that are stored in the frame of the current procedure call. The base
  2125. pointer of the caller is store after the return address. In
  2126. Figure~\ref{fig:frame} we number the variables from $1$ to
  2127. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2128. at $-16\key{(\%rbp)}$, etc.
  2129. \begin{figure}[tbp]
  2130. {\if\edition\racketEd
  2131. \begin{lstlisting}
  2132. start:
  2133. movq $10, -8(%rbp)
  2134. negq -8(%rbp)
  2135. movq -8(%rbp), %rax
  2136. addq $52, %rax
  2137. jmp conclusion
  2138. .globl main
  2139. main:
  2140. pushq %rbp
  2141. movq %rsp, %rbp
  2142. subq $16, %rsp
  2143. jmp start
  2144. conclusion:
  2145. addq $16, %rsp
  2146. popq %rbp
  2147. retq
  2148. \end{lstlisting}
  2149. \fi}
  2150. {\if\edition\pythonEd
  2151. \begin{lstlisting}
  2152. .globl main
  2153. main:
  2154. pushq %rbp
  2155. movq %rsp, %rbp
  2156. subq $16, %rsp
  2157. movq $10, -8(%rbp)
  2158. negq -8(%rbp)
  2159. movq -8(%rbp), %rax
  2160. addq $52, %rax
  2161. addq $16, %rsp
  2162. popq %rbp
  2163. retq
  2164. \end{lstlisting}
  2165. \fi}
  2166. \caption{An x86 program that computes
  2167. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2168. \label{fig:p1-x86}
  2169. \end{figure}
  2170. \begin{figure}[tbp]
  2171. \centering
  2172. \begin{tabular}{|r|l|} \hline
  2173. Position & Contents \\ \hline
  2174. 8(\key{\%rbp}) & return address \\
  2175. 0(\key{\%rbp}) & old \key{rbp} \\
  2176. -8(\key{\%rbp}) & variable $1$ \\
  2177. -16(\key{\%rbp}) & variable $2$ \\
  2178. \ldots & \ldots \\
  2179. 0(\key{\%rsp}) & variable $n$\\ \hline
  2180. \end{tabular}
  2181. \caption{Memory layout of a frame.}
  2182. \label{fig:frame}
  2183. \end{figure}
  2184. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2185. control is transferred from the operating system to the \code{main}
  2186. function. The operating system issues a \code{callq main} instruction
  2187. which pushes its return address on the stack and then jumps to
  2188. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2189. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2190. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2191. alignment (because the \code{callq} pushed the return address). The
  2192. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2193. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2194. pointer for the caller onto the stack and subtracts $8$ from the stack
  2195. pointer. The next instruction \code{movq \%rsp, \%rbp} sets the
  2196. base pointer to the current stack pointer, which is pointing at the location
  2197. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2198. pointer down to make enough room for storing variables. This program
  2199. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2200. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2201. functions.
  2202. \racket{The last instruction of the prelude is \code{jmp start},
  2203. which transfers control to the instructions that were generated from
  2204. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2205. \racket{The first instruction under the \code{start} label is}
  2206. %
  2207. \python{The first instruction after the prelude is}
  2208. %
  2209. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2210. %
  2211. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2212. %
  2213. The next instruction moves the $-10$ from variable $1$ into the
  2214. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2215. the value in \code{rax}, updating its contents to $42$.
  2216. \racket{The three instructions under the label \code{conclusion} are the
  2217. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2218. %
  2219. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2220. \code{main} function consists of the last three instructions.}
  2221. %
  2222. The first two restore the \code{rsp} and \code{rbp} registers to the
  2223. state they were in at the beginning of the procedure. In particular,
  2224. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2225. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2226. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2227. \key{retq}, jumps back to the procedure that called this one and adds
  2228. $8$ to the stack pointer.
  2229. Our compiler needs a convenient representation for manipulating x86
  2230. programs, so we define an abstract syntax for x86 in
  2231. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2232. \LangXInt{}.
  2233. %
  2234. {\if\edition\racketEd
  2235. The main difference compared to the concrete syntax of \LangXInt{}
  2236. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2237. front of every instruction. Instead instructions are grouped into
  2238. \emph{blocks}\index{subject}{block} with a
  2239. label associated with every block, which is why the \key{X86Program}
  2240. struct includes an alist mapping labels to blocks. The reason for this
  2241. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2242. introduce conditional branching. The \code{Block} structure includes
  2243. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2244. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2245. $\itm{info}$ field should contain an empty list.
  2246. \fi}
  2247. %
  2248. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2249. node includes an integer for representing the arity of the function,
  2250. i.e., the number of arguments, which is helpful to know during
  2251. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2252. \begin{figure}[tp]
  2253. \fbox{
  2254. \begin{minipage}{0.98\textwidth}
  2255. \small
  2256. {\if\edition\racketEd
  2257. \[
  2258. \begin{array}{lcl}
  2259. \Reg &::=& \allregisters{} \\
  2260. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2261. \MID \DEREF{\Reg}{\Int} \\
  2262. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2263. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2264. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2265. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2266. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2267. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2268. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2269. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2270. \end{array}
  2271. \]
  2272. \fi}
  2273. {\if\edition\pythonEd
  2274. \[
  2275. \begin{array}{lcl}
  2276. \Reg &::=& \allregisters{} \\
  2277. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2278. \MID \DEREF{\Reg}{\Int} \\
  2279. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2280. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2281. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2282. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2283. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2284. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2285. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2286. \end{array}
  2287. \]
  2288. \fi}
  2289. \end{minipage}
  2290. }
  2291. \caption{The abstract syntax of \LangXInt{} assembly.}
  2292. \label{fig:x86-int-ast}
  2293. \end{figure}
  2294. \section{Planning the trip to x86}
  2295. \label{sec:plan-s0-x86}
  2296. To compile one language to another it helps to focus on the
  2297. differences between the two languages because the compiler will need
  2298. to bridge those differences. What are the differences between \LangVar{}
  2299. and x86 assembly? Here are some of the most important ones:
  2300. \begin{enumerate}
  2301. \item x86 arithmetic instructions typically have two arguments
  2302. and update the second argument in place. In contrast, \LangVar{}
  2303. arithmetic operations take two arguments and produce a new value.
  2304. An x86 instruction may have at most one memory-accessing argument.
  2305. Furthermore, some instructions place special restrictions on their
  2306. arguments.
  2307. \item An argument of an \LangVar{} operator can be a deeply-nested
  2308. expression, whereas x86 instructions restrict their arguments to be
  2309. integer constants, registers, and memory locations.
  2310. {\if\edition\racketEd
  2311. \item The order of execution in x86 is explicit in the syntax: a
  2312. sequence of instructions and jumps to labeled positions, whereas in
  2313. \LangVar{} the order of evaluation is a left-to-right depth-first
  2314. traversal of the abstract syntax tree.
  2315. \fi}
  2316. \item A program in \LangVar{} can have any number of variables
  2317. whereas x86 has 16 registers and the procedure call stack.
  2318. {\if\edition\racketEd
  2319. \item Variables in \LangVar{} can shadow other variables with the
  2320. same name. In x86, registers have unique names and memory locations
  2321. have unique addresses.
  2322. \fi}
  2323. \end{enumerate}
  2324. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2325. the problem into several steps, dealing with the above differences one
  2326. at a time. Each of these steps is called a \emph{pass} of the
  2327. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2328. %
  2329. This terminology comes from the way each step passes over the AST of
  2330. the program.
  2331. %
  2332. We begin by sketching how we might implement each pass, and give them
  2333. names. We then figure out an ordering of the passes and the
  2334. input/output language for each pass. The very first pass has
  2335. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2336. its output language. In between we can choose whichever language is
  2337. most convenient for expressing the output of each pass, whether that
  2338. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2339. our own design. Finally, to implement each pass we write one
  2340. recursive function per non-terminal in the grammar of the input
  2341. language of the pass. \index{subject}{intermediate language}
  2342. \begin{description}
  2343. {\if\edition\racketEd
  2344. \item[\key{uniquify}] deals with the shadowing of variables by
  2345. renaming every variable to a unique name.
  2346. \fi}
  2347. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2348. of a primitive operation or function call is a variable or integer,
  2349. that is, an \emph{atomic} expression. We refer to non-atomic
  2350. expressions as \emph{complex}. This pass introduces temporary
  2351. variables to hold the results of complex
  2352. subexpressions.\index{subject}{atomic
  2353. expression}\index{subject}{complex expression}%
  2354. {\if\edition\racketEd
  2355. \item[\key{explicate\_control}] makes the execution order of the
  2356. program explicit. It convert the abstract syntax tree representation
  2357. into a control-flow graph in which each node contains a sequence of
  2358. statements and the edges between nodes say which nodes contain jumps
  2359. to other nodes.
  2360. \fi}
  2361. \item[\key{select\_instructions}] handles the difference between
  2362. \LangVar{} operations and x86 instructions. This pass converts each
  2363. \LangVar{} operation to a short sequence of instructions that
  2364. accomplishes the same task.
  2365. \item[\key{assign\_homes}] replaces the variables in \LangVar{} with
  2366. registers or stack locations in x86.
  2367. \end{description}
  2368. The next question is: in what order should we apply these passes? This
  2369. question can be challenging because it is difficult to know ahead of
  2370. time which orderings will be better (easier to implement, produce more
  2371. efficient code, etc.) so oftentimes trial-and-error is
  2372. involved. Nevertheless, we can try to plan ahead and make educated
  2373. choices regarding the ordering.
  2374. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2375. \key{uniquify}? The \key{uniquify} pass should come first because
  2376. \key{explicate\_control} changes all the \key{let}-bound variables to
  2377. become local variables whose scope is the entire program, which would
  2378. confuse variables with the same name.}
  2379. %
  2380. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2381. because the later removes the \key{let} form, but it is convenient to
  2382. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2383. %
  2384. \racket{The ordering of \key{uniquify} with respect to
  2385. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2386. \key{uniquify} to come first.}
  2387. The \key{select\_instructions} and \key{assign\_homes} passes are
  2388. intertwined.
  2389. %
  2390. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers are used for
  2391. passing arguments to functions and it is preferable to assign
  2392. parameters to their corresponding registers. This suggests that it
  2393. would be better to start with the \key{select\_instructions} pass,
  2394. which generates the instructions for argument passing, before
  2395. performing register allocation.
  2396. %
  2397. On the other hand, by selecting instructions first we may run into a
  2398. dead end in \key{assign\_homes}. Recall that only one argument of an
  2399. x86 instruction may be a memory access but \key{assign\_homes} might
  2400. be forced to assign both arguments to memory locations.
  2401. %
  2402. A sophisticated approach is to iteratively repeat the two passes until
  2403. a solution is found. However, to reduce implementation complexity we
  2404. recommend a simpler approach in which \key{select\_instructions} comes
  2405. first, followed by the \key{assign\_homes}, then a third pass named
  2406. \key{patch\_instructions} that uses a reserved register to fix
  2407. outstanding problems.
  2408. \begin{figure}[tbp]
  2409. {\if\edition\racketEd
  2410. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2411. \node (Lvar) at (0,2) {\large \LangVar{}};
  2412. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2413. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2414. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2415. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2416. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2417. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2418. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2419. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2420. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2421. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2422. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2423. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2424. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2425. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2426. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2427. \end{tikzpicture}
  2428. \fi}
  2429. {\if\edition\pythonEd
  2430. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2431. \node (Lvar) at (0,2) {\large \LangVar{}};
  2432. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2433. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2434. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2435. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2436. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2437. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2438. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2439. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2440. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2441. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2442. \end{tikzpicture}
  2443. \fi}
  2444. \caption{Diagram of the passes for compiling \LangVar{}. }
  2445. \label{fig:Lvar-passes}
  2446. \end{figure}
  2447. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2448. passes and identifies the input and output language of each pass.
  2449. %
  2450. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2451. language, which extends \LangXInt{} with an unbounded number of
  2452. program-scope variables and removes the restrictions regarding
  2453. instruction arguments.
  2454. %
  2455. The last pass, \key{prelude\_and\_conclusion}, places the program
  2456. instructions inside a \code{main} function with instructions for the
  2457. prelude and conclusion.
  2458. %
  2459. \racket{In the following section we discuss the \LangCVar{}
  2460. intermediate language.}
  2461. %
  2462. The remainder of this chapter provides guidance on the implementation
  2463. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2464. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2465. %% are programs that are still in the \LangVar{} language, though the
  2466. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2467. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2468. %% %
  2469. %% The output of \code{explicate\_control} is in an intermediate language
  2470. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2471. %% syntax, which we introduce in the next section. The
  2472. %% \key{select-instruction} pass translates from \LangCVar{} to
  2473. %% \LangXVar{}. The \key{assign-homes} and
  2474. %% \key{patch-instructions}
  2475. %% passes input and output variants of x86 assembly.
  2476. {\if\edition\racketEd
  2477. \subsection{The \LangCVar{} Intermediate Language}
  2478. The output of \code{explicate\_control} is similar to the $C$
  2479. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2480. categories for expressions and statements, so we name it \LangCVar{}.
  2481. The concrete syntax for \LangCVar{} is defined in
  2482. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2483. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2484. %
  2485. The \LangCVar{} language supports the same operators as \LangVar{} but
  2486. the arguments of operators are restricted to atomic
  2487. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2488. assignment statements which can be executed in sequence using the
  2489. \key{Seq} form. A sequence of statements always ends with
  2490. \key{Return}, a guarantee that is baked into the grammar rules for
  2491. \itm{tail}. The naming of this non-terminal comes from the term
  2492. \emph{tail position}\index{subject}{tail position}, which refers to an
  2493. expression that is the last one to execute within a function.
  2494. A \LangCVar{} program consists of an alist mapping labels to
  2495. tails. This is more general than necessary for the present chapter, as
  2496. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2497. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2498. there will be just one label, \key{start}, and the whole program is
  2499. its tail.
  2500. %
  2501. The $\itm{info}$ field of the \key{CProgram} form, after the
  2502. \code{explicate\_control} pass, contains a mapping from the symbol
  2503. \key{locals} to a list of variables, that is, a list of all the
  2504. variables used in the program. At the start of the program, these
  2505. variables are uninitialized; they become initialized on their first
  2506. assignment.
  2507. \begin{figure}[tbp]
  2508. \fbox{
  2509. \begin{minipage}{0.96\textwidth}
  2510. \[
  2511. \begin{array}{lcl}
  2512. \Atm &::=& \Int \MID \Var \\
  2513. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  2514. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  2515. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  2516. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2517. \end{array}
  2518. \]
  2519. \end{minipage}
  2520. }
  2521. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2522. \label{fig:c0-concrete-syntax}
  2523. \end{figure}
  2524. \begin{figure}[tbp]
  2525. \fbox{
  2526. \begin{minipage}{0.96\textwidth}
  2527. \[
  2528. \begin{array}{lcl}
  2529. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2530. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2531. &\MID& \ADD{\Atm}{\Atm}\\
  2532. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2533. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2534. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2535. \end{array}
  2536. \]
  2537. \end{minipage}
  2538. }
  2539. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2540. \label{fig:c0-syntax}
  2541. \end{figure}
  2542. The definitional interpreter for \LangCVar{} is in the support code,
  2543. in the file \code{interp-Cvar.rkt}.
  2544. \fi}
  2545. {\if\edition\racketEd
  2546. \section{Uniquify Variables}
  2547. \label{sec:uniquify-Lvar}
  2548. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2549. programs in which every \key{let} binds a unique variable name. For
  2550. example, the \code{uniquify} pass should translate the program on the
  2551. left into the program on the right.
  2552. \begin{transformation}
  2553. \begin{lstlisting}
  2554. (let ([x 32])
  2555. (+ (let ([x 10]) x) x))
  2556. \end{lstlisting}
  2557. \compilesto
  2558. \begin{lstlisting}
  2559. (let ([x.1 32])
  2560. (+ (let ([x.2 10]) x.2) x.1))
  2561. \end{lstlisting}
  2562. \end{transformation}
  2563. The following is another example translation, this time of a program
  2564. with a \key{let} nested inside the initializing expression of another
  2565. \key{let}.
  2566. \begin{transformation}
  2567. \begin{lstlisting}
  2568. (let ([x (let ([x 4])
  2569. (+ x 1))])
  2570. (+ x 2))
  2571. \end{lstlisting}
  2572. \compilesto
  2573. \begin{lstlisting}
  2574. (let ([x.2 (let ([x.1 4])
  2575. (+ x.1 1))])
  2576. (+ x.2 2))
  2577. \end{lstlisting}
  2578. \end{transformation}
  2579. We recommend implementing \code{uniquify} by creating a structurally
  2580. recursive function named \code{uniquify-exp} that mostly just copies
  2581. an expression. However, when encountering a \key{let}, it should
  2582. generate a unique name for the variable and associate the old name
  2583. with the new name in an alist.\footnote{The Racket function
  2584. \code{gensym} is handy for generating unique variable names.} The
  2585. \code{uniquify-exp} function needs to access this alist when it gets
  2586. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2587. for the alist.
  2588. The skeleton of the \code{uniquify-exp} function is shown in
  2589. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2590. convenient to partially apply it to an alist and then apply it to
  2591. different expressions, as in the last case for primitive operations in
  2592. Figure~\ref{fig:uniquify-Lvar}. The
  2593. %
  2594. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2595. %
  2596. form of Racket is useful for transforming each element of a list to
  2597. produce a new list.\index{subject}{for/list}
  2598. \begin{figure}[tbp]
  2599. \begin{lstlisting}
  2600. (define (uniquify-exp env)
  2601. (lambda (e)
  2602. (match e
  2603. [(Var x) ___]
  2604. [(Int n) (Int n)]
  2605. [(Let x e body) ___]
  2606. [(Prim op es)
  2607. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2608. (define (uniquify p)
  2609. (match p
  2610. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2611. \end{lstlisting}
  2612. \caption{Skeleton for the \key{uniquify} pass.}
  2613. \label{fig:uniquify-Lvar}
  2614. \end{figure}
  2615. \begin{exercise}
  2616. \normalfont % I don't like the italics for exercises. -Jeremy
  2617. Complete the \code{uniquify} pass by filling in the blanks in
  2618. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2619. variables and for the \key{let} form in the file \code{compiler.rkt}
  2620. in the support code.
  2621. \end{exercise}
  2622. \begin{exercise}
  2623. \normalfont % I don't like the italics for exercises. -Jeremy
  2624. \label{ex:Lvar}
  2625. Create five \LangVar{} programs that exercise the most interesting
  2626. parts of the \key{uniquify} pass, that is, the programs should include
  2627. \key{let} forms, variables, and variables that shadow each other.
  2628. The five programs should be placed in the subdirectory named
  2629. \key{tests} and the file names should start with \code{var\_test\_}
  2630. followed by a unique integer and end with the file extension
  2631. \key{.rkt}.
  2632. %
  2633. The \key{run-tests.rkt} script in the support code checks whether the
  2634. output programs produce the same result as the input programs. The
  2635. script uses the \key{interp-tests} function
  2636. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2637. your \key{uniquify} pass on the example programs. The \code{passes}
  2638. parameter of \key{interp-tests} is a list that should have one entry
  2639. for each pass in your compiler. For now, define \code{passes} to
  2640. contain just one entry for \code{uniquify} as shown below.
  2641. \begin{lstlisting}
  2642. (define passes
  2643. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2644. \end{lstlisting}
  2645. Run the \key{run-tests.rkt} script in the support code to check
  2646. whether the output programs produce the same result as the input
  2647. programs.
  2648. \end{exercise}
  2649. \fi}
  2650. \section{Remove Complex Operands}
  2651. \label{sec:remove-complex-opera-Lvar}
  2652. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2653. into a restricted form in which the arguments of operations are atomic
  2654. expressions. Put another way, this pass removes complex
  2655. operands\index{subject}{complex operand}, such as the expression
  2656. \racket{\code{(- 10)}}\python{\code{-10}}
  2657. in the program below. This is accomplished by introducing a new
  2658. temporary variable, assigning the complex operand to the new
  2659. variable, and then using the new variable in place of the complex
  2660. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2661. right.
  2662. {\if\edition\racketEd
  2663. \begin{transformation}
  2664. % var_test_19.rkt
  2665. \begin{lstlisting}
  2666. (let ([x (+ 42 (- 10))])
  2667. (+ x 10))
  2668. \end{lstlisting}
  2669. \compilesto
  2670. \begin{lstlisting}
  2671. (let ([x (let ([tmp.1 (- 10)])
  2672. (+ 42 tmp.1))])
  2673. (+ x 10))
  2674. \end{lstlisting}
  2675. \end{transformation}
  2676. \fi}
  2677. {\if\edition\pythonEd
  2678. \begin{transformation}
  2679. \begin{lstlisting}
  2680. x = 42 + -10
  2681. print(x + 10)
  2682. \end{lstlisting}
  2683. \compilesto
  2684. \begin{lstlisting}
  2685. tmp_0 = -10
  2686. x = 42 + tmp_0
  2687. tmp_1 = x + 10
  2688. print(tmp_1)
  2689. \end{lstlisting}
  2690. \end{transformation}
  2691. \fi}
  2692. \begin{figure}[tp]
  2693. \centering
  2694. \fbox{
  2695. \begin{minipage}{0.96\textwidth}
  2696. {\if\edition\racketEd
  2697. \[
  2698. \begin{array}{rcl}
  2699. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2700. \Exp &::=& \Atm \MID \READ{} \\
  2701. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2702. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2703. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2704. \end{array}
  2705. \]
  2706. \fi}
  2707. {\if\edition\pythonEd
  2708. \[
  2709. \begin{array}{rcl}
  2710. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2711. \Exp{} &::=& \Atm \MID \READ{} \\
  2712. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2713. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2714. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2715. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2716. \end{array}
  2717. \]
  2718. \fi}
  2719. \end{minipage}
  2720. }
  2721. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2722. atomic expressions.}
  2723. \label{fig:Lvar-anf-syntax}
  2724. \end{figure}
  2725. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output of
  2726. this pass, the language \LangVarANF{}. The only difference is that
  2727. operator arguments are restricted to be atomic expressions that are
  2728. defined by the \Atm{} non-terminal. In particular, integer constants
  2729. and variables are atomic. In the literature, restricting arguments to
  2730. be atomic expressions is one of the ideas in \emph{administrative
  2731. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2732. \index{subject}{administrative normal form} \index{subject}{ANF}
  2733. {\if\edition\racketEd
  2734. We recommend implementing this pass with two mutually recursive
  2735. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2736. \code{rco\_atom} to subexpressions that need to become atomic and to
  2737. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2738. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2739. returns an expression. The \code{rco\_atom} function returns two
  2740. things: an atomic expression and an alist mapping temporary variables to
  2741. complex subexpressions. You can return multiple things from a function
  2742. using Racket's \key{values} form and you can receive multiple things
  2743. from a function call using the \key{define-values} form.
  2744. Also, the
  2745. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2746. form is useful for applying a function to each element of a list, in
  2747. the case where the function returns multiple values.
  2748. \index{subject}{for/lists}
  2749. \fi}
  2750. %
  2751. {\if\edition\pythonEd
  2752. %
  2753. We recommend implementing this pass with an auxiliary method named
  2754. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2755. Boolean that specifies whether the expression needs to become atomic
  2756. or not. The \code{rco\_exp} method should return a pair consisting of
  2757. the new expression and a list of pairs, associating new temporary
  2758. variables with their initializing expressions.
  2759. %
  2760. \fi}
  2761. {\if\edition\racketEd
  2762. Returning to the example program with the expression \code{(+ 42 (-
  2763. 10))}, the subexpression \code{(- 10)} should be processed using the
  2764. \code{rco\_atom} function because it is an argument of the \code{+} and
  2765. therefore needs to become atomic. The output of \code{rco\_atom}
  2766. applied to \code{(- 10)} is as follows.
  2767. \begin{transformation}
  2768. \begin{lstlisting}
  2769. (- 10)
  2770. \end{lstlisting}
  2771. \compilesto
  2772. \begin{lstlisting}
  2773. tmp.1
  2774. ((tmp.1 . (- 10)))
  2775. \end{lstlisting}
  2776. \end{transformation}
  2777. \fi}
  2778. %
  2779. {\if\edition\pythonEd
  2780. %
  2781. Returning to the example program with the expression \code{42 + -10},
  2782. the subexpression \code{-10} should be processed using the
  2783. \code{rco\_exp} function with \code{True} as the second argument
  2784. because \code{-10} is an argument of the \code{+} operator and
  2785. therefore needs to become atomic. The output of \code{rco\_exp}
  2786. applied to \code{-10} is as follows.
  2787. \begin{transformation}
  2788. \begin{lstlisting}
  2789. -10
  2790. \end{lstlisting}
  2791. \compilesto
  2792. \begin{lstlisting}
  2793. tmp_1
  2794. [(tmp_1, -10)]
  2795. \end{lstlisting}
  2796. \end{transformation}
  2797. %
  2798. \fi}
  2799. Take special care of programs such as the following that
  2800. %
  2801. \racket{bind a variable to an atomic expression}
  2802. %
  2803. \python{assign an atomic expression to a variable}.
  2804. %
  2805. You should leave such \racket{variable bindings}\python{assignments}
  2806. unchanged, as shown in the program on the right\\
  2807. %
  2808. {\if\edition\racketEd
  2809. \begin{transformation}
  2810. % var_test_20.rkt
  2811. \begin{lstlisting}
  2812. (let ([a 42])
  2813. (let ([b a])
  2814. b))
  2815. \end{lstlisting}
  2816. \compilesto
  2817. \begin{lstlisting}
  2818. (let ([a 42])
  2819. (let ([b a])
  2820. b))
  2821. \end{lstlisting}
  2822. \end{transformation}
  2823. \fi}
  2824. {\if\edition\pythonEd
  2825. \begin{transformation}
  2826. \begin{lstlisting}
  2827. a = 42
  2828. b = a
  2829. print(b)
  2830. \end{lstlisting}
  2831. \compilesto
  2832. \begin{lstlisting}
  2833. a = 42
  2834. b = a
  2835. print(b)
  2836. \end{lstlisting}
  2837. \end{transformation}
  2838. \fi}
  2839. %
  2840. \noindent A careless implementation might produce the following output with
  2841. unnecessary temporary variables.
  2842. \begin{center}
  2843. \begin{minipage}{0.4\textwidth}
  2844. {\if\edition\racketEd
  2845. \begin{lstlisting}
  2846. (let ([tmp.1 42])
  2847. (let ([a tmp.1])
  2848. (let ([tmp.2 a])
  2849. (let ([b tmp.2])
  2850. b))))
  2851. \end{lstlisting}
  2852. \fi}
  2853. {\if\edition\pythonEd
  2854. \begin{lstlisting}
  2855. tmp_1 = 42
  2856. a = tmp_1
  2857. tmp_2 = a
  2858. b = tmp_2
  2859. print(b)
  2860. \end{lstlisting}
  2861. \fi}
  2862. \end{minipage}
  2863. \end{center}
  2864. \begin{exercise}
  2865. \normalfont
  2866. {\if\edition\racketEd
  2867. Implement the \code{remove\_complex\_operands} function in
  2868. \code{compiler.rkt}.
  2869. %
  2870. Create three new \LangVar{} programs that exercise the interesting
  2871. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2872. regarding file names described in Exercise~\ref{ex:Lvar}.
  2873. %
  2874. In the \code{run-tests.rkt} script, add the following entry to the
  2875. list of \code{passes} and then run the script to test your compiler.
  2876. \begin{lstlisting}
  2877. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  2878. \end{lstlisting}
  2879. While debugging your compiler, it is often useful to see the
  2880. intermediate programs that are output from each pass. To print the
  2881. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2882. \code{interp-tests} in \code{run-tests.rkt}.
  2883. \fi}
  2884. %
  2885. {\if\edition\pythonEd
  2886. Implement the \code{remove\_complex\_operands} pass in
  2887. \code{compiler.py}, creating auxiliary functions for each
  2888. non-terminal in the grammar, i.e., \code{rco\_exp}
  2889. and \code{rco\_stmt}.
  2890. \fi}
  2891. \end{exercise}
  2892. {\if\edition\pythonEd
  2893. \begin{exercise}
  2894. \normalfont % I don't like the italics for exercises. -Jeremy
  2895. \label{ex:Lvar}
  2896. Create five \LangVar{} programs that exercise the most interesting
  2897. parts of the \code{remove\_complex\_operands} pass. The five programs
  2898. should be placed in the subdirectory named \key{tests} and the file
  2899. names should start with \code{var\_test\_} followed by a unique
  2900. integer and end with the file extension \key{.py}.
  2901. %% The \key{run-tests.rkt} script in the support code checks whether the
  2902. %% output programs produce the same result as the input programs. The
  2903. %% script uses the \key{interp-tests} function
  2904. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2905. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2906. %% parameter of \key{interp-tests} is a list that should have one entry
  2907. %% for each pass in your compiler. For now, define \code{passes} to
  2908. %% contain just one entry for \code{uniquify} as shown below.
  2909. %% \begin{lstlisting}
  2910. %% (define passes
  2911. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2912. %% \end{lstlisting}
  2913. Run the \key{run-tests.py} script in the support code to check
  2914. whether the output programs produce the same result as the input
  2915. programs.
  2916. \end{exercise}
  2917. \fi}
  2918. {\if\edition\racketEd
  2919. \section{Explicate Control}
  2920. \label{sec:explicate-control-Lvar}
  2921. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  2922. programs that make the order of execution explicit in their
  2923. syntax. For now this amounts to flattening \key{let} constructs into a
  2924. sequence of assignment statements. For example, consider the following
  2925. \LangVar{} program.\\
  2926. % var_test_11.rkt
  2927. \begin{minipage}{0.96\textwidth}
  2928. \begin{lstlisting}
  2929. (let ([y (let ([x 20])
  2930. (+ x (let ([x 22]) x)))])
  2931. y)
  2932. \end{lstlisting}
  2933. \end{minipage}\\
  2934. %
  2935. The output of the previous pass and of \code{explicate\_control} is
  2936. shown below. Recall that the right-hand-side of a \key{let} executes
  2937. before its body, so the order of evaluation for this program is to
  2938. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2939. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2940. output of \code{explicate\_control} makes this ordering explicit.
  2941. \begin{transformation}
  2942. \begin{lstlisting}
  2943. (let ([y (let ([x.1 20])
  2944. (let ([x.2 22])
  2945. (+ x.1 x.2)))])
  2946. y)
  2947. \end{lstlisting}
  2948. \compilesto
  2949. \begin{lstlisting}[language=C]
  2950. start:
  2951. x.1 = 20;
  2952. x.2 = 22;
  2953. y = (+ x.1 x.2);
  2954. return y;
  2955. \end{lstlisting}
  2956. \end{transformation}
  2957. \begin{figure}[tbp]
  2958. \begin{lstlisting}
  2959. (define (explicate_tail e)
  2960. (match e
  2961. [(Var x) ___]
  2962. [(Int n) (Return (Int n))]
  2963. [(Let x rhs body) ___]
  2964. [(Prim op es) ___]
  2965. [else (error "explicate_tail unhandled case" e)]))
  2966. (define (explicate_assign e x cont)
  2967. (match e
  2968. [(Var x) ___]
  2969. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2970. [(Let y rhs body) ___]
  2971. [(Prim op es) ___]
  2972. [else (error "explicate_assign unhandled case" e)]))
  2973. (define (explicate_control p)
  2974. (match p
  2975. [(Program info body) ___]))
  2976. \end{lstlisting}
  2977. \caption{Skeleton for the \code{explicate\_control} pass.}
  2978. \label{fig:explicate-control-Lvar}
  2979. \end{figure}
  2980. The organization of this pass depends on the notion of tail position
  2981. that we have alluded to earlier.
  2982. \begin{definition}
  2983. The following rules define when an expression is in \textbf{\emph{tail
  2984. position}}\index{subject}{tail position} for the language \LangVar{}.
  2985. \begin{enumerate}
  2986. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2987. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2988. \end{enumerate}
  2989. \end{definition}
  2990. We recommend implementing \code{explicate\_control} using two mutually
  2991. recursive functions, \code{explicate\_tail} and
  2992. \code{explicate\_assign}, as suggested in the skeleton code in
  2993. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  2994. function should be applied to expressions in tail position whereas the
  2995. \code{explicate\_assign} should be applied to expressions that occur on
  2996. the right-hand-side of a \key{let}.
  2997. %
  2998. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  2999. input and produces a \Tail{} in \LangCVar{} (see
  3000. Figure~\ref{fig:c0-syntax}).
  3001. %
  3002. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3003. the variable that it is to be assigned to, and a \Tail{} in
  3004. \LangCVar{} for the code that comes after the assignment. The
  3005. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3006. The \code{explicate\_assign} function is in accumulator-passing style:
  3007. the \code{cont} parameter is used for accumulating the output. This
  3008. accumulator-passing style plays an important role in how we generate
  3009. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3010. \begin{exercise}\normalfont
  3011. %
  3012. Implement the \code{explicate\_control} function in
  3013. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3014. exercise the code in \code{explicate\_control}.
  3015. %
  3016. In the \code{run-tests.rkt} script, add the following entry to the
  3017. list of \code{passes} and then run the script to test your compiler.
  3018. \begin{lstlisting}
  3019. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3020. \end{lstlisting}
  3021. \end{exercise}
  3022. \fi}
  3023. \section{Select Instructions}
  3024. \label{sec:select-Lvar}
  3025. \index{subject}{instruction selection}
  3026. In the \code{select\_instructions} pass we begin the work of
  3027. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3028. language of this pass is a variant of x86 that still uses variables,
  3029. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3030. non-terminal of the \LangXInt{} abstract syntax
  3031. (Figure~\ref{fig:x86-int-ast}).
  3032. \racket{We recommend implementing the
  3033. \code{select\_instructions} with three auxiliary functions, one for
  3034. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3035. $\Tail$.}
  3036. \python{We recommend implementing an auxiliary function
  3037. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3038. \racket{
  3039. The cases for $\Atm$ are straightforward; variables stay
  3040. the same and integer constants change to immediates:
  3041. $\INT{n}$ changes to $\IMM{n}$.}
  3042. We consider the cases for the $\Stmt$ non-terminal, starting with
  3043. arithmetic operations. For example, consider the addition operation
  3044. below, on the left side. There is an \key{addq} instruction in x86,
  3045. but it performs an in-place update. So we could move $\Arg_1$
  3046. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3047. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3048. $\Atm_1$ and $\Atm_2$ respectively.
  3049. \begin{transformation}
  3050. {\if\edition\racketEd
  3051. \begin{lstlisting}
  3052. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3053. \end{lstlisting}
  3054. \fi}
  3055. {\if\edition\pythonEd
  3056. \begin{lstlisting}
  3057. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3058. \end{lstlisting}
  3059. \fi}
  3060. \compilesto
  3061. \begin{lstlisting}
  3062. movq |$\Arg_1$|, |$\itm{var}$|
  3063. addq |$\Arg_2$|, |$\itm{var}$|
  3064. \end{lstlisting}
  3065. \end{transformation}
  3066. There are also cases that require special care to avoid generating
  3067. needlessly complicated code. For example, if one of the arguments of
  3068. the addition is the same variable as the left-hand side of the
  3069. assignment, as shown below, then there is no need for the extra move
  3070. instruction. The assignment statement can be translated into a single
  3071. \key{addq} instruction as follows.
  3072. \begin{transformation}
  3073. {\if\edition\racketEd
  3074. \begin{lstlisting}
  3075. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3076. \end{lstlisting}
  3077. \fi}
  3078. {\if\edition\pythonEd
  3079. \begin{lstlisting}
  3080. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3081. \end{lstlisting}
  3082. \fi}
  3083. \compilesto
  3084. \begin{lstlisting}
  3085. addq |$\Arg_1$|, |$\itm{var}$|
  3086. \end{lstlisting}
  3087. \end{transformation}
  3088. The \READOP{} operation does not have a direct counterpart in x86
  3089. assembly, so we provide this functionality with the function
  3090. \code{read\_int} in the file \code{runtime.c}, written in
  3091. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3092. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3093. system}, or simply the \emph{runtime} for short. When compiling your
  3094. generated x86 assembly code, you need to compile \code{runtime.c} to
  3095. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3096. \code{-c}) and link it into the executable. For our purposes of code
  3097. generation, all you need to do is translate an assignment of
  3098. \READOP{} into a call to the \code{read\_int} function followed by a
  3099. move from \code{rax} to the left-hand-side variable. (Recall that the
  3100. return value of a function goes into \code{rax}.)
  3101. \begin{transformation}
  3102. {\if\edition\racketEd
  3103. \begin{lstlisting}
  3104. |$\itm{var}$| = (read);
  3105. \end{lstlisting}
  3106. \fi}
  3107. {\if\edition\pythonEd
  3108. \begin{lstlisting}
  3109. |$\itm{var}$| = input_int();
  3110. \end{lstlisting}
  3111. \fi}
  3112. \compilesto
  3113. \begin{lstlisting}
  3114. callq read_int
  3115. movq %rax, |$\itm{var}$|
  3116. \end{lstlisting}
  3117. \end{transformation}
  3118. {\if\edition\pythonEd
  3119. %
  3120. Similarly, we translate the \code{print} operation, shown below, into
  3121. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3122. In x86, the first six arguments to functions are passed in registers,
  3123. with the first argument passed in register \code{rdi}. So we move the
  3124. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3125. \code{callq} instruction.
  3126. \begin{transformation}
  3127. \begin{lstlisting}
  3128. print(|$\Atm$|)
  3129. \end{lstlisting}
  3130. \compilesto
  3131. \begin{lstlisting}
  3132. movq |$\Arg$|, %rdi
  3133. callq print_int
  3134. \end{lstlisting}
  3135. \end{transformation}
  3136. %
  3137. \fi}
  3138. {\if\edition\racketEd
  3139. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3140. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3141. assignment to the \key{rax} register followed by a jump to the
  3142. conclusion of the program (so the conclusion needs to be labeled).
  3143. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3144. recursively and then append the resulting instructions.
  3145. \fi}
  3146. \begin{exercise}
  3147. \normalfont
  3148. {\if\edition\racketEd
  3149. Implement the \code{select\_instructions} pass in
  3150. \code{compiler.rkt}. Create three new example programs that are
  3151. designed to exercise all of the interesting cases in this pass.
  3152. %
  3153. In the \code{run-tests.rkt} script, add the following entry to the
  3154. list of \code{passes} and then run the script to test your compiler.
  3155. \begin{lstlisting}
  3156. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3157. \end{lstlisting}
  3158. \fi}
  3159. {\if\edition\pythonEd
  3160. Implement the \key{select\_instructions} pass in
  3161. \code{compiler.py}. Create three new example programs that are
  3162. designed to exercise all of the interesting cases in this pass.
  3163. Run the \code{run-tests.py} script to to check
  3164. whether the output programs produce the same result as the input
  3165. programs.
  3166. \fi}
  3167. \end{exercise}
  3168. \section{Assign Homes}
  3169. \label{sec:assign-Lvar}
  3170. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3171. \LangXVar{} programs that no longer use program variables.
  3172. Thus, the \key{assign-homes} pass is responsible for placing all of
  3173. the program variables in registers or on the stack. For runtime
  3174. efficiency, it is better to place variables in registers, but as there
  3175. are only 16 registers, some programs must necessarily resort to
  3176. placing some variables on the stack. In this chapter we focus on the
  3177. mechanics of placing variables on the stack. We study an algorithm for
  3178. placing variables in registers in
  3179. Chapter~\ref{ch:register-allocation-Lvar}.
  3180. Consider again the following \LangVar{} program from
  3181. Section~\ref{sec:remove-complex-opera-Lvar}.
  3182. % var_test_20.rkt
  3183. {\if\edition\racketEd
  3184. \begin{lstlisting}
  3185. (let ([a 42])
  3186. (let ([b a])
  3187. b))
  3188. \end{lstlisting}
  3189. \fi}
  3190. {\if\edition\pythonEd
  3191. \begin{lstlisting}
  3192. a = 42
  3193. b = a
  3194. print(b)
  3195. \end{lstlisting}
  3196. \fi}
  3197. %
  3198. The output of \code{select\_instructions} is shown below, on the left,
  3199. and the output of \code{assign\_homes} is on the right. In this
  3200. example, we assign variable \code{a} to stack location
  3201. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3202. \begin{transformation}
  3203. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3204. movq $42, a
  3205. movq a, b
  3206. movq b, %rax
  3207. \end{lstlisting}
  3208. \compilesto
  3209. %stack-space: 16
  3210. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3211. movq $42, -8(%rbp)
  3212. movq -8(%rbp), -16(%rbp)
  3213. movq -16(%rbp), %rax
  3214. \end{lstlisting}
  3215. \end{transformation}
  3216. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3217. \code{X86Program} node is an alist mapping all the variables in the
  3218. program to their types (for now just \code{Integer}). The
  3219. \code{assign\_homes} pass should replace all uses of those variables
  3220. with stack locations. As an aside, the \code{locals-types} entry is
  3221. computed by \code{type-check-Cvar} in the support code, which
  3222. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3223. which should be propagated to the \code{X86Program} node.}
  3224. %
  3225. \python{The \code{assign\_homes} pass should replace all uses of
  3226. variables with stack locations.}
  3227. %
  3228. In the process of assigning variables to stack locations, it is
  3229. convenient for you to compute and store the size of the frame (in
  3230. bytes) in%
  3231. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3232. %
  3233. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3234. which is needed later to generate the conclusion of the \code{main}
  3235. procedure. The x86-64 standard requires the frame size to be a
  3236. multiple of 16 bytes.\index{subject}{frame}
  3237. % TODO: store the number of variables instead? -Jeremy
  3238. \begin{exercise}\normalfont
  3239. Implement the \key{assign\_homes} pass in
  3240. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3241. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3242. grammar. We recommend that the auxiliary functions take an extra
  3243. parameter that maps variable names to homes (stack locations for now).
  3244. %
  3245. {\if\edition\racketEd
  3246. In the \code{run-tests.rkt} script, add the following entry to the
  3247. list of \code{passes} and then run the script to test your compiler.
  3248. \begin{lstlisting}
  3249. (list "assign homes" assign-homes interp_x86-0)
  3250. \end{lstlisting}
  3251. \fi}
  3252. {\if\edition\pythonEd
  3253. Run the \code{run-tests.py} script to to check
  3254. whether the output programs produce the same result as the input
  3255. programs.
  3256. \fi}
  3257. \end{exercise}
  3258. \section{Patch Instructions}
  3259. \label{sec:patch-s0}
  3260. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3261. \LangXInt{} by making sure that each instruction adheres to the
  3262. restriction that at most one argument of an instruction may be a
  3263. memory reference.
  3264. We return to the following example.\\
  3265. \begin{minipage}{0.5\textwidth}
  3266. % var_test_20.rkt
  3267. {\if\edition\racketEd
  3268. \begin{lstlisting}
  3269. (let ([a 42])
  3270. (let ([b a])
  3271. b))
  3272. \end{lstlisting}
  3273. \fi}
  3274. {\if\edition\pythonEd
  3275. \begin{lstlisting}
  3276. a = 42
  3277. b = a
  3278. print(b)
  3279. \end{lstlisting}
  3280. \fi}
  3281. \end{minipage}\\
  3282. The \key{assign\_homes} pass produces the following translation. \\
  3283. \begin{minipage}{0.5\textwidth}
  3284. {\if\edition\racketEd
  3285. \begin{lstlisting}
  3286. movq $42, -8(%rbp)
  3287. movq -8(%rbp), -16(%rbp)
  3288. movq -16(%rbp), %rax
  3289. \end{lstlisting}
  3290. \fi}
  3291. {\if\edition\pythonEd
  3292. \begin{lstlisting}
  3293. movq 42, -8(%rbp)
  3294. movq -8(%rbp), -16(%rbp)
  3295. movq -16(%rbp), %rdi
  3296. callq print_int
  3297. \end{lstlisting}
  3298. \fi}
  3299. \end{minipage}\\
  3300. The second \key{movq} instruction is problematic because both
  3301. arguments are stack locations. We suggest fixing this problem by
  3302. moving from the source location to the register \key{rax} and then
  3303. from \key{rax} to the destination location, as follows.
  3304. \begin{lstlisting}
  3305. movq -8(%rbp), %rax
  3306. movq %rax, -16(%rbp)
  3307. \end{lstlisting}
  3308. \begin{exercise}
  3309. \normalfont Implement the \key{patch\_instructions} pass in
  3310. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3311. Create three new example programs that are
  3312. designed to exercise all of the interesting cases in this pass.
  3313. %
  3314. {\if\edition\racketEd
  3315. In the \code{run-tests.rkt} script, add the following entry to the
  3316. list of \code{passes} and then run the script to test your compiler.
  3317. \begin{lstlisting}
  3318. (list "patch instructions" patch_instructions interp_x86-0)
  3319. \end{lstlisting}
  3320. \fi}
  3321. {\if\edition\pythonEd
  3322. Run the \code{run-tests.py} script to to check
  3323. whether the output programs produce the same result as the input
  3324. programs.
  3325. \fi}
  3326. \end{exercise}
  3327. \section{Generate Prelude and Conclusion}
  3328. \label{sec:print-x86}
  3329. \index{subject}{prelude}\index{subject}{conclusion}
  3330. The last step of the compiler from \LangVar{} to x86 is to generate
  3331. the \code{main} function with a prelude and conclusion wrapped around
  3332. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3333. discussed in Section~\ref{sec:x86}.
  3334. When running on Mac OS X, your compiler should prefix an underscore to
  3335. all labels, e.g., changing \key{main} to \key{\_main}.
  3336. %
  3337. \racket{The Racket call \code{(system-type 'os)} is useful for
  3338. determining which operating system the compiler is running on. It
  3339. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3340. %
  3341. \python{The Python \code{platform} library includes a \code{system()}
  3342. function that returns \code{'Linux'}, \code{'Windows'}, or
  3343. \code{'Darwin'} (for Mac).}
  3344. \begin{exercise}\normalfont
  3345. %
  3346. Implement the \key{prelude\_and\_conclusion} pass in
  3347. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3348. %
  3349. {\if\edition\racketEd
  3350. In the \code{run-tests.rkt} script, add the following entry to the
  3351. list of \code{passes} and then run the script to test your compiler.
  3352. \begin{lstlisting}
  3353. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3354. \end{lstlisting}
  3355. %
  3356. Uncomment the call to the \key{compiler-tests} function
  3357. (Appendix~\ref{appendix:utilities}), which tests your complete
  3358. compiler by executing the generated x86 code. It translates the x86
  3359. AST that you produce into a string by invoking the \code{print-x86}
  3360. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3361. the provided \key{runtime.c} file to \key{runtime.o} using
  3362. \key{gcc}. Run the script to test your compiler.
  3363. %
  3364. \fi}
  3365. {\if\edition\pythonEd
  3366. %
  3367. Run the \code{run-tests.py} script to to check whether the output
  3368. programs produce the same result as the input programs. That script
  3369. translates the x86 AST that you produce into a string by invoking the
  3370. \code{repr} method that is implemented by the x86 AST classes in
  3371. \code{x86\_ast.py}.
  3372. %
  3373. \fi}
  3374. \end{exercise}
  3375. \section{Challenge: Partial Evaluator for \LangVar{}}
  3376. \label{sec:pe-Lvar}
  3377. \index{subject}{partial evaluation}
  3378. This section describes two optional challenge exercises that involve
  3379. adapting and improving the partial evaluator for \LangInt{} that was
  3380. introduced in Section~\ref{sec:partial-evaluation}.
  3381. \begin{exercise}\label{ex:pe-Lvar}
  3382. \normalfont
  3383. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3384. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3385. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3386. %
  3387. \racket{\key{let} binding}\python{assignment}
  3388. %
  3389. to the \LangInt{} language, so you will need to add cases for them in
  3390. the \code{pe\_exp}
  3391. %
  3392. \racket{function}
  3393. %
  3394. \python{and \code{pe\_stmt} functions}.
  3395. %
  3396. Once complete, add the partial evaluation pass to the front of your
  3397. compiler and make sure that your compiler still passes all of the
  3398. tests.
  3399. \end{exercise}
  3400. \begin{exercise}
  3401. \normalfont
  3402. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3403. \code{pe\_add} auxiliary functions with functions that know more about
  3404. arithmetic. For example, your partial evaluator should translate
  3405. {\if\edition\racketEd
  3406. \[
  3407. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3408. \code{(+ 2 (read))}
  3409. \]
  3410. \fi}
  3411. {\if\edition\pythonEd
  3412. \[
  3413. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3414. \code{2 + input\_int()}
  3415. \]
  3416. \fi}
  3417. To accomplish this, the \code{pe\_exp} function should produce output
  3418. in the form of the $\itm{residual}$ non-terminal of the following
  3419. grammar. The idea is that when processing an addition expression, we
  3420. can always produce either 1) an integer constant, 2) an addition
  3421. expression with an integer constant on the left-hand side but not the
  3422. right-hand side, or 3) or an addition expression in which neither
  3423. subexpression is a constant.
  3424. {\if\edition\racketEd
  3425. \[
  3426. \begin{array}{lcl}
  3427. \itm{inert} &::=& \Var
  3428. \MID \LP\key{read}\RP
  3429. \MID \LP\key{-} ~\Var\RP
  3430. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3431. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3432. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3433. \itm{residual} &::=& \Int
  3434. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3435. \MID \itm{inert}
  3436. \end{array}
  3437. \]
  3438. \fi}
  3439. {\if\edition\pythonEd
  3440. \[
  3441. \begin{array}{lcl}
  3442. \itm{inert} &::=& \Var
  3443. \MID \key{input\_int}\LP\RP
  3444. \MID \key{-} \Var
  3445. \MID \key{-} \key{input\_int}\LP\RP
  3446. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3447. \itm{residual} &::=& \Int
  3448. \MID \Int ~ \key{+} ~ \itm{inert}
  3449. \MID \itm{inert}
  3450. \end{array}
  3451. \]
  3452. \fi}
  3453. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3454. inputs are $\itm{residual}$ expressions and they should return
  3455. $\itm{residual}$ expressions. Once the improvements are complete,
  3456. make sure that your compiler still passes all of the tests. After
  3457. all, fast code is useless if it produces incorrect results!
  3458. \end{exercise}
  3459. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3460. \chapter{Register Allocation}
  3461. \label{ch:register-allocation-Lvar}
  3462. \index{subject}{register allocation}
  3463. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3464. stack. In this chapter we learn how to improve the performance of the
  3465. generated code by assigning some variables to registers. The CPU can
  3466. access a register in a single cycle, whereas accessing the stack can
  3467. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3468. serves as a running example. The source program is on the left and the
  3469. output of instruction selection is on the right. The program is almost
  3470. in the x86 assembly language but it still uses variables.
  3471. \begin{figure}
  3472. \begin{minipage}{0.45\textwidth}
  3473. Example \LangVar{} program:
  3474. % var_test_28.rkt
  3475. {\if\edition\racketEd
  3476. \begin{lstlisting}
  3477. (let ([v 1])
  3478. (let ([w 42])
  3479. (let ([x (+ v 7)])
  3480. (let ([y x])
  3481. (let ([z (+ x w)])
  3482. (+ z (- y)))))))
  3483. \end{lstlisting}
  3484. \fi}
  3485. {\if\edition\pythonEd
  3486. \begin{lstlisting}
  3487. v = 1
  3488. w = 42
  3489. x = v + 7
  3490. y = x
  3491. z = x + w
  3492. print(z + (- y))
  3493. \end{lstlisting}
  3494. \fi}
  3495. \end{minipage}
  3496. \begin{minipage}{0.45\textwidth}
  3497. After instruction selection:
  3498. {\if\edition\racketEd
  3499. \begin{lstlisting}
  3500. locals-types:
  3501. x : Integer, y : Integer,
  3502. z : Integer, t : Integer,
  3503. v : Integer, w : Integer
  3504. start:
  3505. movq $1, v
  3506. movq $42, w
  3507. movq v, x
  3508. addq $7, x
  3509. movq x, y
  3510. movq x, z
  3511. addq w, z
  3512. movq y, t
  3513. negq t
  3514. movq z, %rax
  3515. addq t, %rax
  3516. jmp conclusion
  3517. \end{lstlisting}
  3518. \fi}
  3519. {\if\edition\pythonEd
  3520. \begin{lstlisting}
  3521. movq $1, v
  3522. movq $42, w
  3523. movq v, x
  3524. addq $7, x
  3525. movq x, y
  3526. movq x, z
  3527. addq w, z
  3528. movq y, tmp_0
  3529. negq tmp_0
  3530. movq z, tmp_1
  3531. addq tmp_0, tmp_1
  3532. movq tmp_1, %rdi
  3533. callq print_int
  3534. \end{lstlisting}
  3535. \fi}
  3536. \end{minipage}
  3537. \caption{A running example for register allocation.}
  3538. \label{fig:reg-eg}
  3539. \end{figure}
  3540. The goal of register allocation is to fit as many variables into
  3541. registers as possible. Some programs have more variables than
  3542. registers so we cannot always map each variable to a different
  3543. register. Fortunately, it is common for different variables to be
  3544. needed during different periods of time during program execution, and
  3545. in such cases several variables can be mapped to the same register.
  3546. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3547. After the variable \code{x} is moved to \code{z} it is no longer
  3548. needed. Variable \code{z}, on the other hand, is used only after this
  3549. point, so \code{x} and \code{z} could share the same register. The
  3550. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3551. where a variable is needed. Once we have that information, we compute
  3552. which variables are needed at the same time, i.e., which ones
  3553. \emph{interfere} with each other, and represent this relation as an
  3554. undirected graph whose vertices are variables and edges indicate when
  3555. two variables interfere (Section~\ref{sec:build-interference}). We
  3556. then model register allocation as a graph coloring problem
  3557. (Section~\ref{sec:graph-coloring}).
  3558. If we run out of registers despite these efforts, we place the
  3559. remaining variables on the stack, similar to what we did in
  3560. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3561. assigning a variable to a stack location. The decision to spill a
  3562. variable is handled as part of the graph coloring process.
  3563. We make the simplifying assumption that each variable is assigned to
  3564. one location (a register or stack address). A more sophisticated
  3565. approach is to assign a variable to one or more locations in different
  3566. regions of the program. For example, if a variable is used many times
  3567. in short sequence and then only used again after many other
  3568. instructions, it could be more efficient to assign the variable to a
  3569. register during the initial sequence and then move it to the stack for
  3570. the rest of its lifetime. We refer the interested reader to
  3571. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3572. approach.
  3573. % discuss prioritizing variables based on how much they are used.
  3574. \section{Registers and Calling Conventions}
  3575. \label{sec:calling-conventions}
  3576. \index{subject}{calling conventions}
  3577. As we perform register allocation, we need to be aware of the
  3578. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3579. functions calls are performed in x86.
  3580. %
  3581. Even though \LangVar{} does not include programmer-defined functions,
  3582. our generated code includes a \code{main} function that is called by
  3583. the operating system and our generated code contains calls to the
  3584. \code{read\_int} function.
  3585. Function calls require coordination between two pieces of code that
  3586. may be written by different programmers or generated by different
  3587. compilers. Here we follow the System V calling conventions that are
  3588. used by the GNU C compiler on Linux and
  3589. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3590. %
  3591. The calling conventions include rules about how functions share the
  3592. use of registers. In particular, the caller is responsible for freeing
  3593. up some registers prior to the function call for use by the callee.
  3594. These are called the \emph{caller-saved registers}
  3595. \index{subject}{caller-saved registers}
  3596. and they are
  3597. \begin{lstlisting}
  3598. rax rcx rdx rsi rdi r8 r9 r10 r11
  3599. \end{lstlisting}
  3600. On the other hand, the callee is responsible for preserving the values
  3601. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3602. which are
  3603. \begin{lstlisting}
  3604. rsp rbp rbx r12 r13 r14 r15
  3605. \end{lstlisting}
  3606. We can think about this caller/callee convention from two points of
  3607. view, the caller view and the callee view:
  3608. \begin{itemize}
  3609. \item The caller should assume that all the caller-saved registers get
  3610. overwritten with arbitrary values by the callee. On the other hand,
  3611. the caller can safely assume that all the callee-saved registers
  3612. contain the same values after the call that they did before the
  3613. call.
  3614. \item The callee can freely use any of the caller-saved registers.
  3615. However, if the callee wants to use a callee-saved register, the
  3616. callee must arrange to put the original value back in the register
  3617. prior to returning to the caller. This can be accomplished by saving
  3618. the value to the stack in the prelude of the function and restoring
  3619. the value in the conclusion of the function.
  3620. \end{itemize}
  3621. In x86, registers are also used for passing arguments to a function
  3622. and for the return value. In particular, the first six arguments to a
  3623. function are passed in the following six registers, in this order.
  3624. \begin{lstlisting}
  3625. rdi rsi rdx rcx r8 r9
  3626. \end{lstlisting}
  3627. If there are more than six arguments, then the convention is to use
  3628. space on the frame of the caller for the rest of the
  3629. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3630. need more than six arguments.
  3631. %
  3632. \racket{For now, the only function we care about is \code{read\_int}
  3633. and it takes zero arguments.}
  3634. %
  3635. \python{For now, the only functions we care about are \code{read\_int}
  3636. and \code{print\_int}, which take zero and one argument, respectively.}
  3637. %
  3638. The register \code{rax} is used for the return value of a function.
  3639. The next question is how these calling conventions impact register
  3640. allocation. Consider the \LangVar{} program in
  3641. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3642. example from the caller point of view and then from the callee point
  3643. of view.
  3644. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3645. is in use during the second call to \READOP{}, so we need to make sure
  3646. that the value in \code{x} does not get accidentally wiped out by the
  3647. call to \READOP{}. One obvious approach is to save all the values in
  3648. caller-saved registers to the stack prior to each function call, and
  3649. restore them after each call. That way, if the register allocator
  3650. chooses to assign \code{x} to a caller-saved register, its value will
  3651. be preserved across the call to \READOP{}. However, saving and
  3652. restoring to the stack is relatively slow. If \code{x} is not used
  3653. many times, it may be better to assign \code{x} to a stack location in
  3654. the first place. Or better yet, if we can arrange for \code{x} to be
  3655. placed in a callee-saved register, then it won't need to be saved and
  3656. restored during function calls.
  3657. The approach that we recommend for variables that are in use during a
  3658. function call is to either assign them to callee-saved registers or to
  3659. spill them to the stack. On the other hand, for variables that are not
  3660. in use during a function call, we try the following alternatives in
  3661. order 1) look for an available caller-saved register (to leave room
  3662. for other variables in the callee-saved register), 2) look for a
  3663. callee-saved register, and 3) spill the variable to the stack.
  3664. It is straightforward to implement this approach in a graph coloring
  3665. register allocator. First, we know which variables are in use during
  3666. every function call because we compute that information for every
  3667. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3668. we build the interference graph
  3669. (Section~\ref{sec:build-interference}), we can place an edge between
  3670. each of these call-live variables and the caller-saved registers in
  3671. the interference graph. This will prevent the graph coloring algorithm
  3672. from assigning them to caller-saved registers.
  3673. Returning to the example in
  3674. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3675. generated x86 code on the right-hand side. Notice that variable
  3676. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3677. is already in a safe place during the second call to
  3678. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3679. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3680. live-after set of a \code{callq} instruction.
  3681. Next we analyze the example from the callee point of view, focusing on
  3682. the prelude and conclusion of the \code{main} function. As usual the
  3683. prelude begins with saving the \code{rbp} register to the stack and
  3684. setting the \code{rbp} to the current stack pointer. We now know why
  3685. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3686. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3687. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3688. (\code{x}). The other callee-saved registers are not saved in the
  3689. prelude because they are not used. The prelude subtracts 8 bytes from
  3690. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3691. conclusion, we see that \code{rbx} is restored from the stack with a
  3692. \code{popq} instruction.
  3693. \index{subject}{prelude}\index{subject}{conclusion}
  3694. \begin{figure}[tp]
  3695. \begin{minipage}{0.45\textwidth}
  3696. Example \LangVar{} program:
  3697. %var_test_14.rkt
  3698. {\if\edition\racketEd
  3699. \begin{lstlisting}
  3700. (let ([x (read)])
  3701. (let ([y (read)])
  3702. (+ (+ x y) 42)))
  3703. \end{lstlisting}
  3704. \fi}
  3705. {\if\edition\pythonEd
  3706. \begin{lstlisting}
  3707. x = input_int()
  3708. y = input_int()
  3709. print((x + y) + 42)
  3710. \end{lstlisting}
  3711. \fi}
  3712. \end{minipage}
  3713. \begin{minipage}{0.45\textwidth}
  3714. Generated x86 assembly:
  3715. {\if\edition\racketEd
  3716. \begin{lstlisting}
  3717. start:
  3718. callq read_int
  3719. movq %rax, %rbx
  3720. callq read_int
  3721. movq %rax, %rcx
  3722. addq %rcx, %rbx
  3723. movq %rbx, %rax
  3724. addq $42, %rax
  3725. jmp _conclusion
  3726. .globl main
  3727. main:
  3728. pushq %rbp
  3729. movq %rsp, %rbp
  3730. pushq %rbx
  3731. subq $8, %rsp
  3732. jmp start
  3733. conclusion:
  3734. addq $8, %rsp
  3735. popq %rbx
  3736. popq %rbp
  3737. retq
  3738. \end{lstlisting}
  3739. \fi}
  3740. {\if\edition\pythonEd
  3741. \begin{lstlisting}
  3742. .globl main
  3743. main:
  3744. pushq %rbp
  3745. movq %rsp, %rbp
  3746. pushq %rbx
  3747. subq $8, %rsp
  3748. callq read_int
  3749. movq %rax, %rbx
  3750. callq read_int
  3751. movq %rax, %rcx
  3752. movq %rbx, %rdx
  3753. addq %rcx, %rdx
  3754. movq %rdx, %rcx
  3755. addq $42, %rcx
  3756. movq %rcx, %rdi
  3757. callq print_int
  3758. addq $8, %rsp
  3759. popq %rbx
  3760. popq %rbp
  3761. retq
  3762. \end{lstlisting}
  3763. \fi}
  3764. \end{minipage}
  3765. \caption{An example with function calls.}
  3766. \label{fig:example-calling-conventions}
  3767. \end{figure}
  3768. %\clearpage
  3769. \section{Liveness Analysis}
  3770. \label{sec:liveness-analysis-Lvar}
  3771. \index{subject}{liveness analysis}
  3772. The \code{uncover\_live} \racket{pass}\python{function}
  3773. performs \emph{liveness analysis}, that
  3774. is, it discovers which variables are in-use in different regions of a
  3775. program.
  3776. %
  3777. A variable or register is \emph{live} at a program point if its
  3778. current value is used at some later point in the program. We refer to
  3779. variables, stack locations, and registers collectively as
  3780. \emph{locations}.
  3781. %
  3782. Consider the following code fragment in which there are two writes to
  3783. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3784. \begin{center}
  3785. \begin{minipage}{0.96\textwidth}
  3786. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3787. movq $5, a
  3788. movq $30, b
  3789. movq a, c
  3790. movq $10, b
  3791. addq b, c
  3792. \end{lstlisting}
  3793. \end{minipage}
  3794. \end{center}
  3795. The answer is no because \code{a} is live from line 1 to 3 and
  3796. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3797. line 2 is never used because it is overwritten (line 4) before the
  3798. next read (line 5).
  3799. The live locations can be computed by traversing the instruction
  3800. sequence back to front (i.e., backwards in execution order). Let
  3801. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3802. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3803. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3804. locations before instruction $I_k$.
  3805. \racket{We recommend representing these
  3806. sets with the Racket \code{set} data structure described in
  3807. Figure~\ref{fig:set}.}
  3808. \python{We recommend representing these sets with the Python
  3809. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3810. data structure.}
  3811. {\if\edition\racketEd
  3812. \begin{figure}[tp]
  3813. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3814. \small
  3815. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3816. A \emph{set} is an unordered collection of elements without duplicates.
  3817. Here are some of the operations defined on sets.
  3818. \index{subject}{set}
  3819. \begin{description}
  3820. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3821. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3822. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3823. difference of the two sets.
  3824. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3825. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3826. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3827. \end{description}
  3828. \end{tcolorbox}
  3829. %\end{wrapfigure}
  3830. \caption{The \code{set} data structure.}
  3831. \label{fig:set}
  3832. \end{figure}
  3833. \fi}
  3834. The live locations after an instruction are always the same as the
  3835. live locations before the next instruction.
  3836. \index{subject}{live-after} \index{subject}{live-before}
  3837. \begin{equation} \label{eq:live-after-before-next}
  3838. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3839. \end{equation}
  3840. To start things off, there are no live locations after the last
  3841. instruction, so
  3842. \begin{equation}\label{eq:live-last-empty}
  3843. L_{\mathsf{after}}(n) = \emptyset
  3844. \end{equation}
  3845. We then apply the following rule repeatedly, traversing the
  3846. instruction sequence back to front.
  3847. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3848. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3849. \end{equation}
  3850. where $W(k)$ are the locations written to by instruction $I_k$ and
  3851. $R(k)$ are the locations read by instruction $I_k$.
  3852. {\if\edition\racketEd
  3853. There is a special case for \code{jmp} instructions. The locations
  3854. that are live before a \code{jmp} should be the locations in
  3855. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3856. maintaining an alist named \code{label->live} that maps each label to
  3857. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3858. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3859. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3860. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3861. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3862. \fi}
  3863. Let us walk through the above example, applying these formulas
  3864. starting with the instruction on line 5. We collect the answers in
  3865. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3866. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3867. instruction (formula~\ref{eq:live-last-empty}). The
  3868. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3869. because it reads from variables \code{b} and \code{c}
  3870. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3871. \[
  3872. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3873. \]
  3874. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3875. the live-before set from line 5 to be the live-after set for this
  3876. instruction (formula~\ref{eq:live-after-before-next}).
  3877. \[
  3878. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3879. \]
  3880. This move instruction writes to \code{b} and does not read from any
  3881. variables, so we have the following live-before set
  3882. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3883. \[
  3884. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3885. \]
  3886. The live-before for instruction \code{movq a, c}
  3887. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3888. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3889. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3890. variable that is not live and does not read from a variable.
  3891. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3892. because it writes to variable \code{a}.
  3893. \begin{figure}[tbp]
  3894. \begin{minipage}{0.45\textwidth}
  3895. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3896. movq $5, a
  3897. movq $30, b
  3898. movq a, c
  3899. movq $10, b
  3900. addq b, c
  3901. \end{lstlisting}
  3902. \end{minipage}
  3903. \vrule\hspace{10pt}
  3904. \begin{minipage}{0.45\textwidth}
  3905. \begin{align*}
  3906. L_{\mathsf{before}}(1)= \emptyset,
  3907. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3908. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3909. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3910. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3911. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3912. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3913. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3914. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3915. L_{\mathsf{after}}(5)= \emptyset
  3916. \end{align*}
  3917. \end{minipage}
  3918. \caption{Example output of liveness analysis on a short example.}
  3919. \label{fig:liveness-example-0}
  3920. \end{figure}
  3921. \begin{exercise}\normalfont
  3922. Perform liveness analysis on the running example in
  3923. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3924. sets for each instruction. Compare your answers to the solution
  3925. shown in Figure~\ref{fig:live-eg}.
  3926. \end{exercise}
  3927. \begin{figure}[tp]
  3928. \hspace{20pt}
  3929. \begin{minipage}{0.45\textwidth}
  3930. {\if\edition\racketEd
  3931. \begin{lstlisting}
  3932. |$\{\ttm{rsp}\}$|
  3933. movq $1, v
  3934. |$\{\ttm{v},\ttm{rsp}\}$|
  3935. movq $42, w
  3936. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3937. movq v, x
  3938. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3939. addq $7, x
  3940. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3941. movq x, y
  3942. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3943. movq x, z
  3944. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3945. addq w, z
  3946. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3947. movq y, t
  3948. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3949. negq t
  3950. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3951. movq z, %rax
  3952. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3953. addq t, %rax
  3954. |$\{\ttm{rax},\ttm{rsp}\}$|
  3955. jmp conclusion
  3956. \end{lstlisting}
  3957. \fi}
  3958. {\if\edition\pythonEd
  3959. \begin{lstlisting}
  3960. movq $1, v
  3961. |$\{\ttm{v}\}$|
  3962. movq $42, w
  3963. |$\{\ttm{w}, \ttm{v}\}$|
  3964. movq v, x
  3965. |$\{\ttm{w}, \ttm{x}\}$|
  3966. addq $7, x
  3967. |$\{\ttm{w}, \ttm{x}\}$|
  3968. movq x, y
  3969. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  3970. movq x, z
  3971. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  3972. addq w, z
  3973. |$\{\ttm{y}, \ttm{z}\}$|
  3974. movq y, tmp_0
  3975. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3976. negq tmp_0
  3977. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3978. movq z, tmp_1
  3979. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  3980. addq tmp_0, tmp_1
  3981. |$\{\ttm{tmp\_1}\}$|
  3982. movq tmp_1, %rdi
  3983. |$\{\ttm{rdi}\}$|
  3984. callq print_int
  3985. |$\{\}$|
  3986. \end{lstlisting}
  3987. \fi}
  3988. \end{minipage}
  3989. \caption{The running example annotated with live-after sets.}
  3990. \label{fig:live-eg}
  3991. \end{figure}
  3992. \begin{exercise}\normalfont
  3993. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  3994. %
  3995. \racket{Store the sequence of live-after sets in the $\itm{info}$
  3996. field of the \code{Block} structure.}
  3997. %
  3998. \python{Return a dictionary that maps each instruction to its
  3999. live-after set.}
  4000. %
  4001. \racket{We recommend creating an auxiliary function that takes a list
  4002. of instructions and an initial live-after set (typically empty) and
  4003. returns the list of live-after sets.}
  4004. %
  4005. We recommend creating auxiliary functions to 1) compute the set
  4006. of locations that appear in an \Arg{}, 2) compute the locations read
  4007. by an instruction (the $R$ function), and 3) the locations written by
  4008. an instruction (the $W$ function). The \code{callq} instruction should
  4009. include all of the caller-saved registers in its write-set $W$ because
  4010. the calling convention says that those registers may be written to
  4011. during the function call. Likewise, the \code{callq} instruction
  4012. should include the appropriate argument-passing registers in its
  4013. read-set $R$, depending on the arity of the function being
  4014. called. (This is why the abstract syntax for \code{callq} includes the
  4015. arity.)
  4016. \end{exercise}
  4017. %\clearpage
  4018. \section{Build the Interference Graph}
  4019. \label{sec:build-interference}
  4020. {\if\edition\racketEd
  4021. \begin{figure}[tp]
  4022. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4023. \small
  4024. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4025. A \emph{graph} is a collection of vertices and edges where each
  4026. edge connects two vertices. A graph is \emph{directed} if each
  4027. edge points from a source to a target. Otherwise the graph is
  4028. \emph{undirected}.
  4029. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4030. \begin{description}
  4031. %% We currently don't use directed graphs. We instead use
  4032. %% directed multi-graphs. -Jeremy
  4033. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4034. directed graph from a list of edges. Each edge is a list
  4035. containing the source and target vertex.
  4036. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4037. undirected graph from a list of edges. Each edge is represented by
  4038. a list containing two vertices.
  4039. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4040. inserts a vertex into the graph.
  4041. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4042. inserts an edge between the two vertices.
  4043. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4044. returns a sequence of vertices adjacent to the vertex.
  4045. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4046. returns a sequence of all vertices in the graph.
  4047. \end{description}
  4048. \end{tcolorbox}
  4049. %\end{wrapfigure}
  4050. \caption{The Racket \code{graph} package.}
  4051. \label{fig:graph}
  4052. \end{figure}
  4053. \fi}
  4054. Based on the liveness analysis, we know where each location is live.
  4055. However, during register allocation, we need to answer questions of
  4056. the specific form: are locations $u$ and $v$ live at the same time?
  4057. (And therefore cannot be assigned to the same register.) To make this
  4058. question more efficient to answer, we create an explicit data
  4059. structure, an \emph{interference graph}\index{subject}{interference
  4060. graph}. An interference graph is an undirected graph that has an
  4061. edge between two locations if they are live at the same time, that is,
  4062. if they interfere with each other.
  4063. %
  4064. \racket{We recommend using the Racket \code{graph} package
  4065. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4066. %
  4067. \python{We provide implementations of directed and undirected graph
  4068. data structures in the file \code{graph.py} of the support code.}
  4069. A straightforward way to compute the interference graph is to look at
  4070. the set of live locations between each instruction and add an edge to
  4071. the graph for every pair of variables in the same set. This approach
  4072. is less than ideal for two reasons. First, it can be expensive because
  4073. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4074. locations. Second, in the special case where two locations hold the
  4075. same value (because one was assigned to the other), they can be live
  4076. at the same time without interfering with each other.
  4077. A better way to compute the interference graph is to focus on
  4078. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4079. must not overwrite something in a live location. So for each
  4080. instruction, we create an edge between the locations being written to
  4081. and the live locations. (Except that one should not create self
  4082. edges.) Note that for the \key{callq} instruction, we consider all of
  4083. the caller-saved registers as being written to, so an edge is added
  4084. between every live variable and every caller-saved register. Also, for
  4085. \key{movq} there is the above-mentioned special case to deal with. If
  4086. a live variable $v$ is the same as the source of the \key{movq}, then
  4087. there is no need to add an edge between $v$ and the destination,
  4088. because they both hold the same value.
  4089. %
  4090. So we have the following two rules.
  4091. \begin{enumerate}
  4092. \item If instruction $I_k$ is a move instruction of the form
  4093. \key{movq} $s$\key{,} $d$, then for every $v \in
  4094. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4095. $(d,v)$.
  4096. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4097. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4098. $(d,v)$.
  4099. \end{enumerate}
  4100. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4101. the above rules to each instruction. We highlight a few of the
  4102. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4103. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4104. so \code{v} interferes with \code{rsp}.}
  4105. %
  4106. \python{The first instruction is \lstinline{movq $1, v} and the
  4107. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4108. no interference because $\ttm{v}$ is the destination of the move.}
  4109. %
  4110. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4111. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4112. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4113. %
  4114. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4115. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4116. $\ttm{x}$ interferes with \ttm{w}.}
  4117. %
  4118. \racket{The next instruction is \lstinline{movq x, y} and the
  4119. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4120. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4121. \ttm{x} because \ttm{x} is the source of the move and therefore
  4122. \ttm{x} and \ttm{y} hold the same value.}
  4123. %
  4124. \python{The next instruction is \lstinline{movq x, y} and the
  4125. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4126. applies, so \ttm{y} interferes with \ttm{w} but not
  4127. \ttm{x} because \ttm{x} is the source of the move and therefore
  4128. \ttm{x} and \ttm{y} hold the same value.}
  4129. %
  4130. Figure~\ref{fig:interference-results} lists the interference results
  4131. for all of the instructions and the resulting interference graph is
  4132. shown in Figure~\ref{fig:interfere}.
  4133. \begin{figure}[tbp]
  4134. \begin{quote}
  4135. {\if\edition\racketEd
  4136. \begin{tabular}{ll}
  4137. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4138. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4139. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4140. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4141. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4142. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4143. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4144. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4145. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4146. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4147. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4148. \lstinline!jmp conclusion!& no interference.
  4149. \end{tabular}
  4150. \fi}
  4151. {\if\edition\pythonEd
  4152. \begin{tabular}{ll}
  4153. \lstinline!movq $1, v!& no interference\\
  4154. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4155. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4156. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4157. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4158. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4159. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4160. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4161. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4162. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4163. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4164. \lstinline!movq tmp_1, %rdi! & no interference \\
  4165. \lstinline!callq print_int!& no interference.
  4166. \end{tabular}
  4167. \fi}
  4168. \end{quote}
  4169. \caption{Interference results for the running example.}
  4170. \label{fig:interference-results}
  4171. \end{figure}
  4172. \begin{figure}[tbp]
  4173. \large
  4174. {\if\edition\racketEd
  4175. \[
  4176. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4177. \node (rax) at (0,0) {$\ttm{rax}$};
  4178. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4179. \node (t1) at (0,2) {$\ttm{t}$};
  4180. \node (z) at (3,2) {$\ttm{z}$};
  4181. \node (x) at (6,2) {$\ttm{x}$};
  4182. \node (y) at (3,0) {$\ttm{y}$};
  4183. \node (w) at (6,0) {$\ttm{w}$};
  4184. \node (v) at (9,0) {$\ttm{v}$};
  4185. \draw (t1) to (rax);
  4186. \draw (t1) to (z);
  4187. \draw (z) to (y);
  4188. \draw (z) to (w);
  4189. \draw (x) to (w);
  4190. \draw (y) to (w);
  4191. \draw (v) to (w);
  4192. \draw (v) to (rsp);
  4193. \draw (w) to (rsp);
  4194. \draw (x) to (rsp);
  4195. \draw (y) to (rsp);
  4196. \path[-.,bend left=15] (z) edge node {} (rsp);
  4197. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4198. \draw (rax) to (rsp);
  4199. \end{tikzpicture}
  4200. \]
  4201. \fi}
  4202. {\if\edition\pythonEd
  4203. \[
  4204. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4205. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4206. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4207. \node (z) at (3,2) {$\ttm{z}$};
  4208. \node (x) at (6,2) {$\ttm{x}$};
  4209. \node (y) at (3,0) {$\ttm{y}$};
  4210. \node (w) at (6,0) {$\ttm{w}$};
  4211. \node (v) at (9,0) {$\ttm{v}$};
  4212. \draw (t0) to (t1);
  4213. \draw (t0) to (z);
  4214. \draw (z) to (y);
  4215. \draw (z) to (w);
  4216. \draw (x) to (w);
  4217. \draw (y) to (w);
  4218. \draw (v) to (w);
  4219. \end{tikzpicture}
  4220. \]
  4221. \fi}
  4222. \caption{The interference graph of the example program.}
  4223. \label{fig:interfere}
  4224. \end{figure}
  4225. %% Our next concern is to choose a data structure for representing the
  4226. %% interference graph. There are many choices for how to represent a
  4227. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4228. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4229. %% data structure is to study the algorithm that uses the data structure,
  4230. %% determine what operations need to be performed, and then choose the
  4231. %% data structure that provide the most efficient implementations of
  4232. %% those operations. Often times the choice of data structure can have an
  4233. %% effect on the time complexity of the algorithm, as it does here. If
  4234. %% you skim the next section, you will see that the register allocation
  4235. %% algorithm needs to ask the graph for all of its vertices and, given a
  4236. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4237. %% correct choice of graph representation is that of an adjacency
  4238. %% list. There are helper functions in \code{utilities.rkt} for
  4239. %% representing graphs using the adjacency list representation:
  4240. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4241. %% (Appendix~\ref{appendix:utilities}).
  4242. %% %
  4243. %% \margincomment{\footnotesize To do: change to use the
  4244. %% Racket graph library. \\ --Jeremy}
  4245. %% %
  4246. %% In particular, those functions use a hash table to map each vertex to
  4247. %% the set of adjacent vertices, and the sets are represented using
  4248. %% Racket's \key{set}, which is also a hash table.
  4249. \begin{exercise}\normalfont
  4250. \racket{Implement the compiler pass named \code{build\_interference} according
  4251. to the algorithm suggested above. We recommend using the Racket
  4252. \code{graph} package to create and inspect the interference graph.
  4253. The output graph of this pass should be stored in the $\itm{info}$ field of
  4254. the program, under the key \code{conflicts}.}
  4255. %
  4256. \python{Implement a function named \code{build\_interference}
  4257. according to the algorithm suggested above that
  4258. returns the interference graph.}
  4259. \end{exercise}
  4260. \section{Graph Coloring via Sudoku}
  4261. \label{sec:graph-coloring}
  4262. \index{subject}{graph coloring}
  4263. \index{subject}{Sudoku}
  4264. \index{subject}{color}
  4265. We come to the main event, mapping variables to registers and stack
  4266. locations. Variables that interfere with each other must be mapped to
  4267. different locations. In terms of the interference graph, this means
  4268. that adjacent vertices must be mapped to different locations. If we
  4269. think of locations as colors, the register allocation problem becomes
  4270. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4271. The reader may be more familiar with the graph coloring problem than he
  4272. or she realizes; the popular game of Sudoku is an instance of the
  4273. graph coloring problem. The following describes how to build a graph
  4274. out of an initial Sudoku board.
  4275. \begin{itemize}
  4276. \item There is one vertex in the graph for each Sudoku square.
  4277. \item There is an edge between two vertices if the corresponding squares
  4278. are in the same row, in the same column, or if the squares are in
  4279. the same $3\times 3$ region.
  4280. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4281. \item Based on the initial assignment of numbers to squares in the
  4282. Sudoku board, assign the corresponding colors to the corresponding
  4283. vertices in the graph.
  4284. \end{itemize}
  4285. If you can color the remaining vertices in the graph with the nine
  4286. colors, then you have also solved the corresponding game of Sudoku.
  4287. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4288. the corresponding graph with colored vertices. We map the Sudoku
  4289. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4290. sampling of the vertices (the colored ones) because showing edges for
  4291. all of the vertices would make the graph unreadable.
  4292. \begin{figure}[tbp]
  4293. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4294. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4295. \caption{A Sudoku game board and the corresponding colored graph.}
  4296. \label{fig:sudoku-graph}
  4297. \end{figure}
  4298. Some techniques for playing Sudoku correspond to heuristics used in
  4299. graph coloring algorithms. For example, one of the basic techniques
  4300. for Sudoku is called Pencil Marks. The idea is to use a process of
  4301. elimination to determine what numbers are no longer available for a
  4302. square and write down those numbers in the square (writing very
  4303. small). For example, if the number $1$ is assigned to a square, then
  4304. write the pencil mark $1$ in all the squares in the same row, column,
  4305. and region to indicate that $1$ is no longer an option for those other
  4306. squares.
  4307. %
  4308. The Pencil Marks technique corresponds to the notion of
  4309. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4310. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4311. are no longer available. In graph terminology, we have the following
  4312. definition:
  4313. \begin{equation*}
  4314. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4315. \text{ and } \mathrm{color}(v) = c \}
  4316. \end{equation*}
  4317. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4318. edge with $u$.
  4319. The Pencil Marks technique leads to a simple strategy for filling in
  4320. numbers: if there is a square with only one possible number left, then
  4321. choose that number! But what if there are no squares with only one
  4322. possibility left? One brute-force approach is to try them all: choose
  4323. the first one and if that ultimately leads to a solution, great. If
  4324. not, backtrack and choose the next possibility. One good thing about
  4325. Pencil Marks is that it reduces the degree of branching in the search
  4326. tree. Nevertheless, backtracking can be terribly time consuming. One
  4327. way to reduce the amount of backtracking is to use the
  4328. most-constrained-first heuristic (aka. minimum remaining
  4329. values)~\citep{Russell2003}. That is, when choosing a square, always
  4330. choose one with the fewest possibilities left (the vertex with the
  4331. highest saturation). The idea is that choosing highly constrained
  4332. squares earlier rather than later is better because later on there may
  4333. not be any possibilities left in the highly saturated squares.
  4334. However, register allocation is easier than Sudoku because the
  4335. register allocator can fall back to assigning variables to stack
  4336. locations when the registers run out. Thus, it makes sense to replace
  4337. backtracking with greedy search: make the best choice at the time and
  4338. keep going. We still wish to minimize the number of colors needed, so
  4339. we use the most-constrained-first heuristic in the greedy search.
  4340. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4341. algorithm for register allocation based on saturation and the
  4342. most-constrained-first heuristic. It is roughly equivalent to the
  4343. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4344. %,Gebremedhin:1999fk,Omari:2006uq
  4345. Just as in Sudoku, the algorithm represents colors with integers. The
  4346. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4347. for register allocation. The integers $k$ and larger correspond to
  4348. stack locations. The registers that are not used for register
  4349. allocation, such as \code{rax}, are assigned to negative integers. In
  4350. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4351. %% One might wonder why we include registers at all in the liveness
  4352. %% analysis and interference graph. For example, we never allocate a
  4353. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4354. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  4355. %% to use register for passing arguments to functions, it will be
  4356. %% necessary for those registers to appear in the interference graph
  4357. %% because those registers will also be assigned to variables, and we
  4358. %% don't want those two uses to encroach on each other. Regarding
  4359. %% registers such as \code{rax} and \code{rsp} that are not used for
  4360. %% variables, we could omit them from the interference graph but that
  4361. %% would require adding special cases to our algorithm, which would
  4362. %% complicate the logic for little gain.
  4363. \begin{figure}[btp]
  4364. \centering
  4365. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4366. Algorithm: DSATUR
  4367. Input: a graph |$G$|
  4368. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4369. |$W \gets \mathrm{vertices}(G)$|
  4370. while |$W \neq \emptyset$| do
  4371. pick a vertex |$u$| from |$W$| with the highest saturation,
  4372. breaking ties randomly
  4373. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4374. |$\mathrm{color}[u] \gets c$|
  4375. |$W \gets W - \{u\}$|
  4376. \end{lstlisting}
  4377. \caption{The saturation-based greedy graph coloring algorithm.}
  4378. \label{fig:satur-algo}
  4379. \end{figure}
  4380. {\if\edition\racketEd
  4381. With the DSATUR algorithm in hand, let us return to the running
  4382. example and consider how to color the interference graph in
  4383. Figure~\ref{fig:interfere}.
  4384. %
  4385. We start by assigning the register nodes to their own color. For
  4386. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4387. assigned $-2$. The variables are not yet colored, so they are
  4388. annotated with a dash. We then update the saturation for vertices that
  4389. are adjacent to a register, obtaining the following annotated
  4390. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4391. it interferes with both \code{rax} and \code{rsp}.
  4392. \[
  4393. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4394. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4395. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4396. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4397. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4398. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4399. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4400. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4401. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4402. \draw (t1) to (rax);
  4403. \draw (t1) to (z);
  4404. \draw (z) to (y);
  4405. \draw (z) to (w);
  4406. \draw (x) to (w);
  4407. \draw (y) to (w);
  4408. \draw (v) to (w);
  4409. \draw (v) to (rsp);
  4410. \draw (w) to (rsp);
  4411. \draw (x) to (rsp);
  4412. \draw (y) to (rsp);
  4413. \path[-.,bend left=15] (z) edge node {} (rsp);
  4414. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4415. \draw (rax) to (rsp);
  4416. \end{tikzpicture}
  4417. \]
  4418. The algorithm says to select a maximally saturated vertex. So we pick
  4419. $\ttm{t}$ and color it with the first available integer, which is
  4420. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4421. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4422. \[
  4423. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4424. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4425. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4426. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4427. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4428. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4429. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4430. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4431. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4432. \draw (t1) to (rax);
  4433. \draw (t1) to (z);
  4434. \draw (z) to (y);
  4435. \draw (z) to (w);
  4436. \draw (x) to (w);
  4437. \draw (y) to (w);
  4438. \draw (v) to (w);
  4439. \draw (v) to (rsp);
  4440. \draw (w) to (rsp);
  4441. \draw (x) to (rsp);
  4442. \draw (y) to (rsp);
  4443. \path[-.,bend left=15] (z) edge node {} (rsp);
  4444. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4445. \draw (rax) to (rsp);
  4446. \end{tikzpicture}
  4447. \]
  4448. We repeat the process, selecting a maximally saturated vertex,
  4449. choosing is \code{z}, and color it with the first available number, which
  4450. is $1$. We add $1$ to the saturation for the neighboring vertices
  4451. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4452. \[
  4453. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4454. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4455. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4456. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4457. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4458. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4459. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4460. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4461. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4462. \draw (t1) to (rax);
  4463. \draw (t1) to (z);
  4464. \draw (z) to (y);
  4465. \draw (z) to (w);
  4466. \draw (x) to (w);
  4467. \draw (y) to (w);
  4468. \draw (v) to (w);
  4469. \draw (v) to (rsp);
  4470. \draw (w) to (rsp);
  4471. \draw (x) to (rsp);
  4472. \draw (y) to (rsp);
  4473. \path[-.,bend left=15] (z) edge node {} (rsp);
  4474. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4475. \draw (rax) to (rsp);
  4476. \end{tikzpicture}
  4477. \]
  4478. The most saturated vertices are now \code{w} and \code{y}. We color
  4479. \code{w} with the first available color, which is $0$.
  4480. \[
  4481. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4482. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4483. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4484. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4485. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4486. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4487. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4488. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4489. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4490. \draw (t1) to (rax);
  4491. \draw (t1) to (z);
  4492. \draw (z) to (y);
  4493. \draw (z) to (w);
  4494. \draw (x) to (w);
  4495. \draw (y) to (w);
  4496. \draw (v) to (w);
  4497. \draw (v) to (rsp);
  4498. \draw (w) to (rsp);
  4499. \draw (x) to (rsp);
  4500. \draw (y) to (rsp);
  4501. \path[-.,bend left=15] (z) edge node {} (rsp);
  4502. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4503. \draw (rax) to (rsp);
  4504. \end{tikzpicture}
  4505. \]
  4506. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4507. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4508. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4509. and \code{z}, whose colors are $0$ and $1$ respectively.
  4510. \[
  4511. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4512. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4513. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4514. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4515. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4516. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4517. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4518. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4519. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4520. \draw (t1) to (rax);
  4521. \draw (t1) to (z);
  4522. \draw (z) to (y);
  4523. \draw (z) to (w);
  4524. \draw (x) to (w);
  4525. \draw (y) to (w);
  4526. \draw (v) to (w);
  4527. \draw (v) to (rsp);
  4528. \draw (w) to (rsp);
  4529. \draw (x) to (rsp);
  4530. \draw (y) to (rsp);
  4531. \path[-.,bend left=15] (z) edge node {} (rsp);
  4532. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4533. \draw (rax) to (rsp);
  4534. \end{tikzpicture}
  4535. \]
  4536. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4537. \[
  4538. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4539. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4540. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4541. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4542. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4543. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4544. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4545. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4546. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4547. \draw (t1) to (rax);
  4548. \draw (t1) to (z);
  4549. \draw (z) to (y);
  4550. \draw (z) to (w);
  4551. \draw (x) to (w);
  4552. \draw (y) to (w);
  4553. \draw (v) to (w);
  4554. \draw (v) to (rsp);
  4555. \draw (w) to (rsp);
  4556. \draw (x) to (rsp);
  4557. \draw (y) to (rsp);
  4558. \path[-.,bend left=15] (z) edge node {} (rsp);
  4559. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4560. \draw (rax) to (rsp);
  4561. \end{tikzpicture}
  4562. \]
  4563. In the last step of the algorithm, we color \code{x} with $1$.
  4564. \[
  4565. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4566. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4567. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4568. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4569. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4570. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4571. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4572. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4573. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4574. \draw (t1) to (rax);
  4575. \draw (t1) to (z);
  4576. \draw (z) to (y);
  4577. \draw (z) to (w);
  4578. \draw (x) to (w);
  4579. \draw (y) to (w);
  4580. \draw (v) to (w);
  4581. \draw (v) to (rsp);
  4582. \draw (w) to (rsp);
  4583. \draw (x) to (rsp);
  4584. \draw (y) to (rsp);
  4585. \path[-.,bend left=15] (z) edge node {} (rsp);
  4586. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4587. \draw (rax) to (rsp);
  4588. \end{tikzpicture}
  4589. \]
  4590. So we obtain the following coloring:
  4591. \[
  4592. \{
  4593. \ttm{rax} \mapsto -1,
  4594. \ttm{rsp} \mapsto -2,
  4595. \ttm{t} \mapsto 0,
  4596. \ttm{z} \mapsto 1,
  4597. \ttm{x} \mapsto 1,
  4598. \ttm{y} \mapsto 2,
  4599. \ttm{w} \mapsto 0,
  4600. \ttm{v} \mapsto 1
  4601. \}
  4602. \]
  4603. \fi}
  4604. %
  4605. {\if\edition\pythonEd
  4606. %
  4607. With the DSATUR algorithm in hand, let us return to the running
  4608. example and consider how to color the interference graph in
  4609. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4610. to indicate that it has not yet been assigned a color. The saturation
  4611. sets are also shown for each node; all of them start as the empty set.
  4612. (We do not include the register nodes in the graph below because there
  4613. were no interference edges involving registers in this program, but in
  4614. general there can be.)
  4615. %
  4616. \[
  4617. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4618. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4619. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4620. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4621. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4622. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4623. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4624. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4625. \draw (t0) to (t1);
  4626. \draw (t0) to (z);
  4627. \draw (z) to (y);
  4628. \draw (z) to (w);
  4629. \draw (x) to (w);
  4630. \draw (y) to (w);
  4631. \draw (v) to (w);
  4632. \end{tikzpicture}
  4633. \]
  4634. The algorithm says to select a maximally saturated vertex, but they
  4635. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4636. then color it with the first available integer, which is $0$. We mark
  4637. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4638. they interfere with $\ttm{tmp\_0}$.
  4639. \[
  4640. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4641. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4642. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4643. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4644. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4645. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4646. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4647. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4648. \draw (t0) to (t1);
  4649. \draw (t0) to (z);
  4650. \draw (z) to (y);
  4651. \draw (z) to (w);
  4652. \draw (x) to (w);
  4653. \draw (y) to (w);
  4654. \draw (v) to (w);
  4655. \end{tikzpicture}
  4656. \]
  4657. We repeat the process. The most saturated vertices are \code{z} and
  4658. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4659. available number, which is $1$. We add $1$ to the saturation for the
  4660. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4661. \[
  4662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4663. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4664. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4665. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4666. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4667. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4668. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4669. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4670. \draw (t0) to (t1);
  4671. \draw (t0) to (z);
  4672. \draw (z) to (y);
  4673. \draw (z) to (w);
  4674. \draw (x) to (w);
  4675. \draw (y) to (w);
  4676. \draw (v) to (w);
  4677. \end{tikzpicture}
  4678. \]
  4679. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4680. \code{y}. We color \code{w} with the first available color, which
  4681. is $0$.
  4682. \[
  4683. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4684. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4685. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4686. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4687. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4688. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4689. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4690. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4691. \draw (t0) to (t1);
  4692. \draw (t0) to (z);
  4693. \draw (z) to (y);
  4694. \draw (z) to (w);
  4695. \draw (x) to (w);
  4696. \draw (y) to (w);
  4697. \draw (v) to (w);
  4698. \end{tikzpicture}
  4699. \]
  4700. Now \code{y} is the most saturated, so we color it with $2$.
  4701. \[
  4702. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4703. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4704. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4705. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4706. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4707. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4708. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4709. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4710. \draw (t0) to (t1);
  4711. \draw (t0) to (z);
  4712. \draw (z) to (y);
  4713. \draw (z) to (w);
  4714. \draw (x) to (w);
  4715. \draw (y) to (w);
  4716. \draw (v) to (w);
  4717. \end{tikzpicture}
  4718. \]
  4719. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4720. We choose to color \code{v} with $1$.
  4721. \[
  4722. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4723. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4724. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4725. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4726. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4727. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4728. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4729. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4730. \draw (t0) to (t1);
  4731. \draw (t0) to (z);
  4732. \draw (z) to (y);
  4733. \draw (z) to (w);
  4734. \draw (x) to (w);
  4735. \draw (y) to (w);
  4736. \draw (v) to (w);
  4737. \end{tikzpicture}
  4738. \]
  4739. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4740. \[
  4741. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4742. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4743. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4744. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4745. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4746. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4747. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4748. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4749. \draw (t0) to (t1);
  4750. \draw (t0) to (z);
  4751. \draw (z) to (y);
  4752. \draw (z) to (w);
  4753. \draw (x) to (w);
  4754. \draw (y) to (w);
  4755. \draw (v) to (w);
  4756. \end{tikzpicture}
  4757. \]
  4758. So we obtain the following coloring:
  4759. \[
  4760. \{ \ttm{tmp\_0} \mapsto 0,
  4761. \ttm{tmp\_1} \mapsto 1,
  4762. \ttm{z} \mapsto 1,
  4763. \ttm{x} \mapsto 1,
  4764. \ttm{y} \mapsto 2,
  4765. \ttm{w} \mapsto 0,
  4766. \ttm{v} \mapsto 1 \}
  4767. \]
  4768. \fi}
  4769. We recommend creating an auxiliary function named \code{color\_graph}
  4770. that takes an interference graph and a list of all the variables in
  4771. the program. This function should return a mapping of variables to
  4772. their colors (represented as natural numbers). By creating this helper
  4773. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4774. when we add support for functions.
  4775. To prioritize the processing of highly saturated nodes inside the
  4776. \code{color\_graph} function, we recommend using the priority queue
  4777. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4778. addition, you will need to maintain a mapping from variables to their
  4779. ``handles'' in the priority queue so that you can notify the priority
  4780. queue when their saturation changes.}
  4781. {\if\edition\racketEd
  4782. \begin{figure}[tp]
  4783. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4784. \small
  4785. \begin{tcolorbox}[title=Priority Queue]
  4786. A \emph{priority queue} is a collection of items in which the
  4787. removal of items is governed by priority. In a ``min'' queue,
  4788. lower priority items are removed first. An implementation is in
  4789. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4790. queue} \index{subject}{minimum priority queue}
  4791. \begin{description}
  4792. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4793. priority queue that uses the $\itm{cmp}$ predicate to determine
  4794. whether its first argument has lower or equal priority to its
  4795. second argument.
  4796. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4797. items in the queue.
  4798. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4799. the item into the queue and returns a handle for the item in the
  4800. queue.
  4801. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4802. the lowest priority.
  4803. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4804. notifies the queue that the priority has decreased for the item
  4805. associated with the given handle.
  4806. \end{description}
  4807. \end{tcolorbox}
  4808. %\end{wrapfigure}
  4809. \caption{The priority queue data structure.}
  4810. \label{fig:priority-queue}
  4811. \end{figure}
  4812. \fi}
  4813. With the coloring complete, we finalize the assignment of variables to
  4814. registers and stack locations. We map the first $k$ colors to the $k$
  4815. registers and the rest of the colors to stack locations. Suppose for
  4816. the moment that we have just one register to use for register
  4817. allocation, \key{rcx}. Then we have the following map from colors to
  4818. locations.
  4819. \[
  4820. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4821. \]
  4822. Composing this mapping with the coloring, we arrive at the following
  4823. assignment of variables to locations.
  4824. {\if\edition\racketEd
  4825. \begin{gather*}
  4826. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4827. \ttm{w} \mapsto \key{\%rcx}, \,
  4828. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4829. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4830. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4831. \ttm{t} \mapsto \key{\%rcx} \}
  4832. \end{gather*}
  4833. \fi}
  4834. {\if\edition\pythonEd
  4835. \begin{gather*}
  4836. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4837. \ttm{w} \mapsto \key{\%rcx}, \,
  4838. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4839. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4840. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4841. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4842. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4843. \end{gather*}
  4844. \fi}
  4845. Adapt the code from the \code{assign\_homes} pass
  4846. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4847. assigned location. Applying the above assignment to our running
  4848. example, on the left, yields the program on the right.
  4849. % why frame size of 32? -JGS
  4850. \begin{center}
  4851. {\if\edition\racketEd
  4852. \begin{minipage}{0.3\textwidth}
  4853. \begin{lstlisting}
  4854. movq $1, v
  4855. movq $42, w
  4856. movq v, x
  4857. addq $7, x
  4858. movq x, y
  4859. movq x, z
  4860. addq w, z
  4861. movq y, t
  4862. negq t
  4863. movq z, %rax
  4864. addq t, %rax
  4865. jmp conclusion
  4866. \end{lstlisting}
  4867. \end{minipage}
  4868. $\Rightarrow\qquad$
  4869. \begin{minipage}{0.45\textwidth}
  4870. \begin{lstlisting}
  4871. movq $1, -8(%rbp)
  4872. movq $42, %rcx
  4873. movq -8(%rbp), -8(%rbp)
  4874. addq $7, -8(%rbp)
  4875. movq -8(%rbp), -16(%rbp)
  4876. movq -8(%rbp), -8(%rbp)
  4877. addq %rcx, -8(%rbp)
  4878. movq -16(%rbp), %rcx
  4879. negq %rcx
  4880. movq -8(%rbp), %rax
  4881. addq %rcx, %rax
  4882. jmp conclusion
  4883. \end{lstlisting}
  4884. \end{minipage}
  4885. \fi}
  4886. {\if\edition\pythonEd
  4887. \begin{minipage}{0.3\textwidth}
  4888. \begin{lstlisting}
  4889. movq $1, v
  4890. movq $42, w
  4891. movq v, x
  4892. addq $7, x
  4893. movq x, y
  4894. movq x, z
  4895. addq w, z
  4896. movq y, tmp_0
  4897. negq tmp_0
  4898. movq z, tmp_1
  4899. addq tmp_0, tmp_1
  4900. movq tmp_1, %rdi
  4901. callq print_int
  4902. \end{lstlisting}
  4903. \end{minipage}
  4904. $\Rightarrow\qquad$
  4905. \begin{minipage}{0.45\textwidth}
  4906. \begin{lstlisting}
  4907. movq $1, -8(%rbp)
  4908. movq $42, %rcx
  4909. movq -8(%rbp), -8(%rbp)
  4910. addq $7, -8(%rbp)
  4911. movq -8(%rbp), -16(%rbp)
  4912. movq -8(%rbp), -8(%rbp)
  4913. addq %rcx, -8(%rbp)
  4914. movq -16(%rbp), %rcx
  4915. negq %rcx
  4916. movq -8(%rbp), -8(%rbp)
  4917. addq %rcx, -8(%rbp)
  4918. movq -8(%rbp), %rdi
  4919. callq print_int
  4920. \end{lstlisting}
  4921. \end{minipage}
  4922. \fi}
  4923. \end{center}
  4924. \begin{exercise}\normalfont
  4925. %
  4926. Implement the compiler pass \code{allocate\_registers}.
  4927. %
  4928. Create five programs that exercise all aspects of the register
  4929. allocation algorithm, including spilling variables to the stack.
  4930. %
  4931. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4932. \code{run-tests.rkt} script with the three new passes:
  4933. \code{uncover\_live}, \code{build\_interference}, and
  4934. \code{allocate\_registers}.
  4935. %
  4936. Temporarily remove the \code{print\_x86} pass from the list of passes
  4937. and the call to \code{compiler-tests}.
  4938. Run the script to test the register allocator.
  4939. }
  4940. %
  4941. \python{Run the \code{run-tests.py} script to to check whether the
  4942. output programs produce the same result as the input programs.}
  4943. \end{exercise}
  4944. \section{Patch Instructions}
  4945. \label{sec:patch-instructions}
  4946. The remaining step in the compilation to x86 is to ensure that the
  4947. instructions have at most one argument that is a memory access.
  4948. %
  4949. In the running example, the instruction \code{movq -8(\%rbp),
  4950. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4951. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4952. then move \code{rax} into \code{-16(\%rbp)}.
  4953. %
  4954. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4955. problematic, but they can simply be deleted. In general, we recommend
  4956. deleting all the trivial moves whose source and destination are the
  4957. same location.
  4958. %
  4959. The following is the output of \code{patch\_instructions} on the
  4960. running example.
  4961. \begin{center}
  4962. {\if\edition\racketEd
  4963. \begin{minipage}{0.4\textwidth}
  4964. \begin{lstlisting}
  4965. movq $1, -8(%rbp)
  4966. movq $42, %rcx
  4967. movq -8(%rbp), -8(%rbp)
  4968. addq $7, -8(%rbp)
  4969. movq -8(%rbp), -16(%rbp)
  4970. movq -8(%rbp), -8(%rbp)
  4971. addq %rcx, -8(%rbp)
  4972. movq -16(%rbp), %rcx
  4973. negq %rcx
  4974. movq -8(%rbp), %rax
  4975. addq %rcx, %rax
  4976. jmp conclusion
  4977. \end{lstlisting}
  4978. \end{minipage}
  4979. $\Rightarrow\qquad$
  4980. \begin{minipage}{0.45\textwidth}
  4981. \begin{lstlisting}
  4982. movq $1, -8(%rbp)
  4983. movq $42, %rcx
  4984. addq $7, -8(%rbp)
  4985. movq -8(%rbp), %rax
  4986. movq %rax, -16(%rbp)
  4987. addq %rcx, -8(%rbp)
  4988. movq -16(%rbp), %rcx
  4989. negq %rcx
  4990. movq -8(%rbp), %rax
  4991. addq %rcx, %rax
  4992. jmp conclusion
  4993. \end{lstlisting}
  4994. \end{minipage}
  4995. \fi}
  4996. {\if\edition\pythonEd
  4997. \begin{minipage}{0.4\textwidth}
  4998. \begin{lstlisting}
  4999. movq $1, -8(%rbp)
  5000. movq $42, %rcx
  5001. movq -8(%rbp), -8(%rbp)
  5002. addq $7, -8(%rbp)
  5003. movq -8(%rbp), -16(%rbp)
  5004. movq -8(%rbp), -8(%rbp)
  5005. addq %rcx, -8(%rbp)
  5006. movq -16(%rbp), %rcx
  5007. negq %rcx
  5008. movq -8(%rbp), -8(%rbp)
  5009. addq %rcx, -8(%rbp)
  5010. movq -8(%rbp), %rdi
  5011. callq print_int
  5012. \end{lstlisting}
  5013. \end{minipage}
  5014. $\Rightarrow\qquad$
  5015. \begin{minipage}{0.45\textwidth}
  5016. \begin{lstlisting}
  5017. movq $1, -8(%rbp)
  5018. movq $42, %rcx
  5019. addq $7, -8(%rbp)
  5020. movq -8(%rbp), %rax
  5021. movq %rax, -16(%rbp)
  5022. addq %rcx, -8(%rbp)
  5023. movq -16(%rbp), %rcx
  5024. negq %rcx
  5025. addq %rcx, -8(%rbp)
  5026. movq -8(%rbp), %rdi
  5027. callq print_int
  5028. \end{lstlisting}
  5029. \end{minipage}
  5030. \fi}
  5031. \end{center}
  5032. \begin{exercise}\normalfont
  5033. %
  5034. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5035. %
  5036. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5037. %in the \code{run-tests.rkt} script.
  5038. %
  5039. Run the script to test the \code{patch\_instructions} pass.
  5040. \end{exercise}
  5041. \section{Prelude and Conclusion}
  5042. \label{sec:print-x86-reg-alloc}
  5043. \index{subject}{calling conventions}
  5044. \index{subject}{prelude}\index{subject}{conclusion}
  5045. Recall that this pass generates the prelude and conclusion
  5046. instructions to satisfy the x86 calling conventions
  5047. (Section~\ref{sec:calling-conventions}). With the addition of the
  5048. register allocator, the callee-saved registers used by the register
  5049. allocator must be saved in the prelude and restored in the conclusion.
  5050. In the \code{allocate\_registers} pass,
  5051. %
  5052. \racket{add an entry to the \itm{info}
  5053. of \code{X86Program} named \code{used\_callee}}
  5054. %
  5055. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5056. %
  5057. that stores the set of callee-saved registers that were assigned to
  5058. variables. The \code{prelude\_and\_conclusion} pass can then access
  5059. this information to decide which callee-saved registers need to be
  5060. saved and restored.
  5061. %
  5062. When calculating the size of the frame to adjust the \code{rsp} in the
  5063. prelude, make sure to take into account the space used for saving the
  5064. callee-saved registers. Also, don't forget that the frame needs to be
  5065. a multiple of 16 bytes!
  5066. \racket{An overview of all of the passes involved in register
  5067. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5068. {\if\edition\racketEd
  5069. \begin{figure}[tbp]
  5070. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5071. \node (Lvar) at (0,2) {\large \LangVar{}};
  5072. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5073. \node (Lvar-3) at (6,2) {\large \LangVar{}};
  5074. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5075. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5076. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5077. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5078. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5079. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5080. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5081. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5082. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5083. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5084. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5085. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5086. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5087. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5088. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5089. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5090. \end{tikzpicture}
  5091. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5092. \label{fig:reg-alloc-passes}
  5093. \end{figure}
  5094. \fi}
  5095. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5096. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5097. use of registers and the stack, we limit the register allocator for
  5098. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5099. the prelude\index{subject}{prelude} of the \code{main} function, we
  5100. push \code{rbx} onto the stack because it is a callee-saved register
  5101. and it was assigned to variable by the register allocator. We
  5102. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5103. reserve space for the one spilled variable. After that subtraction,
  5104. the \code{rsp} is aligned to 16 bytes.
  5105. Moving on to the program proper, we see how the registers were
  5106. allocated.
  5107. %
  5108. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5109. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5110. %
  5111. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5112. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5113. were assigned to \code{rbx}.}
  5114. %
  5115. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5116. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5117. callee-save register \code{rbx} onto the stack. The spilled variables
  5118. must be placed lower on the stack than the saved callee-save
  5119. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5120. \code{-16(\%rbp)}.
  5121. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5122. done in the prelude. We move the stack pointer up by \code{8} bytes
  5123. (the room for spilled variables), then we pop the old values of
  5124. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5125. \code{retq} to return control to the operating system.
  5126. \begin{figure}[tbp]
  5127. % var_test_28.rkt
  5128. % (use-minimal-set-of-registers! #t)
  5129. % and only rbx rcx
  5130. % tmp 0 rbx
  5131. % z 1 rcx
  5132. % y 0 rbx
  5133. % w 2 16(%rbp)
  5134. % v 0 rbx
  5135. % x 0 rbx
  5136. {\if\edition\racketEd
  5137. \begin{lstlisting}
  5138. start:
  5139. movq $1, %rbx
  5140. movq $42, -16(%rbp)
  5141. addq $7, %rbx
  5142. movq %rbx, %rcx
  5143. addq -16(%rbp), %rcx
  5144. negq %rbx
  5145. movq %rcx, %rax
  5146. addq %rbx, %rax
  5147. jmp conclusion
  5148. .globl main
  5149. main:
  5150. pushq %rbp
  5151. movq %rsp, %rbp
  5152. pushq %rbx
  5153. subq $8, %rsp
  5154. jmp start
  5155. conclusion:
  5156. addq $8, %rsp
  5157. popq %rbx
  5158. popq %rbp
  5159. retq
  5160. \end{lstlisting}
  5161. \fi}
  5162. {\if\edition\pythonEd
  5163. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5164. \begin{lstlisting}
  5165. .globl main
  5166. main:
  5167. pushq %rbp
  5168. movq %rsp, %rbp
  5169. pushq %rbx
  5170. subq $8, %rsp
  5171. movq $1, %rcx
  5172. movq $42, %rbx
  5173. addq $7, %rcx
  5174. movq %rcx, -16(%rbp)
  5175. addq %rbx, -16(%rbp)
  5176. negq %rcx
  5177. movq -16(%rbp), %rbx
  5178. addq %rcx, %rbx
  5179. movq %rbx, %rdi
  5180. callq print_int
  5181. addq $8, %rsp
  5182. popq %rbx
  5183. popq %rbp
  5184. retq
  5185. \end{lstlisting}
  5186. \fi}
  5187. \caption{The x86 output from the running example
  5188. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5189. and \code{rcx}.}
  5190. \label{fig:running-example-x86}
  5191. \end{figure}
  5192. \begin{exercise}\normalfont
  5193. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5194. %
  5195. \racket{
  5196. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5197. list of passes and the call to \code{compiler-tests}.}
  5198. %
  5199. Run the script to test the complete compiler for \LangVar{} that
  5200. performs register allocation.
  5201. \end{exercise}
  5202. \section{Challenge: Move Biasing}
  5203. \label{sec:move-biasing}
  5204. \index{subject}{move biasing}
  5205. This section describes an enhancement to the register allocator,
  5206. called move biasing, for students who are looking for an extra
  5207. challenge.
  5208. {\if\edition\racketEd
  5209. To motivate the need for move biasing we return to the running example
  5210. but this time use all of the general purpose registers. So we have
  5211. the following mapping of color numbers to registers.
  5212. \[
  5213. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5214. \]
  5215. Using the same assignment of variables to color numbers that was
  5216. produced by the register allocator described in the last section, we
  5217. get the following program.
  5218. \begin{center}
  5219. \begin{minipage}{0.3\textwidth}
  5220. \begin{lstlisting}
  5221. movq $1, v
  5222. movq $42, w
  5223. movq v, x
  5224. addq $7, x
  5225. movq x, y
  5226. movq x, z
  5227. addq w, z
  5228. movq y, t
  5229. negq t
  5230. movq z, %rax
  5231. addq t, %rax
  5232. jmp conclusion
  5233. \end{lstlisting}
  5234. \end{minipage}
  5235. $\Rightarrow\qquad$
  5236. \begin{minipage}{0.45\textwidth}
  5237. \begin{lstlisting}
  5238. movq $1, %rdx
  5239. movq $42, %rcx
  5240. movq %rdx, %rdx
  5241. addq $7, %rdx
  5242. movq %rdx, %rsi
  5243. movq %rdx, %rdx
  5244. addq %rcx, %rdx
  5245. movq %rsi, %rcx
  5246. negq %rcx
  5247. movq %rdx, %rax
  5248. addq %rcx, %rax
  5249. jmp conclusion
  5250. \end{lstlisting}
  5251. \end{minipage}
  5252. \end{center}
  5253. In the above output code there are two \key{movq} instructions that
  5254. can be removed because their source and target are the same. However,
  5255. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5256. register, we could instead remove three \key{movq} instructions. We
  5257. can accomplish this by taking into account which variables appear in
  5258. \key{movq} instructions with which other variables.
  5259. \fi}
  5260. {\if\edition\pythonEd
  5261. %
  5262. To motivate the need for move biasing we return to the running example
  5263. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5264. remove three trivial move instructions from the running
  5265. example. However, we could remove another trivial move if we were able
  5266. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5267. We say that two variables $p$ and $q$ are \emph{move
  5268. related}\index{subject}{move related} if they participate together in
  5269. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5270. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5271. when there are multiple variables with the same saturation, prefer
  5272. variables that can be assigned to a color that is the same as the
  5273. color of a move related variable. Furthermore, when the register
  5274. allocator chooses a color for a variable, it should prefer a color
  5275. that has already been used for a move-related variable (assuming that
  5276. they do not interfere). Of course, this preference should not override
  5277. the preference for registers over stack locations. So this preference
  5278. should be used as a tie breaker when choosing between registers or
  5279. when choosing between stack locations.
  5280. We recommend representing the move relationships in a graph, similar
  5281. to how we represented interference. The following is the \emph{move
  5282. graph} for our running example.
  5283. {\if\edition\racketEd
  5284. \[
  5285. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5286. \node (rax) at (0,0) {$\ttm{rax}$};
  5287. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5288. \node (t) at (0,2) {$\ttm{t}$};
  5289. \node (z) at (3,2) {$\ttm{z}$};
  5290. \node (x) at (6,2) {$\ttm{x}$};
  5291. \node (y) at (3,0) {$\ttm{y}$};
  5292. \node (w) at (6,0) {$\ttm{w}$};
  5293. \node (v) at (9,0) {$\ttm{v}$};
  5294. \draw (v) to (x);
  5295. \draw (x) to (y);
  5296. \draw (x) to (z);
  5297. \draw (y) to (t);
  5298. \end{tikzpicture}
  5299. \]
  5300. \fi}
  5301. %
  5302. {\if\edition\pythonEd
  5303. \[
  5304. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5305. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5306. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5307. \node (z) at (3,2) {$\ttm{z}$};
  5308. \node (x) at (6,2) {$\ttm{x}$};
  5309. \node (y) at (3,0) {$\ttm{y}$};
  5310. \node (w) at (6,0) {$\ttm{w}$};
  5311. \node (v) at (9,0) {$\ttm{v}$};
  5312. \draw (y) to (t0);
  5313. \draw (z) to (x);
  5314. \draw (z) to (t1);
  5315. \draw (x) to (y);
  5316. \draw (x) to (v);
  5317. \end{tikzpicture}
  5318. \]
  5319. \fi}
  5320. {\if\edition\racketEd
  5321. Now we replay the graph coloring, pausing to see the coloring of
  5322. \code{y}. Recall the following configuration. The most saturated vertices
  5323. were \code{w} and \code{y}.
  5324. \[
  5325. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5326. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5327. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5328. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5329. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5330. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5331. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5332. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5333. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5334. \draw (t1) to (rax);
  5335. \draw (t1) to (z);
  5336. \draw (z) to (y);
  5337. \draw (z) to (w);
  5338. \draw (x) to (w);
  5339. \draw (y) to (w);
  5340. \draw (v) to (w);
  5341. \draw (v) to (rsp);
  5342. \draw (w) to (rsp);
  5343. \draw (x) to (rsp);
  5344. \draw (y) to (rsp);
  5345. \path[-.,bend left=15] (z) edge node {} (rsp);
  5346. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5347. \draw (rax) to (rsp);
  5348. \end{tikzpicture}
  5349. \]
  5350. %
  5351. Last time we chose to color \code{w} with $0$. But this time we see
  5352. that \code{w} is not move related to any vertex, but \code{y} is move
  5353. related to \code{t}. So we choose to color \code{y} the same color as
  5354. \code{t}, $0$.
  5355. \[
  5356. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5357. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5358. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5359. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5360. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5361. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5362. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5363. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5364. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5365. \draw (t1) to (rax);
  5366. \draw (t1) to (z);
  5367. \draw (z) to (y);
  5368. \draw (z) to (w);
  5369. \draw (x) to (w);
  5370. \draw (y) to (w);
  5371. \draw (v) to (w);
  5372. \draw (v) to (rsp);
  5373. \draw (w) to (rsp);
  5374. \draw (x) to (rsp);
  5375. \draw (y) to (rsp);
  5376. \path[-.,bend left=15] (z) edge node {} (rsp);
  5377. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5378. \draw (rax) to (rsp);
  5379. \end{tikzpicture}
  5380. \]
  5381. Now \code{w} is the most saturated, so we color it $2$.
  5382. \[
  5383. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5384. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5385. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5386. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5387. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5388. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5389. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5390. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5391. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5392. \draw (t1) to (rax);
  5393. \draw (t1) to (z);
  5394. \draw (z) to (y);
  5395. \draw (z) to (w);
  5396. \draw (x) to (w);
  5397. \draw (y) to (w);
  5398. \draw (v) to (w);
  5399. \draw (v) to (rsp);
  5400. \draw (w) to (rsp);
  5401. \draw (x) to (rsp);
  5402. \draw (y) to (rsp);
  5403. \path[-.,bend left=15] (z) edge node {} (rsp);
  5404. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5405. \draw (rax) to (rsp);
  5406. \end{tikzpicture}
  5407. \]
  5408. At this point, vertices \code{x} and \code{v} are most saturated, but
  5409. \code{x} is move related to \code{y} and \code{z}, so we color
  5410. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5411. \[
  5412. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5413. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5414. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5415. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5416. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5417. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5418. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5419. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5420. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5421. \draw (t1) to (rax);
  5422. \draw (t) to (z);
  5423. \draw (z) to (y);
  5424. \draw (z) to (w);
  5425. \draw (x) to (w);
  5426. \draw (y) to (w);
  5427. \draw (v) to (w);
  5428. \draw (v) to (rsp);
  5429. \draw (w) to (rsp);
  5430. \draw (x) to (rsp);
  5431. \draw (y) to (rsp);
  5432. \path[-.,bend left=15] (z) edge node {} (rsp);
  5433. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5434. \draw (rax) to (rsp);
  5435. \end{tikzpicture}
  5436. \]
  5437. \fi}
  5438. %
  5439. {\if\edition\pythonEd
  5440. Now we replay the graph coloring, pausing before the coloring of
  5441. \code{w}. Recall the following configuration. The most saturated vertices
  5442. were \code{tmp\_1}, \code{w}, and \code{y}.
  5443. \[
  5444. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5445. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5446. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5447. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5448. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5449. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5450. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5451. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5452. \draw (t0) to (t1);
  5453. \draw (t0) to (z);
  5454. \draw (z) to (y);
  5455. \draw (z) to (w);
  5456. \draw (x) to (w);
  5457. \draw (y) to (w);
  5458. \draw (v) to (w);
  5459. \end{tikzpicture}
  5460. \]
  5461. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5462. or \code{y}, but note that \code{w} is not move related to any
  5463. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5464. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5465. \code{y} and color it $0$, we can delete another move instruction.
  5466. \[
  5467. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5468. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5469. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5470. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5471. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5472. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5473. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5474. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5475. \draw (t0) to (t1);
  5476. \draw (t0) to (z);
  5477. \draw (z) to (y);
  5478. \draw (z) to (w);
  5479. \draw (x) to (w);
  5480. \draw (y) to (w);
  5481. \draw (v) to (w);
  5482. \end{tikzpicture}
  5483. \]
  5484. Now \code{w} is the most saturated, so we color it $2$.
  5485. \[
  5486. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5487. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5488. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5489. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5490. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5491. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5492. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5493. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5494. \draw (t0) to (t1);
  5495. \draw (t0) to (z);
  5496. \draw (z) to (y);
  5497. \draw (z) to (w);
  5498. \draw (x) to (w);
  5499. \draw (y) to (w);
  5500. \draw (v) to (w);
  5501. \end{tikzpicture}
  5502. \]
  5503. To finish the coloring, \code{x} and \code{v} get $0$ and
  5504. \code{tmp\_1} gets $1$.
  5505. \[
  5506. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5507. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5508. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5509. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5510. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5511. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5512. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5513. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5514. \draw (t0) to (t1);
  5515. \draw (t0) to (z);
  5516. \draw (z) to (y);
  5517. \draw (z) to (w);
  5518. \draw (x) to (w);
  5519. \draw (y) to (w);
  5520. \draw (v) to (w);
  5521. \end{tikzpicture}
  5522. \]
  5523. \fi}
  5524. So we have the following assignment of variables to registers.
  5525. {\if\edition\racketEd
  5526. \begin{gather*}
  5527. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5528. \ttm{w} \mapsto \key{\%rsi}, \,
  5529. \ttm{x} \mapsto \key{\%rcx}, \,
  5530. \ttm{y} \mapsto \key{\%rcx}, \,
  5531. \ttm{z} \mapsto \key{\%rdx}, \,
  5532. \ttm{t} \mapsto \key{\%rcx} \}
  5533. \end{gather*}
  5534. \fi}
  5535. {\if\edition\pythonEd
  5536. \begin{gather*}
  5537. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5538. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5539. \ttm{x} \mapsto \key{\%rcx}, \,
  5540. \ttm{y} \mapsto \key{\%rcx}, \\
  5541. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5542. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5543. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5544. \end{gather*}
  5545. \fi}
  5546. We apply this register assignment to the running example, on the left,
  5547. to obtain the code in the middle. The \code{patch\_instructions} then
  5548. deletes the trivial moves to obtain the code on the right.
  5549. {\if\edition\racketEd
  5550. \begin{minipage}{0.25\textwidth}
  5551. \begin{lstlisting}
  5552. movq $1, v
  5553. movq $42, w
  5554. movq v, x
  5555. addq $7, x
  5556. movq x, y
  5557. movq x, z
  5558. addq w, z
  5559. movq y, t
  5560. negq t
  5561. movq z, %rax
  5562. addq t, %rax
  5563. jmp conclusion
  5564. \end{lstlisting}
  5565. \end{minipage}
  5566. $\Rightarrow\qquad$
  5567. \begin{minipage}{0.25\textwidth}
  5568. \begin{lstlisting}
  5569. movq $1, %rcx
  5570. movq $42, %rsi
  5571. movq %rcx, %rcx
  5572. addq $7, %rcx
  5573. movq %rcx, %rcx
  5574. movq %rcx, %rdx
  5575. addq %rsi, %rdx
  5576. movq %rcx, %rcx
  5577. negq %rcx
  5578. movq %rdx, %rax
  5579. addq %rcx, %rax
  5580. jmp conclusion
  5581. \end{lstlisting}
  5582. \end{minipage}
  5583. $\Rightarrow\qquad$
  5584. \begin{minipage}{0.25\textwidth}
  5585. \begin{lstlisting}
  5586. movq $1, %rcx
  5587. movq $42, %rsi
  5588. addq $7, %rcx
  5589. movq %rcx, %rdx
  5590. addq %rsi, %rdx
  5591. negq %rcx
  5592. movq %rdx, %rax
  5593. addq %rcx, %rax
  5594. jmp conclusion
  5595. \end{lstlisting}
  5596. \end{minipage}
  5597. \fi}
  5598. {\if\edition\pythonEd
  5599. \begin{minipage}{0.20\textwidth}
  5600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5601. movq $1, v
  5602. movq $42, w
  5603. movq v, x
  5604. addq $7, x
  5605. movq x, y
  5606. movq x, z
  5607. addq w, z
  5608. movq y, tmp_0
  5609. negq tmp_0
  5610. movq z, tmp_1
  5611. addq tmp_0, tmp_1
  5612. movq tmp_1, %rdi
  5613. callq _print_int
  5614. \end{lstlisting}
  5615. \end{minipage}
  5616. ${\Rightarrow\qquad}$
  5617. \begin{minipage}{0.30\textwidth}
  5618. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5619. movq $1, %rcx
  5620. movq $42, -16(%rbp)
  5621. movq %rcx, %rcx
  5622. addq $7, %rcx
  5623. movq %rcx, %rcx
  5624. movq %rcx, -8(%rbp)
  5625. addq -16(%rbp), -8(%rbp)
  5626. movq %rcx, %rcx
  5627. negq %rcx
  5628. movq -8(%rbp), -8(%rbp)
  5629. addq %rcx, -8(%rbp)
  5630. movq -8(%rbp), %rdi
  5631. callq _print_int
  5632. \end{lstlisting}
  5633. \end{minipage}
  5634. ${\Rightarrow\qquad}$
  5635. \begin{minipage}{0.20\textwidth}
  5636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5637. movq $1, %rcx
  5638. movq $42, -16(%rbp)
  5639. addq $7, %rcx
  5640. movq %rcx, -8(%rbp)
  5641. movq -16(%rbp), %rax
  5642. addq %rax, -8(%rbp)
  5643. negq %rcx
  5644. addq %rcx, -8(%rbp)
  5645. movq -8(%rbp), %rdi
  5646. callq print_int
  5647. \end{lstlisting}
  5648. \end{minipage}
  5649. \fi}
  5650. \begin{exercise}\normalfont
  5651. Change your implementation of \code{allocate\_registers} to take move
  5652. biasing into account. Create two new tests that include at least one
  5653. opportunity for move biasing and visually inspect the output x86
  5654. programs to make sure that your move biasing is working properly. Make
  5655. sure that your compiler still passes all of the tests.
  5656. \end{exercise}
  5657. %To do: another neat challenge would be to do
  5658. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5659. %% \subsection{Output of the Running Example}
  5660. %% \label{sec:reg-alloc-output}
  5661. % challenge: prioritize variables based on execution frequencies
  5662. % and the number of uses of a variable
  5663. % challenge: enhance the coloring algorithm using Chaitin's
  5664. % approach of prioritizing high-degree variables
  5665. % by removing low-degree variables (coloring them later)
  5666. % from the interference graph
  5667. \section{Further Reading}
  5668. \label{sec:register-allocation-further-reading}
  5669. Early register allocation algorithms were developed for Fortran
  5670. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5671. of graph coloring began in the late 1970s and early 1980s with the
  5672. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5673. algorithm is based on the following observation of
  5674. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5675. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5676. $v$ removed is also $k$ colorable. To see why, suppose that the
  5677. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5678. different colors, but since there are less than $k$ neighbors, there
  5679. will be one or more colors left over to use for coloring $v$ in $G$.
  5680. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5681. less than $k$ from the graph and recursively colors the rest of the
  5682. graph. Upon returning from the recursion, it colors $v$ with one of
  5683. the available colors and returns. \citet{Chaitin:1982vn} augments
  5684. this algorithm to handle spilling as follows. If there are no vertices
  5685. of degree lower than $k$ then pick a vertex at random, spill it,
  5686. remove it from the graph, and proceed recursively to color the rest of
  5687. the graph.
  5688. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5689. move-related and that don't interfere with each other, a process
  5690. called \emph{coalescing}. While coalescing decreases the number of
  5691. moves, it can make the graph more difficult to
  5692. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5693. which two variables are merged only if they have fewer than $k$
  5694. neighbors of high degree. \citet{George:1996aa} observe that
  5695. conservative coalescing is sometimes too conservative and make it more
  5696. aggressive by iterating the coalescing with the removal of low-degree
  5697. vertices.
  5698. %
  5699. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5700. also propose \emph{biased coloring} in which a variable is assigned to
  5701. the same color as another move-related variable if possible, as
  5702. discussed in Section~\ref{sec:move-biasing}.
  5703. %
  5704. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5705. performs coalescing, graph coloring, and spill code insertion until
  5706. all variables have been assigned a location.
  5707. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5708. spills variables that don't have to be: a high-degree variable can be
  5709. colorable if many of its neighbors are assigned the same color.
  5710. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5711. high-degree vertex is not immediately spilled. Instead the decision is
  5712. deferred until after the recursive call, at which point it is apparent
  5713. whether there is actually an available color or not. We observe that
  5714. this algorithm is equivalent to the smallest-last ordering
  5715. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5716. be registers and the rest to be stack locations.
  5717. %% biased coloring
  5718. Earlier editions of the compiler course at Indiana University
  5719. \citep{Dybvig:2010aa} were based on the algorithm of
  5720. \citet{Briggs:1994kx}.
  5721. The smallest-last ordering algorithm is one of many \emph{greedy}
  5722. coloring algorithms. A greedy coloring algorithm visits all the
  5723. vertices in a particular order and assigns each one the first
  5724. available color. An \emph{offline} greedy algorithm chooses the
  5725. ordering up-front, prior to assigning colors. The algorithm of
  5726. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5727. ordering does not depend on the colors assigned. Other orderings are
  5728. possible. For example, \citet{Chow:1984ys} order variables according
  5729. to an estimate of runtime cost.
  5730. An \emph{online} greedy coloring algorithm uses information about the
  5731. current assignment of colors to influence the order in which the
  5732. remaining vertices are colored. The saturation-based algorithm
  5733. described in this chapter is one such algorithm. We choose to use
  5734. saturation-based coloring because it is fun to introduce graph
  5735. coloring via Sudoku!
  5736. A register allocator may choose to map each variable to just one
  5737. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5738. variable to one or more locations. The later can be achieved by
  5739. \emph{live range splitting}, where a variable is replaced by several
  5740. variables that each handle part of its live
  5741. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5742. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5743. %% replacement algorithm, bottom-up local
  5744. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5745. %% Cooper: top-down (priority bassed), bottom-up
  5746. %% top-down
  5747. %% order variables by priority (estimated cost)
  5748. %% caveat: split variables into two groups:
  5749. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5750. %% color the constrained ones first
  5751. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5752. %% cite J. Cocke for an algorithm that colors variables
  5753. %% in a high-degree first ordering
  5754. %Register Allocation via Usage Counts, Freiburghouse CACM
  5755. \citet{Palsberg:2007si} observe that many of the interference graphs
  5756. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5757. that is, every cycle with four or more edges has an edge which is not
  5758. part of the cycle but which connects two vertices on the cycle. Such
  5759. graphs can be optimally colored by the greedy algorithm with a vertex
  5760. ordering determined by maximum cardinality search.
  5761. In situations where compile time is of utmost importance, such as in
  5762. just-in-time compilers, graph coloring algorithms can be too expensive
  5763. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5764. appropriate.
  5765. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5766. \chapter{Booleans and Conditionals}
  5767. \label{ch:Lif}
  5768. \index{subject}{Boolean}
  5769. \index{subject}{control flow}
  5770. \index{subject}{conditional expression}
  5771. The \LangInt{} and \LangVar{} languages only have a single kind of
  5772. value, the integers. In this chapter we add a second kind of value,
  5773. the Booleans, to create the \LangIf{} language. The Boolean values
  5774. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5775. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5776. language includes several operations that involve Booleans (\key{and},
  5777. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5778. \key{if} expression \python{and statement}. With the addition of
  5779. \key{if}, programs can have non-trivial control flow which
  5780. %
  5781. \racket{impacts \code{explicate\_control} and liveness analysis}
  5782. %
  5783. \python{impacts liveness analysis and motivates a new pass named
  5784. \code{explicate\_control}}.
  5785. %
  5786. Also, because we now have two kinds of values, we need to handle
  5787. programs that apply an operation to the wrong kind of value, such as
  5788. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5789. There are two language design options for such situations. One option
  5790. is to signal an error and the other is to provide a wider
  5791. interpretation of the operation. \racket{The Racket
  5792. language}\python{Python} uses a mixture of these two options,
  5793. depending on the operation and the kind of value. For example, the
  5794. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5795. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5796. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5797. %
  5798. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5799. in Racket because \code{car} expects a pair.}
  5800. %
  5801. \python{On the other hand, \code{1[0]} results in a run-time error
  5802. in Python because an ``\code{int} object is not subscriptable''.}
  5803. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5804. design choices as \racket{Racket}\python{Python}, except much of the
  5805. error detection happens at compile time instead of run
  5806. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5807. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5808. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5809. Racket}\python{MyPy} reports a compile-time error
  5810. %
  5811. \racket{because Racket expects the type of the argument to be of the form
  5812. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5813. %
  5814. \python{stating that a ``value of type \code{int} is not indexable''.}
  5815. The \LangIf{} language performs type checking during compilation like
  5816. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5817. alternative choice, that is, a dynamically typed language like
  5818. \racket{Racket}\python{Python}.
  5819. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5820. for some operations we are more restrictive, for example, rejecting
  5821. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5822. This chapter is organized as follows. We begin by defining the syntax
  5823. and interpreter for the \LangIf{} language
  5824. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5825. checking and define a type checker for \LangIf{}
  5826. (Section~\ref{sec:type-check-Lif}).
  5827. %
  5828. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5829. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5830. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5831. %
  5832. The remaining sections of this chapter discuss how the addition of
  5833. Booleans and conditional control flow to the language requires changes
  5834. to the existing compiler passes and the addition of new ones. In
  5835. particular, we introduce the \code{shrink} pass to translates some
  5836. operators into others, thereby reducing the number of operators that
  5837. need to be handled in later passes.
  5838. %
  5839. The main event of this chapter is the \code{explicate\_control} pass
  5840. that is responsible for translating \code{if}'s into conditional
  5841. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5842. %
  5843. Regarding register allocation, there is the interesting question of
  5844. how to handle conditional \code{goto}'s during liveness analysis.
  5845. \section{The \LangIf{} Language}
  5846. \label{sec:lang-if}
  5847. The concrete syntax of the \LangIf{} language is defined in
  5848. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5849. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5850. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5851. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5852. operators to include
  5853. \begin{enumerate}
  5854. \item subtraction on integers,
  5855. \item the logical operators \key{and}, \key{or}, and \key{not},
  5856. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5857. for comparing integers or Booleans for equality, and
  5858. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5859. comparing integers.
  5860. \end{enumerate}
  5861. \racket{We reorganize the abstract syntax for the primitive
  5862. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5863. rule for all of them. This means that the grammar no longer checks
  5864. whether the arity of an operators matches the number of
  5865. arguments. That responsibility is moved to the type checker for
  5866. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5867. \begin{figure}[tp]
  5868. \centering
  5869. \fbox{
  5870. \begin{minipage}{0.96\textwidth}
  5871. {\if\edition\racketEd
  5872. \[
  5873. \begin{array}{lcl}
  5874. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5875. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5876. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5877. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5878. &\MID& \itm{bool}
  5879. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5880. \MID (\key{not}\;\Exp) \\
  5881. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5882. \LangIfM{} &::=& \Exp
  5883. \end{array}
  5884. \]
  5885. \fi}
  5886. {\if\edition\pythonEd
  5887. \[
  5888. \begin{array}{rcl}
  5889. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5890. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  5891. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{uniop}}{\Exp} \MID \CBINOP{\itm{binop}}{\Exp}{\Exp} \MID \Var{} \\
  5892. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5893. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  5894. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  5895. \LangIfM{} &::=& \Stmt^{*}
  5896. \end{array}
  5897. \]
  5898. \fi}
  5899. \end{minipage}
  5900. }
  5901. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5902. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  5903. \label{fig:Lif-concrete-syntax}
  5904. \end{figure}
  5905. \begin{figure}[tp]
  5906. \centering
  5907. \fbox{
  5908. \begin{minipage}{0.96\textwidth}
  5909. {\if\edition\racketEd
  5910. \[
  5911. \begin{array}{lcl}
  5912. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5913. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5914. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5915. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5916. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5917. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5918. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5919. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5920. \end{array}
  5921. \]
  5922. \fi}
  5923. {\if\edition\pythonEd
  5924. \[
  5925. \begin{array}{lcl}
  5926. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  5927. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5928. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5929. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  5930. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5931. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  5932. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  5933. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  5934. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  5935. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  5936. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5937. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  5938. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  5939. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  5940. \end{array}
  5941. \]
  5942. \fi}
  5943. \end{minipage}
  5944. }
  5945. \caption{The abstract syntax of \LangIf{}.}
  5946. \label{fig:Lif-syntax}
  5947. \end{figure}
  5948. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  5949. which inherits from the interpreter for \LangVar{}
  5950. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  5951. evaluate to the corresponding Boolean values. The conditional
  5952. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  5953. and then either evaluates $e_2$ or $e_3$ depending on whether
  5954. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  5955. \code{and}, \code{or}, and \code{not} behave according to propositional logic,
  5956. but note that the \code{and} and \code{or} operations are
  5957. short-circuiting.
  5958. %
  5959. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  5960. is not evaluated if $e_1$ evaluates to \FALSE{}.
  5961. %
  5962. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  5963. evaluated if $e_1$ evaluates to \TRUE{}.
  5964. \racket{With the increase in the number of primitive operations, the
  5965. interpreter would become repetitive without some care. We refactor
  5966. the case for \code{Prim}, moving the code that differs with each
  5967. operation into the \code{interp\_op} method shown in in
  5968. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  5969. \code{or} operations separately because of their short-circuiting
  5970. behavior.}
  5971. \begin{figure}[tbp]
  5972. {\if\edition\racketEd
  5973. \begin{lstlisting}
  5974. (define interp_Lif_class
  5975. (class interp_Lvar_class
  5976. (super-new)
  5977. (define/public (interp_op op) ...)
  5978. (define/override ((interp_exp env) e)
  5979. (define recur (interp_exp env))
  5980. (match e
  5981. [(Bool b) b]
  5982. [(If cnd thn els)
  5983. (match (recur cnd)
  5984. [#t (recur thn)]
  5985. [#f (recur els)])]
  5986. [(Prim 'and (list e1 e2))
  5987. (match (recur e1)
  5988. [#t (match (recur e2) [#t #t] [#f #f])]
  5989. [#f #f])]
  5990. [(Prim 'or (list e1 e2))
  5991. (define v1 (recur e1))
  5992. (match v1
  5993. [#t #t]
  5994. [#f (match (recur e2) [#t #t] [#f #f])])]
  5995. [(Prim op args)
  5996. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  5997. [else ((super interp_exp env) e)]))
  5998. ))
  5999. (define (interp_Lif p)
  6000. (send (new interp_Lif_class) interp_program p))
  6001. \end{lstlisting}
  6002. \fi}
  6003. {\if\edition\pythonEd
  6004. \begin{lstlisting}
  6005. class InterpLif(InterpLvar):
  6006. def interp_exp(self, e, env):
  6007. match e:
  6008. case IfExp(test, body, orelse):
  6009. if self.interp_exp(test, env):
  6010. return self.interp_exp(body, env)
  6011. else:
  6012. return self.interp_exp(orelse, env)
  6013. case BinOp(left, Sub(), right):
  6014. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6015. case UnaryOp(Not(), v):
  6016. return not self.interp_exp(v, env)
  6017. case BoolOp(And(), values):
  6018. if self.interp_exp(values[0], env):
  6019. return self.interp_exp(values[1], env)
  6020. else:
  6021. return False
  6022. case BoolOp(Or(), values):
  6023. if self.interp_exp(values[0], env):
  6024. return True
  6025. else:
  6026. return self.interp_exp(values[1], env)
  6027. case Compare(left, [cmp], [right]):
  6028. l = self.interp_exp(left, env)
  6029. r = self.interp_exp(right, env)
  6030. return self.interp_cmp(cmp)(l, r)
  6031. case _:
  6032. return super().interp_exp(e, env)
  6033. def interp_stmts(self, ss, env):
  6034. if len(ss) == 0:
  6035. return
  6036. match ss[0]:
  6037. case If(test, body, orelse):
  6038. if self.interp_exp(test, env):
  6039. return self.interp_stmts(body + ss[1:], env)
  6040. else:
  6041. return self.interp_stmts(orelse + ss[1:], env)
  6042. case _:
  6043. return super().interp_stmts(ss, env)
  6044. ...
  6045. \end{lstlisting}
  6046. \fi}
  6047. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6048. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6049. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6050. \label{fig:interp-Lif}
  6051. \end{figure}
  6052. {\if\edition\racketEd
  6053. \begin{figure}[tbp]
  6054. \begin{lstlisting}
  6055. (define/public (interp_op op)
  6056. (match op
  6057. ['+ fx+]
  6058. ['- fx-]
  6059. ['read read-fixnum]
  6060. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6061. ['eq? (lambda (v1 v2)
  6062. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6063. (and (boolean? v1) (boolean? v2))
  6064. (and (vector? v1) (vector? v2)))
  6065. (eq? v1 v2)]))]
  6066. ['< (lambda (v1 v2)
  6067. (cond [(and (fixnum? v1) (fixnum? v2))
  6068. (< v1 v2)]))]
  6069. ['<= (lambda (v1 v2)
  6070. (cond [(and (fixnum? v1) (fixnum? v2))
  6071. (<= v1 v2)]))]
  6072. ['> (lambda (v1 v2)
  6073. (cond [(and (fixnum? v1) (fixnum? v2))
  6074. (> v1 v2)]))]
  6075. ['>= (lambda (v1 v2)
  6076. (cond [(and (fixnum? v1) (fixnum? v2))
  6077. (>= v1 v2)]))]
  6078. [else (error 'interp_op "unknown operator")]))
  6079. \end{lstlisting}
  6080. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6081. \label{fig:interp-op-Lif}
  6082. \end{figure}
  6083. \fi}
  6084. {\if\edition\pythonEd
  6085. \begin{figure}
  6086. \begin{lstlisting}
  6087. class InterpLif(InterpLvar):
  6088. ...
  6089. def interp_cmp(self, cmp):
  6090. match cmp:
  6091. case Lt():
  6092. return lambda x, y: x < y
  6093. case LtE():
  6094. return lambda x, y: x <= y
  6095. case Gt():
  6096. return lambda x, y: x > y
  6097. case GtE():
  6098. return lambda x, y: x >= y
  6099. case Eq():
  6100. return lambda x, y: x == y
  6101. case NotEq():
  6102. return lambda x, y: x != y
  6103. \end{lstlisting}
  6104. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6105. \label{fig:interp-cmp-Lif}
  6106. \end{figure}
  6107. \fi}
  6108. \section{Type Checking \LangIf{} Programs}
  6109. \label{sec:type-check-Lif}
  6110. \index{subject}{type checking}
  6111. \index{subject}{semantic analysis}
  6112. It is helpful to think about type checking in two complementary
  6113. ways. A type checker predicts the type of value that will be produced
  6114. by each expression in the program. For \LangIf{}, we have just two types,
  6115. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6116. {\if\edition\racketEd
  6117. \begin{lstlisting}
  6118. (+ 10 (- (+ 12 20)))
  6119. \end{lstlisting}
  6120. \fi}
  6121. {\if\edition\pythonEd
  6122. \begin{lstlisting}
  6123. 10 + -(12 + 20)
  6124. \end{lstlisting}
  6125. \fi}
  6126. \noindent produces a value of type \INTTY{} while
  6127. {\if\edition\racketEd
  6128. \begin{lstlisting}
  6129. (and (not #f) #t)
  6130. \end{lstlisting}
  6131. \fi}
  6132. {\if\edition\pythonEd
  6133. \begin{lstlisting}
  6134. (not False) and True
  6135. \end{lstlisting}
  6136. \fi}
  6137. \noindent produces a value of type \BOOLTY{}.
  6138. A second way to think about type checking is that it enforces a set of
  6139. rules about which operators can be applied to which kinds of
  6140. values. For example, our type checker for \LangIf{} signals an error
  6141. for the below expression {\if\edition\racketEd
  6142. \begin{lstlisting}
  6143. (not (+ 10 (- (+ 12 20))))
  6144. \end{lstlisting}
  6145. \fi}
  6146. {\if\edition\pythonEd
  6147. \begin{lstlisting}
  6148. not (10 + -(12 + 20))
  6149. \end{lstlisting}
  6150. \fi}
  6151. The subexpression
  6152. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6153. has type \INTTY{} but the type checker enforces the rule that the argument of
  6154. \code{not} must be an expression of type \BOOLTY{}.
  6155. We implement type checking using classes and methods because they
  6156. provide the open recursion needed to reuse code as we extend the type
  6157. checker in later chapters, analogous to the use of classes and methods
  6158. for the interpreters (Section~\ref{sec:extensible-interp}).
  6159. We separate the type checker for the \LangVar{} subset into its own
  6160. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6161. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6162. from the type checker for \LangVar{}. These type checkers are in the
  6163. files
  6164. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6165. and
  6166. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6167. of the support code.
  6168. %
  6169. Each type checker is a structurally recursive function over the AST.
  6170. Given an input expression \code{e}, the type checker either signals an
  6171. error or returns \racket{an expression and} its type (\INTTY{} or
  6172. \BOOLTY{}).
  6173. %
  6174. \racket{It returns an expression because there are situations in which
  6175. we want to change or update the expression.}
  6176. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6177. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6178. \INTTY{}. To handle variables, the type checker uses the environment
  6179. \code{env} to map variables to types.
  6180. %
  6181. \racket{Consider the case for \key{let}. We type check the
  6182. initializing expression to obtain its type \key{T} and then
  6183. associate type \code{T} with the variable \code{x} in the
  6184. environment used to type check the body of the \key{let}. Thus,
  6185. when the type checker encounters a use of variable \code{x}, it can
  6186. find its type in the environment.}
  6187. %
  6188. \python{Consider the case for assignment. We type check the
  6189. initializing expression to obtain its type \key{t}. If the variable
  6190. \code{lhs.id} is already in the environment because there was a
  6191. prior assignment, we check that this initializer has the same type
  6192. as the prior one. If this is the first assignment to the variable,
  6193. we associate type \code{t} with the variable \code{lhs.id} in the
  6194. environment. Thus, when the type checker encounters a use of
  6195. variable \code{x}, it can find its type in the environment.}
  6196. %
  6197. \racket{Regarding primitive operators, we recursively analyze the
  6198. arguments and then invoke \code{type\_check\_op} to check whether
  6199. the argument types are allowed.}
  6200. %
  6201. \python{Regarding addition and negation, we recursively analyze the
  6202. arguments, check that they have type \INT{}, and return \INT{}.}
  6203. \racket{Several auxiliary methods are used in the type checker. The
  6204. method \code{operator-types} defines a dictionary that maps the
  6205. operator names to their parameter and return types. The
  6206. \code{type-equal?} method determines whether two types are equal,
  6207. which for now simply dispatches to \code{equal?} (deep
  6208. equality). The \code{check-type-equal?} method triggers an error if
  6209. the two types are not equal. The \code{type-check-op} method looks
  6210. up the operator in the \code{operator-types} dictionary and then
  6211. checks whether the argument types are equal to the parameter types.
  6212. The result is the return type of the operator.}
  6213. %
  6214. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6215. an error if the two types are not equal.}
  6216. \begin{figure}[tbp]
  6217. {\if\edition\racketEd
  6218. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6219. (define type-check-Lvar_class
  6220. (class object%
  6221. (super-new)
  6222. (define/public (operator-types)
  6223. '((+ . ((Integer Integer) . Integer))
  6224. (- . ((Integer) . Integer))
  6225. (read . (() . Integer))))
  6226. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6227. (define/public (check-type-equal? t1 t2 e)
  6228. (unless (type-equal? t1 t2)
  6229. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6230. (define/public (type-check-op op arg-types e)
  6231. (match (dict-ref (operator-types) op)
  6232. [`(,param-types . ,return-type)
  6233. (for ([at arg-types] [pt param-types])
  6234. (check-type-equal? at pt e))
  6235. return-type]
  6236. [else (error 'type-check-op "unrecognized ~a" op)]))
  6237. (define/public (type-check-exp env)
  6238. (lambda (e)
  6239. (match e
  6240. [(Int n) (values (Int n) 'Integer)]
  6241. [(Var x) (values (Var x) (dict-ref env x))]
  6242. [(Let x e body)
  6243. (define-values (e^ Te) ((type-check-exp env) e))
  6244. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6245. (values (Let x e^ b) Tb)]
  6246. [(Prim op es)
  6247. (define-values (new-es ts)
  6248. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6249. (values (Prim op new-es) (type-check-op op ts e))]
  6250. [else (error 'type-check-exp "couldn't match" e)])))
  6251. (define/public (type-check-program e)
  6252. (match e
  6253. [(Program info body)
  6254. (define-values (body^ Tb) ((type-check-exp '()) body))
  6255. (check-type-equal? Tb 'Integer body)
  6256. (Program info body^)]
  6257. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6258. ))
  6259. (define (type-check-Lvar p)
  6260. (send (new type-check-Lvar_class) type-check-program p))
  6261. \end{lstlisting}
  6262. \fi}
  6263. {\if\edition\pythonEd
  6264. \begin{lstlisting}
  6265. class TypeCheckLvar:
  6266. def check_type_equal(self, t1, t2, e):
  6267. if t1 != t2:
  6268. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6269. raise Exception(msg)
  6270. def type_check_exp(self, e, env):
  6271. match e:
  6272. case BinOp(left, Add(), right):
  6273. l = self.type_check_exp(left, env)
  6274. check_type_equal(l, int, left)
  6275. r = self.type_check_exp(right, env)
  6276. check_type_equal(r, int, right)
  6277. return int
  6278. case UnaryOp(USub(), v):
  6279. t = self.type_check_exp(v, env)
  6280. check_type_equal(t, int, v)
  6281. return int
  6282. case Name(id):
  6283. return env[id]
  6284. case Constant(value) if isinstance(value, int):
  6285. return int
  6286. case Call(Name('input_int'), []):
  6287. return int
  6288. def type_check_stmts(self, ss, env):
  6289. if len(ss) == 0:
  6290. return
  6291. match ss[0]:
  6292. case Assign([lhs], value):
  6293. t = self.type_check_exp(value, env)
  6294. if lhs.id in env:
  6295. check_type_equal(env[lhs.id], t, value)
  6296. else:
  6297. env[lhs.id] = t
  6298. return self.type_check_stmts(ss[1:], env)
  6299. case Expr(Call(Name('print'), [arg])):
  6300. t = self.type_check_exp(arg, env)
  6301. check_type_equal(t, int, arg)
  6302. return self.type_check_stmts(ss[1:], env)
  6303. case Expr(value):
  6304. self.type_check_exp(value, env)
  6305. return self.type_check_stmts(ss[1:], env)
  6306. def type_check_P(self, p):
  6307. match p:
  6308. case Module(body):
  6309. self.type_check_stmts(body, {})
  6310. \end{lstlisting}
  6311. \fi}
  6312. \caption{Type checker for the \LangVar{} language.}
  6313. \label{fig:type-check-Lvar}
  6314. \end{figure}
  6315. \begin{figure}[tbp]
  6316. {\if\edition\racketEd
  6317. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6318. (define type-check-Lif_class
  6319. (class type-check-Lvar_class
  6320. (super-new)
  6321. (inherit check-type-equal?)
  6322. (define/override (operator-types)
  6323. (append '((- . ((Integer Integer) . Integer))
  6324. (and . ((Boolean Boolean) . Boolean))
  6325. (or . ((Boolean Boolean) . Boolean))
  6326. (< . ((Integer Integer) . Boolean))
  6327. (<= . ((Integer Integer) . Boolean))
  6328. (> . ((Integer Integer) . Boolean))
  6329. (>= . ((Integer Integer) . Boolean))
  6330. (not . ((Boolean) . Boolean))
  6331. )
  6332. (super operator-types)))
  6333. (define/override (type-check-exp env)
  6334. (lambda (e)
  6335. (match e
  6336. [(Bool b) (values (Bool b) 'Boolean)]
  6337. [(Prim 'eq? (list e1 e2))
  6338. (define-values (e1^ T1) ((type-check-exp env) e1))
  6339. (define-values (e2^ T2) ((type-check-exp env) e2))
  6340. (check-type-equal? T1 T2 e)
  6341. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6342. [(If cnd thn els)
  6343. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6344. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6345. (define-values (els^ Te) ((type-check-exp env) els))
  6346. (check-type-equal? Tc 'Boolean e)
  6347. (check-type-equal? Tt Te e)
  6348. (values (If cnd^ thn^ els^) Te)]
  6349. [else ((super type-check-exp env) e)])))
  6350. ))
  6351. (define (type-check-Lif p)
  6352. (send (new type-check-Lif_class) type-check-program p))
  6353. \end{lstlisting}
  6354. \fi}
  6355. {\if\edition\pythonEd
  6356. \begin{lstlisting}
  6357. class TypeCheckLif(TypeCheckLvar):
  6358. def type_check_exp(self, e, env):
  6359. match e:
  6360. case Constant(value) if isinstance(value, bool):
  6361. return bool
  6362. case BinOp(left, Sub(), right):
  6363. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6364. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6365. return int
  6366. case UnaryOp(Not(), v):
  6367. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6368. return bool
  6369. case BoolOp(op, values):
  6370. left = values[0] ; right = values[1]
  6371. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6372. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6373. return bool
  6374. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6375. or isinstance(cmp, NotEq):
  6376. l = self.type_check_exp(left, env)
  6377. r = self.type_check_exp(right, env)
  6378. check_type_equal(l, r, e)
  6379. return bool
  6380. case Compare(left, [cmp], [right]):
  6381. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6382. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6383. return bool
  6384. case IfExp(test, body, orelse):
  6385. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6386. b = self.type_check_exp(body, env)
  6387. o = self.type_check_exp(orelse, env)
  6388. check_type_equal(b, o, e)
  6389. return b
  6390. case _:
  6391. return super().type_check_exp(e, env)
  6392. def type_check_stmts(self, ss, env):
  6393. if len(ss) == 0:
  6394. return
  6395. match ss[0]:
  6396. case If(test, body, orelse):
  6397. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6398. b = self.type_check_stmts(body, env)
  6399. o = self.type_check_stmts(orelse, env)
  6400. check_type_equal(b, o, ss[0])
  6401. return self.type_check_stmts(ss[1:], env)
  6402. case _:
  6403. return super().type_check_stmts(ss, env)
  6404. \end{lstlisting}
  6405. \fi}
  6406. \caption{Type checker for the \LangIf{} language.}
  6407. \label{fig:type-check-Lif}
  6408. \end{figure}
  6409. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6410. checker for \LangIf{}.
  6411. %
  6412. The type of a Boolean constant is \BOOLTY{}.
  6413. %
  6414. \racket{The \code{operator-types} function adds dictionary entries for
  6415. the other new operators.}
  6416. %
  6417. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6418. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6419. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6420. %
  6421. The equality operators requires the two arguments to have the same
  6422. type.
  6423. %
  6424. \python{The other comparisons (less-than, etc.) require their
  6425. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6426. %
  6427. The condition of an \code{if} must
  6428. be of \BOOLTY{} type and the two branches must have the same type.
  6429. \begin{exercise}\normalfont
  6430. Create 10 new test programs in \LangIf{}. Half of the programs should
  6431. have a type error. For those programs, create an empty file with the
  6432. same base name but with file extension \code{.tyerr}. For example, if
  6433. the test
  6434. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6435. is expected to error, then create
  6436. an empty file named \code{cond\_test\_14.tyerr}.
  6437. %
  6438. \racket{This indicates to \code{interp-tests} and
  6439. \code{compiler-tests} that a type error is expected. }
  6440. %
  6441. \racket{This indicates to the \code{run-tests.rkt} scripts that a type
  6442. error is expected.}
  6443. %
  6444. The other half of the test programs should not have type errors.
  6445. %
  6446. \racket{In the \code{run-tests.rkt} script, change the second argument
  6447. of \code{interp-tests} and \code{compiler-tests} to
  6448. \code{type-check-Lif}, which causes the type checker to run prior to
  6449. the compiler passes. Temporarily change the \code{passes} to an
  6450. empty list and run the script, thereby checking that the new test
  6451. programs either type check or not as intended.}
  6452. %
  6453. Run the test script to check that these test programs type check as
  6454. expected.
  6455. \end{exercise}
  6456. \clearpage
  6457. \section{The \LangCIf{} Intermediate Language}
  6458. \label{sec:Cif}
  6459. {\if\edition\racketEd
  6460. %
  6461. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6462. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6463. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6464. language adds logical and comparison operators to the \Exp{}
  6465. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6466. non-terminal.
  6467. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6468. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6469. statement is a comparison operation and the branches are \code{goto}
  6470. statements, making it straightforward to compile \code{if} statements
  6471. to x86.
  6472. %
  6473. \fi}
  6474. %
  6475. {\if\edition\pythonEd
  6476. %
  6477. The output of \key{explicate\_control} is a language similar to the
  6478. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6479. \code{goto} statements, so we name it \LangCIf{}. The
  6480. concrete syntax for \LangCIf{} is defined in
  6481. Figure~\ref{fig:c1-concrete-syntax}
  6482. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6483. %
  6484. The \LangCIf{} language supports the same operators as \LangIf{} but
  6485. the arguments of operators are restricted to atomic expressions. The
  6486. \LangCIf{} language does not include \code{if} expressions but it does
  6487. include a restricted form of \code{if} statment. The condition must be
  6488. a comparison and the two branches may only contain \code{goto}
  6489. statements. These restrictions make it easier to translate \code{if}
  6490. statements to x86.
  6491. %
  6492. \fi}
  6493. %
  6494. The \key{CProgram} construct contains
  6495. %
  6496. \racket{an alist}\python{a dictionary}
  6497. %
  6498. mapping labels to $\Tail$ expressions, which can be return statements,
  6499. an assignment statement followed by a $\Tail$ expression, a
  6500. \code{goto}, or a conditional \code{goto}.
  6501. \begin{figure}[tbp]
  6502. \fbox{
  6503. \begin{minipage}{0.96\textwidth}
  6504. \small
  6505. \[
  6506. \begin{array}{lcl}
  6507. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  6508. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6509. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  6510. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6511. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  6512. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  6513. \MID \key{goto}~\itm{label}\key{;}\\
  6514. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  6515. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  6516. \end{array}
  6517. \]
  6518. \end{minipage}
  6519. }
  6520. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6521. \label{fig:c1-concrete-syntax}
  6522. \end{figure}
  6523. \begin{figure}[tp]
  6524. \fbox{
  6525. \begin{minipage}{0.96\textwidth}
  6526. \small
  6527. {\if\edition\racketEd
  6528. \[
  6529. \begin{array}{lcl}
  6530. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6531. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6532. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6533. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6534. &\MID& \UNIOP{\key{'not}}{\Atm}
  6535. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6536. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6537. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6538. \MID \GOTO{\itm{label}} \\
  6539. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6540. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6541. \end{array}
  6542. \]
  6543. \fi}
  6544. {\if\edition\pythonEd
  6545. \[
  6546. \begin{array}{lcl}
  6547. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6548. \Exp &::= & \Atm \MID \READ{} \\
  6549. &\MID& \BINOP{\Atm}{\itm{binop}}{\Atm}
  6550. \MID \UNIOP{\itm{uniop}}{\Atm} \\
  6551. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6552. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6553. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6554. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6555. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6556. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6557. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  6558. \end{array}
  6559. \]
  6560. \fi}
  6561. \end{minipage}
  6562. }
  6563. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6564. (Figure~\ref{fig:c0-syntax})}.}
  6565. \label{fig:c1-syntax}
  6566. \end{figure}
  6567. \section{The \LangXIf{} Language}
  6568. \label{sec:x86-if}
  6569. \index{subject}{x86} To implement the new logical operations, the comparison
  6570. operations, and the \key{if} expression, we need to delve further into
  6571. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6572. define the concrete and abstract syntax for the \LangXIf{} subset
  6573. of x86, which includes instructions for logical operations,
  6574. comparisons, and \racket{conditional} jumps.
  6575. One challenge is that x86 does not provide an instruction that
  6576. directly implements logical negation (\code{not} in \LangIf{} and
  6577. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6578. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6579. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6580. bit of its arguments, and writes the results into its second argument.
  6581. Recall the truth table for exclusive-or:
  6582. \begin{center}
  6583. \begin{tabular}{l|cc}
  6584. & 0 & 1 \\ \hline
  6585. 0 & 0 & 1 \\
  6586. 1 & 1 & 0
  6587. \end{tabular}
  6588. \end{center}
  6589. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6590. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6591. for the bit $1$, the result is the opposite of the second bit. Thus,
  6592. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6593. the first argument as follows, where $\Arg$ is the translation of
  6594. $\Atm$.
  6595. \[
  6596. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6597. \qquad\Rightarrow\qquad
  6598. \begin{array}{l}
  6599. \key{movq}~ \Arg\key{,} \Var\\
  6600. \key{xorq}~ \key{\$1,} \Var
  6601. \end{array}
  6602. \]
  6603. \begin{figure}[tp]
  6604. \fbox{
  6605. \begin{minipage}{0.96\textwidth}
  6606. \[
  6607. \begin{array}{lcl}
  6608. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6609. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6610. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6611. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6612. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6613. \key{subq} \; \Arg\key{,} \Arg \MID
  6614. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6615. && \gray{ \key{callq} \; \itm{label} \MID
  6616. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6617. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6618. \MID \key{xorq}~\Arg\key{,}~\Arg
  6619. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6620. && \key{set}cc~\Arg
  6621. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6622. \MID \key{j}cc~\itm{label}
  6623. \\
  6624. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6625. & & \gray{ \key{main:} \; \Instr\ldots }
  6626. \end{array}
  6627. \]
  6628. \end{minipage}
  6629. }
  6630. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6631. \label{fig:x86-1-concrete}
  6632. \end{figure}
  6633. \begin{figure}[tp]
  6634. \fbox{
  6635. \begin{minipage}{0.98\textwidth}
  6636. \small
  6637. {\if\edition\racketEd
  6638. \[
  6639. \begin{array}{lcl}
  6640. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6641. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6642. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6643. \MID \BYTEREG{\itm{bytereg}} \\
  6644. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6645. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6646. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6647. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6648. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6649. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6650. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6651. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6652. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6653. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6654. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6655. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6656. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6657. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6658. \end{array}
  6659. \]
  6660. \fi}
  6661. %
  6662. {\if\edition\pythonEd
  6663. \[
  6664. \begin{array}{lcl}
  6665. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6666. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6667. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6668. \MID \BYTEREG{\itm{bytereg}} \\
  6669. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6670. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6671. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6672. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6673. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6674. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6675. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6676. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6677. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6678. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6679. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6680. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6681. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6682. \end{array}
  6683. \]
  6684. \fi}
  6685. \end{minipage}
  6686. }
  6687. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6688. \label{fig:x86-1}
  6689. \end{figure}
  6690. Next we consider the x86 instructions that are relevant for compiling
  6691. the comparison operations. The \key{cmpq} instruction compares its two
  6692. arguments to determine whether one argument is less than, equal, or
  6693. greater than the other argument. The \key{cmpq} instruction is unusual
  6694. regarding the order of its arguments and where the result is
  6695. placed. The argument order is backwards: if you want to test whether
  6696. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6697. \key{cmpq} is placed in the special EFLAGS register. This register
  6698. cannot be accessed directly but it can be queried by a number of
  6699. instructions, including the \key{set} instruction. The instruction
  6700. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6701. depending on whether the comparison comes out according to the
  6702. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6703. for less-or-equal, \key{g} for greater, \key{ge} for
  6704. greater-or-equal). The \key{set} instruction has a quirk in
  6705. that its destination argument must be single byte register, such as
  6706. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6707. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6708. instruction can be used to move from a single byte register to a
  6709. normal 64-bit register. The abstract syntax for the \code{set}
  6710. instruction differs from the concrete syntax in that it separates the
  6711. instruction name from the condition code.
  6712. \python{The x86 instructions for jumping are relevant to the
  6713. compilation of \key{if} expressions.}
  6714. %
  6715. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6716. counter to the address of the instruction after the specified
  6717. label.}
  6718. %
  6719. \racket{The x86 instruction for conditional jump is relevant to the
  6720. compilation of \key{if} expressions.}
  6721. %
  6722. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6723. counter to point to the instruction after \itm{label} depending on
  6724. whether the result in the EFLAGS register matches the condition code
  6725. \itm{cc}, otherwise the jump instruction falls through to the next
  6726. instruction. Like the abstract syntax for \code{set}, the abstract
  6727. syntax for conditional jump separates the instruction name from the
  6728. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6729. to \code{jle foo}. Because the conditional jump instruction relies on
  6730. the EFLAGS register, it is common for it to be immediately preceded by
  6731. a \key{cmpq} instruction to set the EFLAGS register.
  6732. \section{Shrink the \LangIf{} Language}
  6733. \label{sec:shrink-Lif}
  6734. The \LangIf{} language includes several features that are easily
  6735. expressible with other features. For example, \code{and} and \code{or}
  6736. are expressible using \code{if} as follows.
  6737. \begin{align*}
  6738. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6739. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6740. \end{align*}
  6741. By performing these translations in the front-end of the compiler, the
  6742. later passes of the compiler do not need to deal with these features,
  6743. making the passes shorter.
  6744. %% For example, subtraction is
  6745. %% expressible using addition and negation.
  6746. %% \[
  6747. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6748. %% \]
  6749. %% Several of the comparison operations are expressible using less-than
  6750. %% and logical negation.
  6751. %% \[
  6752. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6753. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6754. %% \]
  6755. %% The \key{let} is needed in the above translation to ensure that
  6756. %% expression $e_1$ is evaluated before $e_2$.
  6757. On the other hand, sometimes translations reduce the efficiency of the
  6758. generated code by increasing the number of instructions. For example,
  6759. expressing subtraction in terms of negation
  6760. \[
  6761. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6762. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6763. \]
  6764. produces code with two x86 instructions (\code{negq} and \code{addq})
  6765. instead of just one (\code{subq}).
  6766. %% However,
  6767. %% these differences typically do not affect the number of accesses to
  6768. %% memory, which is the primary factor that determines execution time on
  6769. %% modern computer architectures.
  6770. \begin{exercise}\normalfont
  6771. %
  6772. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6773. the language by translating them to \code{if} expressions in \LangIf{}.
  6774. %
  6775. Create four test programs that involve these operators.
  6776. %
  6777. {\if\edition\racketEd
  6778. In the \code{run-tests.rkt} script, add the following entry for
  6779. \code{shrink} to the list of passes (it should be the only pass at
  6780. this point).
  6781. \begin{lstlisting}
  6782. (list "shrink" shrink interp_Lif type-check-Lif)
  6783. \end{lstlisting}
  6784. This instructs \code{interp-tests} to run the intepreter
  6785. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6786. output of \code{shrink}.
  6787. \fi}
  6788. %
  6789. Run the script to test your compiler on all the test programs.
  6790. \end{exercise}
  6791. {\if\edition\racketEd
  6792. \section{Uniquify Variables}
  6793. \label{sec:uniquify-Lif}
  6794. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6795. \code{if} expressions.
  6796. \begin{exercise}\normalfont
  6797. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6798. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6799. \begin{lstlisting}
  6800. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6801. \end{lstlisting}
  6802. Run the script to test your compiler.
  6803. \end{exercise}
  6804. \fi}
  6805. \section{Remove Complex Operands}
  6806. \label{sec:remove-complex-opera-Lif}
  6807. The output language of \code{remove\_complex\_operands} is
  6808. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  6809. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  6810. but the \code{if} expression is not. All three sub-expressions of an
  6811. \code{if} are allowed to be complex expressions but the operands of
  6812. \code{not} and the comparisons must be atomic.
  6813. %
  6814. \python{We add a new language form, the \code{Let} expression, to aid
  6815. in the translation of \code{if} expressions. When we recursively
  6816. process the two branches of the \code{if}, we generate temporary
  6817. variables and their initializing expressions. However, these
  6818. expressions may contain side effects and should only be executed
  6819. when the condition of the \code{if} is true (for the ``then''
  6820. branch) or false (for the ``else'' branch). The \code{Let} provides
  6821. a way to initialize the temporary variables within the two branches
  6822. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  6823. form assigns the result of $e_1$ to the variable $x$, an then
  6824. evaluates $e_2$, which may reference $x$.}
  6825. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6826. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6827. according to whether the output needs to be \Exp{} or \Atm{} as
  6828. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6829. particularly important to \textbf{not} replace its condition with a
  6830. temporary variable because that would interfere with the generation of
  6831. high-quality output in the \code{explicate\_control} pass.
  6832. \begin{figure}[tp]
  6833. \centering
  6834. \fbox{
  6835. \begin{minipage}{0.96\textwidth}
  6836. {\if\edition\racketEd
  6837. \[
  6838. \begin{array}{rcl}
  6839. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6840. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6841. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6842. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6843. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6844. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6845. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6846. \end{array}
  6847. \]
  6848. \fi}
  6849. {\if\edition\pythonEd
  6850. \[
  6851. \begin{array}{rcl}
  6852. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  6853. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6854. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  6855. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6856. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  6857. \Exp &::=& \Atm \MID \READ{} \\
  6858. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  6859. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6860. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  6861. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6862. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  6863. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  6864. \end{array}
  6865. \]
  6866. \fi}
  6867. \end{minipage}
  6868. }
  6869. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  6870. \label{fig:Lif-anf-syntax}
  6871. \end{figure}
  6872. \begin{exercise}\normalfont
  6873. %
  6874. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6875. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6876. %
  6877. Create three new \LangIf{} programs that exercise the interesting
  6878. code in this pass.
  6879. %
  6880. {\if\edition\racketEd
  6881. In the \code{run-tests.rkt} script, add the following entry to the
  6882. list of \code{passes} and then run the script to test your compiler.
  6883. \begin{lstlisting}
  6884. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  6885. \end{lstlisting}
  6886. \fi}
  6887. \end{exercise}
  6888. \section{Explicate Control}
  6889. \label{sec:explicate-control-Lif}
  6890. \racket{Recall that the purpose of \code{explicate\_control} is to
  6891. make the order of evaluation explicit in the syntax of the program.
  6892. With the addition of \key{if} this get more interesting.}
  6893. %
  6894. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  6895. %
  6896. The main challenge to overcome is that the condition of an \key{if}
  6897. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  6898. condition must be a comparison.
  6899. As a motivating example, consider the following program that has an
  6900. \key{if} expression nested in the condition of another \key{if}.%
  6901. \python{\footnote{Programmers rarely write nested \code{if}
  6902. expressions, but it is not uncommon for the condition of an
  6903. \code{if} statement to be a call of a function that also contains an
  6904. \code{if} statement. When such a function is inlined, the result is
  6905. a nested \code{if} that requires the techniques discussed in this
  6906. section.}}
  6907. % cond_test_41.rkt, if_lt_eq.py
  6908. \begin{center}
  6909. \begin{minipage}{0.96\textwidth}
  6910. {\if\edition\racketEd
  6911. \begin{lstlisting}
  6912. (let ([x (read)])
  6913. (let ([y (read)])
  6914. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6915. (+ y 2)
  6916. (+ y 10))))
  6917. \end{lstlisting}
  6918. \fi}
  6919. {\if\edition\pythonEd
  6920. \begin{lstlisting}
  6921. x = input_int()
  6922. y = input_int()
  6923. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  6924. \end{lstlisting}
  6925. \fi}
  6926. \end{minipage}
  6927. \end{center}
  6928. %
  6929. The naive way to compile \key{if} and the comparison operations would
  6930. be to handle each of them in isolation, regardless of their context.
  6931. Each comparison would be translated into a \key{cmpq} instruction
  6932. followed by a couple instructions to move the result from the EFLAGS
  6933. register into a general purpose register or stack location. Each
  6934. \key{if} would be translated into a \key{cmpq} instruction followed by
  6935. a conditional jump. The generated code for the inner \key{if} in the
  6936. above example would be as follows.
  6937. \begin{center}
  6938. \begin{minipage}{0.96\textwidth}
  6939. \begin{lstlisting}
  6940. cmpq $1, x
  6941. setl %al
  6942. movzbq %al, tmp
  6943. cmpq $1, tmp
  6944. je then_branch_1
  6945. jmp else_branch_1
  6946. \end{lstlisting}
  6947. \end{minipage}
  6948. \end{center}
  6949. However, if we take context into account we can do better and reduce
  6950. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6951. Our goal will be to compile \key{if} expressions so that the relevant
  6952. comparison instruction appears directly before the conditional jump.
  6953. For example, we want to generate the following code for the inner
  6954. \code{if}.
  6955. \begin{center}
  6956. \begin{minipage}{0.96\textwidth}
  6957. \begin{lstlisting}
  6958. cmpq $1, x
  6959. jl then_branch_1
  6960. jmp else_branch_1
  6961. \end{lstlisting}
  6962. \end{minipage}
  6963. \end{center}
  6964. One way to achieve this is to reorganize the code at the level of
  6965. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  6966. the following code.
  6967. \begin{center}
  6968. \begin{minipage}{0.96\textwidth}
  6969. {\if\edition\racketEd
  6970. \begin{lstlisting}
  6971. (let ([x (read)])
  6972. (let ([y (read)])
  6973. (if (< x 1)
  6974. (if (eq? x 0)
  6975. (+ y 2)
  6976. (+ y 10))
  6977. (if (eq? x 2)
  6978. (+ y 2)
  6979. (+ y 10)))))
  6980. \end{lstlisting}
  6981. \fi}
  6982. {\if\edition\pythonEd
  6983. \begin{lstlisting}
  6984. x = input_int()
  6985. y = intput_int()
  6986. print(((y + 2) if x == 0 else (y + 10)) \
  6987. if (x < 1) \
  6988. else ((y + 2) if (x == 2) else (y + 10)))
  6989. \end{lstlisting}
  6990. \fi}
  6991. \end{minipage}
  6992. \end{center}
  6993. Unfortunately, this approach duplicates the two branches from the
  6994. outer \code{if} and a compiler must never duplicate code! After all,
  6995. the two branches could have been very large expressions.
  6996. We need a way to perform the above transformation but without
  6997. duplicating code. That is, we need a way for different parts of a
  6998. program to refer to the same piece of code.
  6999. %
  7000. Put another way, we need to move away from abstract syntax
  7001. \emph{trees} and instead use \emph{graphs}.
  7002. %
  7003. At the level of x86 assembly this is straightforward because we can
  7004. label the code for each branch and insert jumps in all the places that
  7005. need to execute the branch.
  7006. %
  7007. Likewise, our language \LangCIf{} provides the ability to label a
  7008. sequence of code and to jump to a label via \code{goto}.
  7009. %
  7010. %% In particular, we use a standard program representation called a
  7011. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7012. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7013. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7014. %% edge represents a jump to another block.
  7015. %
  7016. %% The nice thing about the output of \code{explicate\_control} is that
  7017. %% there are no unnecessary comparisons and every comparison is part of a
  7018. %% conditional jump.
  7019. %% The down-side of this output is that it includes
  7020. %% trivial blocks, such as the blocks labeled \code{block92} through
  7021. %% \code{block95}, that only jump to another block. We discuss a solution
  7022. %% to this problem in Section~\ref{sec:opt-jumps}.
  7023. {\if\edition\racketEd
  7024. %
  7025. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7026. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7027. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7028. former function translates expressions in tail position whereas the
  7029. later function translates expressions on the right-hand-side of a
  7030. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7031. have a new kind of position to deal with: the predicate position of
  7032. the \key{if}. We need another function, \code{explicate\_pred}, that
  7033. decides how to compile an \key{if} by analyzing its predicate. So
  7034. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7035. tails for the then-branch and else-branch and outputs a tail. In the
  7036. following paragraphs we discuss specific cases in the
  7037. \code{explicate\_tail}, \code{explicate\_assign}, and
  7038. \code{explicate\_pred} functions.
  7039. %
  7040. \fi}
  7041. %
  7042. {\if\edition\pythonEd
  7043. %
  7044. We recommend implementing \code{explicate\_control} using the
  7045. following four auxiliary functions.
  7046. \begin{description}
  7047. \item[\code{explicate\_effect}] generates code for expressions as
  7048. statements, so their result is ignored and only their side effects
  7049. matter.
  7050. \item[\code{explicate\_assign}] generates code for expressions
  7051. on the right-hand side of an assignment.
  7052. \item[\code{explicate\_pred}] generates code for an \code{if}
  7053. expression or statement by analyzing the condition expression.
  7054. \item[\code{explicate\_stmt}] generates code for statements.
  7055. \end{description}
  7056. These four functions should build the dictionary of basic blocks. The
  7057. following auxiliary function can be used to create a new basic block
  7058. from a list of statements. It returns a \code{goto} statement that
  7059. jumps to the new basic block.
  7060. \begin{center}
  7061. \begin{minipage}{\textwidth}
  7062. \begin{lstlisting}
  7063. def create_block(stmts, basic_blocks):
  7064. label = label_name(generate_name('block'))
  7065. basic_blocks[label] = stmts
  7066. return Goto(label)
  7067. \end{lstlisting}
  7068. \end{minipage}
  7069. \end{center}
  7070. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7071. \code{explicate\_control} pass.
  7072. The \code{explicate\_effect} function has three parameters: 1) the
  7073. expression to be compiled, 2) the already-compiled code for this
  7074. expression's \emph{continuation}, that is, the list of statements that
  7075. should execute after this expression, and 3) the dictionary of
  7076. generated basic blocks. The \code{explicate\_effect} function returns
  7077. a list of \LangCIf{} statements and it may add to the dictionary of
  7078. basic blocks.
  7079. %
  7080. Let's consider a few of the cases for the expression to be compiled.
  7081. If the expression to be compiled is a constant, then it can be
  7082. discarded because it has no side effects. If it's a \CREAD{}, then it
  7083. has a side-effect and should be preserved. So the exprssion should be
  7084. translated into a statement using the \code{Expr} AST class. If the
  7085. expression to be compiled is an \code{if} expression, we translate the
  7086. two branches using \code{explicate\_effect} and then translate the
  7087. condition expression using \code{explicate\_pred}, which generates
  7088. code for the entire \code{if}.
  7089. The \code{explicate\_assign} function has four parameters: 1) the
  7090. right-hand-side of the assignment, 2) the left-hand-side of the
  7091. assignment (the variable), 3) the continuation, and 4) the dictionary
  7092. of basic blocks. The \code{explicate\_assign} function returns a list
  7093. of \LangCIf{} statements and it may add to the dictionary of basic
  7094. blocks.
  7095. When the right-hand-side is an \code{if} expression, there is some
  7096. work to do. In particular, the two branches should be translated using
  7097. \code{explicate\_assign} and the condition expression should be
  7098. translated using \code{explicate\_pred}. Otherwise we can simply
  7099. generate an assignment statement, with the given left and right-hand
  7100. sides, concatenated with its continuation.
  7101. \begin{figure}[tbp]
  7102. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7103. def explicate_effect(e, cont, basic_blocks):
  7104. match e:
  7105. case IfExp(test, body, orelse):
  7106. ...
  7107. case Call(func, args):
  7108. ...
  7109. case Let(var, rhs, body):
  7110. ...
  7111. case _:
  7112. ...
  7113. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7114. match rhs:
  7115. case IfExp(test, body, orelse):
  7116. ...
  7117. case Let(var, rhs, body):
  7118. ...
  7119. case _:
  7120. return [Assign([lhs], rhs)] + cont
  7121. def explicate_pred(cnd, thn, els, basic_blocks):
  7122. match cnd:
  7123. case Compare(left, [op], [right]):
  7124. goto_thn = create_block(thn, basic_blocks)
  7125. goto_els = create_block(els, basic_blocks)
  7126. return [If(cnd, [goto_thn], [goto_els])]
  7127. case Constant(True):
  7128. return thn;
  7129. case Constant(False):
  7130. return els;
  7131. case UnaryOp(Not(), operand):
  7132. ...
  7133. case IfExp(test, body, orelse):
  7134. ...
  7135. case Let(var, rhs, body):
  7136. ...
  7137. case _:
  7138. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7139. [create_block(els, basic_blocks)],
  7140. [create_block(thn, basic_blocks)])]
  7141. def explicate_stmt(s, cont, basic_blocks):
  7142. match s:
  7143. case Assign([lhs], rhs):
  7144. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7145. case Expr(value):
  7146. return explicate_effect(value, cont, basic_blocks)
  7147. case If(test, body, orelse):
  7148. ...
  7149. def explicate_control(p):
  7150. match p:
  7151. case Module(body):
  7152. new_body = [Return(Constant(0))]
  7153. basic_blocks = {}
  7154. for s in reversed(body):
  7155. new_body = explicate_stmt(s, new_body, basic_blocks)
  7156. basic_blocks[label_name('start')] = new_body
  7157. return CProgram(basic_blocks)
  7158. \end{lstlisting}
  7159. \caption{Skeleton for the \code{explicate\_control} pass.}
  7160. \label{fig:explicate-control-Lif}
  7161. \end{figure}
  7162. \fi}
  7163. {\if\edition\racketEd
  7164. %
  7165. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7166. additional cases for Boolean constants and \key{if}. The cases for
  7167. \code{if} should recursively compile the two branches using either
  7168. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7169. cases should then invoke \code{explicate\_pred} on the condition
  7170. expression, passing in the generated code for the two branches. For
  7171. example, consider the following program with an \code{if} in tail
  7172. position.
  7173. \begin{lstlisting}
  7174. (let ([x (read)])
  7175. (if (eq? x 0) 42 777))
  7176. \end{lstlisting}
  7177. The two branches are recursively compiled to \code{return 42;} and
  7178. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7179. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7180. used as the result for \code{explicate\_tail}.
  7181. Next let us consider a program with an \code{if} on the right-hand
  7182. side of a \code{let}.
  7183. \begin{lstlisting}
  7184. (let ([y (read)])
  7185. (let ([x (if (eq? y 0) 40 777)])
  7186. (+ x 2)))
  7187. \end{lstlisting}
  7188. Note that the body of the inner \code{let} will have already been
  7189. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7190. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7191. to recursively process both branches of the \code{if}, so we generate
  7192. the following block using an auxiliary function named \code{create\_block}.
  7193. \begin{lstlisting}
  7194. block_6:
  7195. return (+ x 2)
  7196. \end{lstlisting}
  7197. and use \code{goto block\_6;} as the \code{cont} argument for
  7198. compiling the branches. So the two branches compile to
  7199. \begin{lstlisting}
  7200. x = 40;
  7201. goto block_6;
  7202. \end{lstlisting}
  7203. and
  7204. \begin{lstlisting}
  7205. x = 777;
  7206. goto block_6;
  7207. \end{lstlisting}
  7208. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7209. 0)} and the above code for the branches.
  7210. \fi}
  7211. {\if\edition\racketEd
  7212. \begin{figure}[tbp]
  7213. \begin{lstlisting}
  7214. (define (explicate_pred cnd thn els)
  7215. (match cnd
  7216. [(Var x) ___]
  7217. [(Let x rhs body) ___]
  7218. [(Prim 'not (list e)) ___]
  7219. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7220. (IfStmt (Prim op es) (create_block thn)
  7221. (create_block els))]
  7222. [(Bool b) (if b thn els)]
  7223. [(If cnd^ thn^ els^) ___]
  7224. [else (error "explicate_pred unhandled case" cnd)]))
  7225. \end{lstlisting}
  7226. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7227. \label{fig:explicate-pred}
  7228. \end{figure}
  7229. \fi}
  7230. \racket{The skeleton for the \code{explicate\_pred} function is given
  7231. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7232. 1) \code{cnd}, the condition expression of the \code{if},
  7233. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7234. and 3) \code{els}, the code generated by
  7235. explicate for the ``else'' branch. The \code{explicate\_pred}
  7236. function should match on \code{cnd} with a case for
  7237. every kind of expression that can have type \code{Boolean}.}
  7238. %
  7239. \python{The \code{explicate\_pred} function has four parameters: 1)
  7240. the condition expession, 2) the generated statements for the
  7241. ``then'' branch, 3) the generated statements for the ``else''
  7242. branch, and 4) the dictionary of basic blocks. The
  7243. \code{explicate\_pred} function returns a list of \LangCIf{}
  7244. statements and it may add to the dictionary of basic blocks.}
  7245. Consider the case for comparison operators. We translate the
  7246. comparison to an \code{if} statement whose branches are \code{goto}
  7247. statements created by applying \code{create\_block} to the code
  7248. generated for the \code{thn} and \code{els} branches. Let us
  7249. illustrate this translation with an example. Returning
  7250. to the program with an \code{if} expression in tail position,
  7251. we invoke \code{explicate\_pred} on its condition \code{(eq? x 0)}
  7252. which happens to be a comparison operator.
  7253. \begin{lstlisting}
  7254. (let ([x (read)])
  7255. (if (eq? x 0) 42 777))
  7256. \end{lstlisting}
  7257. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7258. statements, from which we now create the following blocks.
  7259. \begin{center}
  7260. \begin{minipage}{\textwidth}
  7261. \begin{lstlisting}
  7262. block_1:
  7263. return 42;
  7264. block_2:
  7265. return 777;
  7266. \end{lstlisting}
  7267. \end{minipage}
  7268. \end{center}
  7269. %
  7270. So \code{explicate\_pred} compiles the comparison \code{(eq? x 0)}
  7271. to the following \code{if} statement.
  7272. %
  7273. \begin{center}
  7274. \begin{minipage}{\textwidth}
  7275. \begin{lstlisting}
  7276. if (eq? x 0)
  7277. goto block_1;
  7278. else
  7279. goto block_2;
  7280. \end{lstlisting}
  7281. \end{minipage}
  7282. \end{center}
  7283. Next consider the case for Boolean constants. We perform a kind of
  7284. partial evaluation\index{subject}{partial evaluation} and output
  7285. either the \code{thn} or \code{els} branch depending on whether the
  7286. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7287. following program.
  7288. \begin{center}
  7289. \begin{minipage}{\textwidth}
  7290. \begin{lstlisting}
  7291. (if #t 42 777)
  7292. \end{lstlisting}
  7293. \end{minipage}
  7294. \end{center}
  7295. %
  7296. Again, the two branches \code{42} and \code{777} were compiled to
  7297. \code{return} statements, so \code{explicate\_pred} compiles the
  7298. constant \code{\#t} to the code for the ``then'' branch.
  7299. \begin{center}
  7300. \begin{minipage}{\textwidth}
  7301. \begin{lstlisting}
  7302. return 42;
  7303. \end{lstlisting}
  7304. \end{minipage}
  7305. \end{center}
  7306. %
  7307. This case demonstrates that we sometimes discard the \code{thn} or
  7308. \code{els} blocks that are input to \code{explicate\_pred}.
  7309. The case for \key{if} expressions in \code{explicate\_pred} is
  7310. particularly illuminating because it deals with the challenges we
  7311. discussed above regarding nested \key{if} expressions
  7312. (Figure~\ref{fig:explicate-control-s1-38}). The
  7313. \racket{\lstinline{thn^}}\python{\code{body}} and
  7314. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7315. \key{if} inherit their context from the current one, that is,
  7316. predicate context. So you should recursively apply
  7317. \code{explicate\_pred} to the
  7318. \racket{\lstinline{thn^}}\python{\code{body}} and
  7319. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7320. those recursive calls, pass \code{thn} and \code{els} as the extra
  7321. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7322. inside each recursive call. As discussed above, to avoid duplicating
  7323. code, we need to add them to the dictionary of basic blocks so that we
  7324. can instead refer to them by name and execute them with a \key{goto}.
  7325. {\if\edition\pythonEd
  7326. %
  7327. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7328. three parameters: 1) the statement to be compiled, 2) the code for its
  7329. continuation, and 3) the dictionary of basic blocks. The
  7330. \code{explicate\_stmt} returns a list of statements and it may add to
  7331. the dictionary of basic blocks. The cases for assignment and an
  7332. expression-statement are given in full in the skeleton code: they
  7333. simply dispatch to \code{explicate\_assign} and
  7334. \code{explicate\_effect}, respectively. The case for \code{if}
  7335. statements is not given, and is similar to the case for \code{if}
  7336. expressions.
  7337. The \code{explicate\_control} function itself is given in
  7338. Figure~\ref{fig:explicate-control-Lif}. It applies
  7339. \code{explicate\_stmt} to each statement in the program, from back to
  7340. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7341. used as the continuation parameter in the next call to
  7342. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7343. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7344. the dictionary of basic blocks, labeling it as the ``start'' block.
  7345. %
  7346. \fi}
  7347. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7348. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7349. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7350. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7351. %% results from the two recursive calls. We complete the case for
  7352. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7353. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7354. %% the result $B_5$.
  7355. %% \[
  7356. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7357. %% \quad\Rightarrow\quad
  7358. %% B_5
  7359. %% \]
  7360. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7361. %% inherit the current context, so they are in tail position. Thus, the
  7362. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7363. %% \code{explicate\_tail}.
  7364. %% %
  7365. %% We need to pass $B_0$ as the accumulator argument for both of these
  7366. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7367. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7368. %% to the control-flow graph and obtain a promised goto $G_0$.
  7369. %% %
  7370. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7371. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7372. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7373. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7374. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7375. %% \[
  7376. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7377. %% \]
  7378. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7379. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7380. %% should not be confused with the labels for the blocks that appear in
  7381. %% the generated code. We initially construct unlabeled blocks; we only
  7382. %% attach labels to blocks when we add them to the control-flow graph, as
  7383. %% we see in the next case.
  7384. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7385. %% function. The context of the \key{if} is an assignment to some
  7386. %% variable $x$ and then the control continues to some promised block
  7387. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7388. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7389. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7390. %% branches of the \key{if} inherit the current context, so they are in
  7391. %% assignment positions. Let $B_2$ be the result of applying
  7392. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7393. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7394. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7395. %% the result of applying \code{explicate\_pred} to the predicate
  7396. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7397. %% translates to the promise $B_4$.
  7398. %% \[
  7399. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7400. %% \]
  7401. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7402. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7403. \code{remove\_complex\_operands} pass and then the
  7404. \code{explicate\_control} pass on the example program. We walk through
  7405. the output program.
  7406. %
  7407. Following the order of evaluation in the output of
  7408. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7409. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7410. in the predicate of the inner \key{if}. In the output of
  7411. \code{explicate\_control}, in the
  7412. block labeled \code{start}, are two assignment statements followed by a
  7413. \code{if} statement that branches to \code{block\_8} or
  7414. \code{block\_9}. The blocks associated with those labels contain the
  7415. translations of the code
  7416. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7417. and
  7418. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7419. respectively. In particular, we start \code{block\_8} with the
  7420. comparison
  7421. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7422. and then branch to \code{block\_4} or \code{block\_5}.
  7423. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7424. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7425. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7426. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7427. and go directly to \code{block\_2} and \code{block\_3},
  7428. which we investigate in Section~\ref{sec:opt-jumps}.
  7429. Getting back to the example, \code{block\_2} and \code{block\_3},
  7430. corresponds to the two branches of the outer \key{if}, i.e.,
  7431. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7432. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7433. %
  7434. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7435. %
  7436. \python{The \code{block\_1} corresponds to the \code{print} statment
  7437. at the end of the program.}
  7438. \begin{figure}[tbp]
  7439. {\if\edition\racketEd
  7440. \begin{tabular}{lll}
  7441. \begin{minipage}{0.4\textwidth}
  7442. % cond_test_41.rkt
  7443. \begin{lstlisting}
  7444. (let ([x (read)])
  7445. (let ([y (read)])
  7446. (if (if (< x 1)
  7447. (eq? x 0)
  7448. (eq? x 2))
  7449. (+ y 2)
  7450. (+ y 10))))
  7451. \end{lstlisting}
  7452. \end{minipage}
  7453. &
  7454. $\Rightarrow$
  7455. &
  7456. \begin{minipage}{0.55\textwidth}
  7457. \begin{lstlisting}
  7458. start:
  7459. x = (read);
  7460. y = (read);
  7461. if (< x 1)
  7462. goto block_8;
  7463. else
  7464. goto block_9;
  7465. block_8:
  7466. if (eq? x 0)
  7467. goto block_4;
  7468. else
  7469. goto block_5;
  7470. block_9:
  7471. if (eq? x 2)
  7472. goto block_6;
  7473. else
  7474. goto block_7;
  7475. block_4:
  7476. goto block_2;
  7477. block_5:
  7478. goto block_3;
  7479. block_6:
  7480. goto block_2;
  7481. block_7:
  7482. goto block_3;
  7483. block_2:
  7484. return (+ y 2);
  7485. block_3:
  7486. return (+ y 10);
  7487. \end{lstlisting}
  7488. \end{minipage}
  7489. \end{tabular}
  7490. \fi}
  7491. {\if\edition\pythonEd
  7492. \begin{tabular}{lll}
  7493. \begin{minipage}{0.4\textwidth}
  7494. % cond_test_41.rkt
  7495. \begin{lstlisting}
  7496. x = input_int()
  7497. y = input_int()
  7498. print(y + 2 \
  7499. if (x == 0 \
  7500. if x < 1 \
  7501. else x == 2) \
  7502. else y + 10)
  7503. \end{lstlisting}
  7504. \end{minipage}
  7505. &
  7506. $\Rightarrow$
  7507. &
  7508. \begin{minipage}{0.55\textwidth}
  7509. \begin{lstlisting}
  7510. start:
  7511. x = input_int()
  7512. y = input_int()
  7513. if x < 1:
  7514. goto block_8
  7515. else:
  7516. goto block_9
  7517. block_8:
  7518. if x == 0:
  7519. goto block_4
  7520. else:
  7521. goto block_5
  7522. block_9:
  7523. if x == 2:
  7524. goto block_6
  7525. else:
  7526. goto block_7
  7527. block_4:
  7528. goto block_2
  7529. block_5:
  7530. goto block_3
  7531. block_6:
  7532. goto block_2
  7533. block_7:
  7534. goto block_3
  7535. block_2:
  7536. tmp_0 = y + 2
  7537. goto block_1
  7538. block_3:
  7539. tmp_0 = y + 10
  7540. goto block_1
  7541. block_1:
  7542. print(tmp_0)
  7543. return 0
  7544. \end{lstlisting}
  7545. \end{minipage}
  7546. \end{tabular}
  7547. \fi}
  7548. \caption{Translation from \LangIf{} to \LangCIf{}
  7549. via the \code{explicate\_control}.}
  7550. \label{fig:explicate-control-s1-38}
  7551. \end{figure}
  7552. {\if\edition\racketEd
  7553. The way in which the \code{shrink} pass transforms logical operations
  7554. such as \code{and} and \code{or} can impact the quality of code
  7555. generated by \code{explicate\_control}. For example, consider the
  7556. following program.
  7557. % cond_test_21.rkt, and_eq_input.py
  7558. \begin{lstlisting}
  7559. (if (and (eq? (read) 0) (eq? (read) 1))
  7560. 0
  7561. 42)
  7562. \end{lstlisting}
  7563. The \code{and} operation should transform into something that the
  7564. \code{explicate\_pred} function can still analyze and descend through to
  7565. reach the underlying \code{eq?} conditions. Ideally, your
  7566. \code{explicate\_control} pass should generate code similar to the
  7567. following for the above program.
  7568. \begin{center}
  7569. \begin{lstlisting}
  7570. start:
  7571. tmp1 = (read);
  7572. if (eq? tmp1 0) goto block40;
  7573. else goto block39;
  7574. block40:
  7575. tmp2 = (read);
  7576. if (eq? tmp2 1) goto block38;
  7577. else goto block39;
  7578. block38:
  7579. return 0;
  7580. block39:
  7581. return 42;
  7582. \end{lstlisting}
  7583. \end{center}
  7584. \fi}
  7585. \begin{exercise}\normalfont
  7586. \racket{
  7587. Implement the pass \code{explicate\_control} by adding the cases for
  7588. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7589. \code{explicate\_assign} functions. Implement the auxiliary function
  7590. \code{explicate\_pred} for predicate contexts.}
  7591. \python{Implement \code{explicate\_control} pass with its
  7592. four auxiliary functions.}
  7593. %
  7594. Create test cases that exercise all of the new cases in the code for
  7595. this pass.
  7596. %
  7597. {\if\edition\racketEd
  7598. Add the following entry to the list of \code{passes} in
  7599. \code{run-tests.rkt} and then run this script to test your compiler.
  7600. \begin{lstlisting}
  7601. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7602. \end{lstlisting}
  7603. \fi}
  7604. \end{exercise}
  7605. \clearpage
  7606. \section{Select Instructions}
  7607. \label{sec:select-Lif}
  7608. \index{subject}{instruction selection}
  7609. The \code{select\_instructions} pass translates \LangCIf{} to
  7610. \LangXIfVar{}.
  7611. %
  7612. \racket{Recall that we implement this pass using three auxiliary
  7613. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7614. $\Tail$.}
  7615. %
  7616. \racket{For $\Atm$, we have new cases for the Booleans.}
  7617. %
  7618. \python{We begin with the Boolean constants.}
  7619. We take the usual approach of encoding them as integers.
  7620. \[
  7621. \TRUE{} \quad\Rightarrow\quad \key{1}
  7622. \qquad\qquad
  7623. \FALSE{} \quad\Rightarrow\quad \key{0}
  7624. \]
  7625. For translating statements, we discuss a couple cases. The \code{not}
  7626. operation can be implemented in terms of \code{xorq} as we discussed
  7627. at the beginning of this section. Given an assignment, if the
  7628. left-hand side variable is the same as the argument of \code{not},
  7629. then just the \code{xorq} instruction suffices.
  7630. \[
  7631. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7632. \quad\Rightarrow\quad
  7633. \key{xorq}~\key{\$}1\key{,}~\Var
  7634. \]
  7635. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7636. semantics of x86. In the following translation, let $\Arg$ be the
  7637. result of translating $\Atm$ to x86.
  7638. \[
  7639. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7640. \quad\Rightarrow\quad
  7641. \begin{array}{l}
  7642. \key{movq}~\Arg\key{,}~\Var\\
  7643. \key{xorq}~\key{\$}1\key{,}~\Var
  7644. \end{array}
  7645. \]
  7646. Next consider the cases for equality. Translating this operation to
  7647. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7648. instruction discussed above. We recommend translating an assignment
  7649. with an equality on the right-hand side into a sequence of three
  7650. instructions. \\
  7651. \begin{tabular}{lll}
  7652. \begin{minipage}{0.4\textwidth}
  7653. \begin{lstlisting}
  7654. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7655. \end{lstlisting}
  7656. \end{minipage}
  7657. &
  7658. $\Rightarrow$
  7659. &
  7660. \begin{minipage}{0.4\textwidth}
  7661. \begin{lstlisting}
  7662. cmpq |$\Arg_2$|, |$\Arg_1$|
  7663. sete %al
  7664. movzbq %al, |$\Var$|
  7665. \end{lstlisting}
  7666. \end{minipage}
  7667. \end{tabular} \\
  7668. The translations for the other comparison operators are similar to the
  7669. above but use different suffixes for the \code{set} instruction.
  7670. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7671. \key{goto} and \key{if} statements. Both are straightforward to
  7672. translate to x86.}
  7673. %
  7674. A \key{goto} statement becomes a jump instruction.
  7675. \[
  7676. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7677. \]
  7678. %
  7679. An \key{if} statement becomes a compare instruction followed by a
  7680. conditional jump (for the ``then'' branch) and the fall-through is to
  7681. a regular jump (for the ``else'' branch).\\
  7682. \begin{tabular}{lll}
  7683. \begin{minipage}{0.4\textwidth}
  7684. \begin{lstlisting}
  7685. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7686. goto |$\ell_1$||$\racket{\key{;}}$|
  7687. else|$\python{\key{:}}$|
  7688. goto |$\ell_2$||$\racket{\key{;}}$|
  7689. \end{lstlisting}
  7690. \end{minipage}
  7691. &
  7692. $\Rightarrow$
  7693. &
  7694. \begin{minipage}{0.4\textwidth}
  7695. \begin{lstlisting}
  7696. cmpq |$\Arg_2$|, |$\Arg_1$|
  7697. je |$\ell_1$|
  7698. jmp |$\ell_2$|
  7699. \end{lstlisting}
  7700. \end{minipage}
  7701. \end{tabular} \\
  7702. Again, the translations for the other comparison operators are similar to the
  7703. above but use different suffixes for the conditional jump instruction.
  7704. \python{Regarding the \key{return} statement, we recommend treating it
  7705. as an assignment to the \key{rax} register followed by a jump to the
  7706. conclusion of the \code{main} function.}
  7707. \begin{exercise}\normalfont
  7708. Expand your \code{select\_instructions} pass to handle the new
  7709. features of the \LangIf{} language.
  7710. %
  7711. {\if\edition\racketEd
  7712. Add the following entry to the list of \code{passes} in
  7713. \code{run-tests.rkt}
  7714. \begin{lstlisting}
  7715. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7716. \end{lstlisting}
  7717. \fi}
  7718. %
  7719. Run the script to test your compiler on all the test programs.
  7720. \end{exercise}
  7721. \section{Register Allocation}
  7722. \label{sec:register-allocation-Lif}
  7723. \index{subject}{register allocation}
  7724. The changes required for \LangIf{} affect liveness analysis, building the
  7725. interference graph, and assigning homes, but the graph coloring
  7726. algorithm itself does not change.
  7727. \subsection{Liveness Analysis}
  7728. \label{sec:liveness-analysis-Lif}
  7729. \index{subject}{liveness analysis}
  7730. Recall that for \LangVar{} we implemented liveness analysis for a
  7731. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7732. the addition of \key{if} expressions to \LangIf{},
  7733. \code{explicate\_control} produces many basic blocks.
  7734. %% We recommend that you create a new auxiliary function named
  7735. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7736. %% control-flow graph.
  7737. The first question is: what order should we process the basic blocks?
  7738. Recall that to perform liveness analysis on a basic block we need to
  7739. know the live-after set for the last instruction in the block. If a
  7740. basic block has no successors (i.e. contains no jumps to other
  7741. blocks), then it has an empty live-after set and we can immediately
  7742. apply liveness analysis to it. If a basic block has some successors,
  7743. then we need to complete liveness analysis on those blocks
  7744. first. These ordering contraints are the reverse of a
  7745. \emph{topological order}\index{subject}{topological order} on a graph
  7746. representation of the program. In particular, the \emph{control flow
  7747. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  7748. of a program has a node for each basic block and an edge for each jump
  7749. from one block to another. It is straightforward to generate a CFG
  7750. from the dictionary of basic blocks. One then transposes the CFG and
  7751. applies the topological sort algorithm.
  7752. %
  7753. %
  7754. \racket{We recommend using the \code{tsort} and \code{transpose}
  7755. functions of the Racket \code{graph} package to accomplish this.}
  7756. %
  7757. \python{We provide implementations of \code{topological\_sort} and
  7758. \code{transpose} in the file \code{graph.py} of the support code.}
  7759. %
  7760. As an aside, a topological ordering is only guaranteed to exist if the
  7761. graph does not contain any cycles. This is the case for the
  7762. control-flow graphs that we generate from \LangIf{} programs.
  7763. However, in Chapter~\ref{ch:Rwhile} we add loops to create \LangLoop{}
  7764. and learn how to handle cycles in the control-flow graph.
  7765. \racket{You'll need to construct a directed graph to represent the
  7766. control-flow graph. Do not use the \code{directed-graph} of the
  7767. \code{graph} package because that only allows at most one edge
  7768. between each pair of vertices, but a control-flow graph may have
  7769. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7770. file in the support code implements a graph representation that
  7771. allows multiple edges between a pair of vertices.}
  7772. {\if\edition\racketEd
  7773. The next question is how to analyze jump instructions. Recall that in
  7774. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7775. \code{label->live} that maps each label to the set of live locations
  7776. at the beginning of its block. We use \code{label->live} to determine
  7777. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7778. that we have many basic blocks, \code{label->live} needs to be updated
  7779. as we process the blocks. In particular, after performing liveness
  7780. analysis on a block, we take the live-before set of its first
  7781. instruction and associate that with the block's label in the
  7782. \code{label->live}.
  7783. \fi}
  7784. %
  7785. {\if\edition\pythonEd
  7786. %
  7787. The next question is how to analyze jump instructions. The locations
  7788. that are live before a \code{jmp} should be the locations in
  7789. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7790. maintaining a dictionary named \code{live\_before\_block} that maps each
  7791. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7792. block. After performing liveness analysis on each block, we take the
  7793. live-before set of its first instruction and associate that with the
  7794. block's label in the \code{live\_before\_block} dictionary.
  7795. %
  7796. \fi}
  7797. In \LangXIfVar{} we also have the conditional jump
  7798. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7799. this instruction is particularly interesting because, during
  7800. compilation, we do not know which way a conditional jump will go. So
  7801. we do not know whether to use the live-before set for the following
  7802. instruction or the live-before set for the block associated with the
  7803. $\itm{label}$. However, there is no harm to the correctness of the
  7804. generated code if we classify more locations as live than the ones
  7805. that are truly live during one particular execution of the
  7806. instruction. Thus, we can take the union of the live-before sets from
  7807. the following instruction and from the mapping for $\itm{label}$ in
  7808. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7809. The auxiliary functions for computing the variables in an
  7810. instruction's argument and for computing the variables read-from ($R$)
  7811. or written-to ($W$) by an instruction need to be updated to handle the
  7812. new kinds of arguments and instructions in \LangXIfVar{}.
  7813. \begin{exercise}\normalfont
  7814. {\if\edition\racketEd
  7815. %
  7816. Update the \code{uncover\_live} pass to apply liveness analysis to
  7817. every basic block in the program.
  7818. %
  7819. Add the following entry to the list of \code{passes} in the
  7820. \code{run-tests.rkt} script.
  7821. \begin{lstlisting}
  7822. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  7823. \end{lstlisting}
  7824. \fi}
  7825. {\if\edition\pythonEd
  7826. %
  7827. Update the \code{uncover\_live} function to perform liveness analysis,
  7828. in reverse topological order, on all of the basic blocks in the
  7829. program.
  7830. %
  7831. \fi}
  7832. % Check that the live-after sets that you generate for
  7833. % example X matches the following... -Jeremy
  7834. \end{exercise}
  7835. \subsection{Build the Interference Graph}
  7836. \label{sec:build-interference-Lif}
  7837. Many of the new instructions in \LangXIfVar{} can be handled in the
  7838. same way as the instructions in \LangXVar{}. Thus, if your code was
  7839. already quite general, it will not need to be changed to handle the
  7840. new instructions. If you code is not general enough, we recommend that
  7841. you change your code to be more general. For example, you can factor
  7842. out the computing of the the read and write sets for each kind of
  7843. instruction into auxiliary functions.
  7844. Note that the \key{movzbq} instruction requires some special care,
  7845. similar to the \key{movq} instruction. See rule number 1 in
  7846. Section~\ref{sec:build-interference}.
  7847. \begin{exercise}\normalfont
  7848. Update the \code{build\_interference} pass for \LangXIfVar{}.
  7849. {\if\edition\racketEd
  7850. Add the following entries to the list of \code{passes} in the
  7851. \code{run-tests.rkt} script.
  7852. \begin{lstlisting}
  7853. (list "build_interference" build_interference interp-pseudo-x86-1)
  7854. (list "allocate_registers" allocate_registers interp-x86-1)
  7855. \end{lstlisting}
  7856. \fi}
  7857. % Check that the interference graph that you generate for
  7858. % example X matches the following graph G... -Jeremy
  7859. \end{exercise}
  7860. \section{Patch Instructions}
  7861. The new instructions \key{cmpq} and \key{movzbq} have some special
  7862. restrictions that need to be handled in the \code{patch\_instructions}
  7863. pass.
  7864. %
  7865. The second argument of the \key{cmpq} instruction must not be an
  7866. immediate value (such as an integer). So if you are comparing two
  7867. immediates, we recommend inserting a \key{movq} instruction to put the
  7868. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  7869. one memory reference.
  7870. %
  7871. The second argument of the \key{movzbq} must be a register.
  7872. \begin{exercise}\normalfont
  7873. %
  7874. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  7875. %
  7876. {\if\edition\racketEd
  7877. Add the following entry to the list of \code{passes} in
  7878. \code{run-tests.rkt} and then run this script to test your compiler.
  7879. \begin{lstlisting}
  7880. (list "patch_instructions" patch_instructions interp-x86-1)
  7881. \end{lstlisting}
  7882. \fi}
  7883. \end{exercise}
  7884. {\if\edition\pythonEd
  7885. \section{Prelude and Conclusion}
  7886. \label{sec:prelude-conclusion-cond}
  7887. The generation of the \code{main} function with its prelude and
  7888. conclusion must change to accomodate how the program now consists of
  7889. one or more basic blocks. After the prelude in \code{main}, jump to
  7890. the \code{start} block. Place the conclusion in a basic block labelled
  7891. with \code{conclusion}.
  7892. \fi}
  7893. Figure~\ref{fig:if-example-x86} shows a simple example program in
  7894. \LangIf{} translated to x86, showing the results of
  7895. \code{explicate\_control}, \code{select\_instructions}, and the final
  7896. x86 assembly.
  7897. \begin{figure}[tbp]
  7898. {\if\edition\racketEd
  7899. \begin{tabular}{lll}
  7900. \begin{minipage}{0.4\textwidth}
  7901. % cond_test_20.rkt, eq_input.py
  7902. \begin{lstlisting}
  7903. (if (eq? (read) 1) 42 0)
  7904. \end{lstlisting}
  7905. $\Downarrow$
  7906. \begin{lstlisting}
  7907. start:
  7908. tmp7951 = (read);
  7909. if (eq? tmp7951 1)
  7910. goto block7952;
  7911. else
  7912. goto block7953;
  7913. block7952:
  7914. return 42;
  7915. block7953:
  7916. return 0;
  7917. \end{lstlisting}
  7918. $\Downarrow$
  7919. \begin{lstlisting}
  7920. start:
  7921. callq read_int
  7922. movq %rax, tmp7951
  7923. cmpq $1, tmp7951
  7924. je block7952
  7925. jmp block7953
  7926. block7953:
  7927. movq $0, %rax
  7928. jmp conclusion
  7929. block7952:
  7930. movq $42, %rax
  7931. jmp conclusion
  7932. \end{lstlisting}
  7933. \end{minipage}
  7934. &
  7935. $\Rightarrow\qquad$
  7936. \begin{minipage}{0.4\textwidth}
  7937. \begin{lstlisting}
  7938. start:
  7939. callq read_int
  7940. movq %rax, %rcx
  7941. cmpq $1, %rcx
  7942. je block7952
  7943. jmp block7953
  7944. block7953:
  7945. movq $0, %rax
  7946. jmp conclusion
  7947. block7952:
  7948. movq $42, %rax
  7949. jmp conclusion
  7950. .globl main
  7951. main:
  7952. pushq %rbp
  7953. movq %rsp, %rbp
  7954. pushq %r13
  7955. pushq %r12
  7956. pushq %rbx
  7957. pushq %r14
  7958. subq $0, %rsp
  7959. jmp start
  7960. conclusion:
  7961. addq $0, %rsp
  7962. popq %r14
  7963. popq %rbx
  7964. popq %r12
  7965. popq %r13
  7966. popq %rbp
  7967. retq
  7968. \end{lstlisting}
  7969. \end{minipage}
  7970. \end{tabular}
  7971. \fi}
  7972. {\if\edition\pythonEd
  7973. \begin{tabular}{lll}
  7974. \begin{minipage}{0.4\textwidth}
  7975. % cond_test_20.rkt, eq_input.py
  7976. \begin{lstlisting}
  7977. print(42 if input_int() == 1 else 0)
  7978. \end{lstlisting}
  7979. $\Downarrow$
  7980. \begin{lstlisting}
  7981. start:
  7982. tmp_0 = input_int()
  7983. if tmp_0 == 1:
  7984. goto block_3
  7985. else:
  7986. goto block_4
  7987. block_3:
  7988. tmp_1 = 42
  7989. goto block_2
  7990. block_4:
  7991. tmp_1 = 0
  7992. goto block_2
  7993. block_2:
  7994. print(tmp_1)
  7995. return 0
  7996. \end{lstlisting}
  7997. $\Downarrow$
  7998. \begin{lstlisting}
  7999. start:
  8000. callq read_int
  8001. movq %rax, tmp_0
  8002. cmpq 1, tmp_0
  8003. je block_3
  8004. jmp block_4
  8005. block_3:
  8006. movq 42, tmp_1
  8007. jmp block_2
  8008. block_4:
  8009. movq 0, tmp_1
  8010. jmp block_2
  8011. block_2:
  8012. movq tmp_1, %rdi
  8013. callq print_int
  8014. movq 0, %rax
  8015. jmp conclusion
  8016. \end{lstlisting}
  8017. \end{minipage}
  8018. &
  8019. $\Rightarrow\qquad$
  8020. \begin{minipage}{0.4\textwidth}
  8021. \begin{lstlisting}
  8022. .globl main
  8023. main:
  8024. pushq %rbp
  8025. movq %rsp, %rbp
  8026. subq $0, %rsp
  8027. jmp start
  8028. start:
  8029. callq read_int
  8030. movq %rax, %rcx
  8031. cmpq $1, %rcx
  8032. je block_3
  8033. jmp block_4
  8034. block_3:
  8035. movq $42, %rcx
  8036. jmp block_2
  8037. block_4:
  8038. movq $0, %rcx
  8039. jmp block_2
  8040. block_2:
  8041. movq %rcx, %rdi
  8042. callq print_int
  8043. movq $0, %rax
  8044. jmp conclusion
  8045. conclusion:
  8046. addq $0, %rsp
  8047. popq %rbp
  8048. retq
  8049. \end{lstlisting}
  8050. \end{minipage}
  8051. \end{tabular}
  8052. \fi}
  8053. \caption{Example compilation of an \key{if} expression to x86, showing
  8054. the results of \code{explicate\_control},
  8055. \code{select\_instructions}, and the final x86 assembly code. }
  8056. \label{fig:if-example-x86}
  8057. \end{figure}
  8058. \begin{figure}[tbp]
  8059. {\if\edition\racketEd
  8060. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8061. \node (Lif) at (0,2) {\large \LangIf{}};
  8062. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8063. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8064. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8065. \node (Lif-5) at (12,2) {\large \LangIf{}};
  8066. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8067. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8068. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8069. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8070. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8071. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8072. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8073. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8074. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8075. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8076. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8077. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8078. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8079. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8080. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8081. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8082. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8083. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8084. \end{tikzpicture}
  8085. \fi}
  8086. {\if\edition\pythonEd
  8087. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8088. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8089. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8090. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8091. \node (C-1) at (3,0) {\large \LangCIf{}};
  8092. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8093. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8094. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8095. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8096. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8097. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8098. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8099. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8100. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8101. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8102. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8103. \end{tikzpicture}
  8104. \fi}
  8105. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8106. \label{fig:Lif-passes}
  8107. \end{figure}
  8108. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8109. compilation of \LangIf{}.
  8110. \section{Challenge: Optimize Blocks and Remove Jumps}
  8111. \label{sec:opt-jumps}
  8112. We discuss two optional challenges that involve optimizing the
  8113. control-flow of the program.
  8114. \subsection{Optimize Blocks}
  8115. The algorithm for \code{explicate\_control} that we discussed in
  8116. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8117. blocks. It does so in two different ways.
  8118. %
  8119. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8120. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8121. a new basic block from a single \code{goto} statement, whereas we
  8122. could have simply returned the \code{goto} statement. We can solve
  8123. this problem by modifying the \code{create\_block} function to
  8124. recognize this situation.
  8125. Second, \code{explicate\_control} creates a basic block whenever a
  8126. continuation \emph{might} get used more than once (wheneven a
  8127. continuation is passed into two or more recursive calls). However,
  8128. just because a continuation might get used more than once, doesn't
  8129. mean it will. In fact, some continuation parameters may not be used
  8130. at all because we sometimes ignore them. For example, consider the
  8131. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8132. discard the \code{els} branch. So the question is how can we decide
  8133. whether to create a basic block?
  8134. The solution to this conundrum is to use \emph{lazy
  8135. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8136. to delay creating a basic block until the point in time where we know
  8137. it will be used.
  8138. %
  8139. {\if\edition\racketEd
  8140. %
  8141. Racket provides support for
  8142. lazy evaluation with the
  8143. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8144. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8145. \index{subject}{delay} creates a
  8146. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8147. expressions is postponed. When \key{(force}
  8148. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8149. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8150. result of $e_n$ is cached in the promise and returned. If \code{force}
  8151. is applied again to the same promise, then the cached result is
  8152. returned. If \code{force} is applied to an argument that is not a
  8153. promise, \code{force} simply returns the argument.
  8154. %
  8155. \fi}
  8156. %
  8157. {\if\edition\pythonEd
  8158. %
  8159. While Python does not provide direct support for lazy evaluation, it
  8160. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8161. by wrapping it inside a function with no parameters. We can
  8162. \emph{force} its evaluation by calling the function. However, in some
  8163. cases of \code{explicate\_pred}, etc., we will return a list of
  8164. statements and in other cases we will return a function that computes
  8165. a list of statements. We use the term \emph{promise} to refer to a
  8166. value that may or may not be delayed. To uniformly deal with
  8167. promises, we define the following \code{force} function that checks
  8168. whether its input is delayed (i.e. whether it is a function) and then
  8169. either 1) calls the function, or 2) returns the input.
  8170. \begin{lstlisting}
  8171. def force(promise):
  8172. if isinstance(promise, types.FunctionType):
  8173. return promise()
  8174. else:
  8175. return promise
  8176. \end{lstlisting}
  8177. %
  8178. \fi}
  8179. We use promises for the input and output of the functions
  8180. \code{explicate\_pred}, \code{explicate\_assign},
  8181. %
  8182. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8183. %
  8184. So instead of taking and returning lists of statments, they take and
  8185. return promises. Furthermore, when we come to a situation in which a
  8186. continuation might be used more than once, as in the case for
  8187. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8188. that creates a basic block for each continuation (if there is not
  8189. already one) and then returns a \code{goto} statement to that basic
  8190. block.
  8191. %
  8192. {\if\edition\racketEd
  8193. %
  8194. The following auxiliary function named \code{create\_block} accomplishes
  8195. this task. It begins with \code{delay} to create a promise. When
  8196. forced, this promise will force the original promise. If that returns
  8197. a \code{goto} (because the block was already added to the control-flow
  8198. graph), then we return the \code{goto}. Otherwise we add the block to
  8199. the control-flow graph with another auxiliary function named
  8200. \code{add-node}. That function returns the label for the new block,
  8201. which we use to create a \code{goto}.
  8202. \begin{lstlisting}
  8203. (define (create_block block)
  8204. (delay
  8205. (define b (force block))
  8206. (match b
  8207. [(Goto label) (Goto label)]
  8208. [else (Goto (add-node b))])))
  8209. \end{lstlisting}
  8210. \fi}
  8211. {\if\edition\pythonEd
  8212. %
  8213. Here's the new version of the \code{create\_block} auxiliary function
  8214. that works on promises and that checks whether the block consists of a
  8215. solitary \code{goto} statement.\\
  8216. \begin{minipage}{\textwidth}
  8217. \begin{lstlisting}
  8218. def create_block(promise, basic_blocks):
  8219. stmts = force(promise)
  8220. match stmts:
  8221. case [Goto(l)]:
  8222. return Goto(l)
  8223. case _:
  8224. label = label_name(generate_name('block'))
  8225. basic_blocks[label] = stmts
  8226. return Goto(label)
  8227. \end{lstlisting}
  8228. \end{minipage}
  8229. \fi}
  8230. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8231. \code{explicate\_control} on the example of the nested \code{if}
  8232. expressions with the two improvements discussed above. As you can
  8233. see, the number of basic blocks has been reduced from 10 blocks (see
  8234. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8235. \begin{figure}[tbp]
  8236. {\if\edition\racketEd
  8237. \begin{tabular}{lll}
  8238. \begin{minipage}{0.4\textwidth}
  8239. % cond_test_41.rkt
  8240. \begin{lstlisting}
  8241. (let ([x (read)])
  8242. (let ([y (read)])
  8243. (if (if (< x 1)
  8244. (eq? x 0)
  8245. (eq? x 2))
  8246. (+ y 2)
  8247. (+ y 10))))
  8248. \end{lstlisting}
  8249. \end{minipage}
  8250. &
  8251. $\Rightarrow$
  8252. &
  8253. \begin{minipage}{0.55\textwidth}
  8254. \begin{lstlisting}
  8255. start:
  8256. x = (read);
  8257. y = (read);
  8258. if (< x 1) goto block40;
  8259. else goto block41;
  8260. block40:
  8261. if (eq? x 0) goto block38;
  8262. else goto block39;
  8263. block41:
  8264. if (eq? x 2) goto block38;
  8265. else goto block39;
  8266. block38:
  8267. return (+ y 2);
  8268. block39:
  8269. return (+ y 10);
  8270. \end{lstlisting}
  8271. \end{minipage}
  8272. \end{tabular}
  8273. \fi}
  8274. {\if\edition\pythonEd
  8275. \begin{tabular}{lll}
  8276. \begin{minipage}{0.4\textwidth}
  8277. % cond_test_41.rkt
  8278. \begin{lstlisting}
  8279. x = input_int()
  8280. y = input_int()
  8281. print(y + 2 \
  8282. if (x == 0 \
  8283. if x < 1 \
  8284. else x == 2) \
  8285. else y + 10)
  8286. \end{lstlisting}
  8287. \end{minipage}
  8288. &
  8289. $\Rightarrow$
  8290. &
  8291. \begin{minipage}{0.55\textwidth}
  8292. \begin{lstlisting}
  8293. start:
  8294. x = input_int()
  8295. y = input_int()
  8296. if x < 1:
  8297. goto block_4
  8298. else:
  8299. goto block_5
  8300. block_4:
  8301. if x == 0:
  8302. goto block_2
  8303. else:
  8304. goto block_3
  8305. block_5:
  8306. if x == 2:
  8307. goto block_2
  8308. else:
  8309. goto block_3
  8310. block_2:
  8311. tmp_0 = y + 2
  8312. goto block_1
  8313. block_3:
  8314. tmp_0 = y + 10
  8315. goto block_1
  8316. block_1:
  8317. print(tmp_0)
  8318. return 0
  8319. \end{lstlisting}
  8320. \end{minipage}
  8321. \end{tabular}
  8322. \fi}
  8323. \caption{Translation from \LangIf{} to \LangCIf{}
  8324. via the improved \code{explicate\_control}.}
  8325. \label{fig:explicate-control-challenge}
  8326. \end{figure}
  8327. %% Recall that in the example output of \code{explicate\_control} in
  8328. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8329. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8330. %% block. The first goal of this challenge assignment is to remove those
  8331. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8332. %% \code{explicate\_control} on the left and shows the result of bypassing
  8333. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8334. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8335. %% \code{block55}. The optimized code on the right of
  8336. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8337. %% \code{then} branch jumping directly to \code{block55}. The story is
  8338. %% similar for the \code{else} branch, as well as for the two branches in
  8339. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8340. %% have been optimized in this way, there are no longer any jumps to
  8341. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8342. %% \begin{figure}[tbp]
  8343. %% \begin{tabular}{lll}
  8344. %% \begin{minipage}{0.4\textwidth}
  8345. %% \begin{lstlisting}
  8346. %% block62:
  8347. %% tmp54 = (read);
  8348. %% if (eq? tmp54 2) then
  8349. %% goto block59;
  8350. %% else
  8351. %% goto block60;
  8352. %% block61:
  8353. %% tmp53 = (read);
  8354. %% if (eq? tmp53 0) then
  8355. %% goto block57;
  8356. %% else
  8357. %% goto block58;
  8358. %% block60:
  8359. %% goto block56;
  8360. %% block59:
  8361. %% goto block55;
  8362. %% block58:
  8363. %% goto block56;
  8364. %% block57:
  8365. %% goto block55;
  8366. %% block56:
  8367. %% return (+ 700 77);
  8368. %% block55:
  8369. %% return (+ 10 32);
  8370. %% start:
  8371. %% tmp52 = (read);
  8372. %% if (eq? tmp52 1) then
  8373. %% goto block61;
  8374. %% else
  8375. %% goto block62;
  8376. %% \end{lstlisting}
  8377. %% \end{minipage}
  8378. %% &
  8379. %% $\Rightarrow$
  8380. %% &
  8381. %% \begin{minipage}{0.55\textwidth}
  8382. %% \begin{lstlisting}
  8383. %% block62:
  8384. %% tmp54 = (read);
  8385. %% if (eq? tmp54 2) then
  8386. %% goto block55;
  8387. %% else
  8388. %% goto block56;
  8389. %% block61:
  8390. %% tmp53 = (read);
  8391. %% if (eq? tmp53 0) then
  8392. %% goto block55;
  8393. %% else
  8394. %% goto block56;
  8395. %% block56:
  8396. %% return (+ 700 77);
  8397. %% block55:
  8398. %% return (+ 10 32);
  8399. %% start:
  8400. %% tmp52 = (read);
  8401. %% if (eq? tmp52 1) then
  8402. %% goto block61;
  8403. %% else
  8404. %% goto block62;
  8405. %% \end{lstlisting}
  8406. %% \end{minipage}
  8407. %% \end{tabular}
  8408. %% \caption{Optimize jumps by removing trivial blocks.}
  8409. %% \label{fig:optimize-jumps}
  8410. %% \end{figure}
  8411. %% The name of this pass is \code{optimize-jumps}. We recommend
  8412. %% implementing this pass in two phases. The first phrase builds a hash
  8413. %% table that maps labels to possibly improved labels. The second phase
  8414. %% changes the target of each \code{goto} to use the improved label. If
  8415. %% the label is for a trivial block, then the hash table should map the
  8416. %% label to the first non-trivial block that can be reached from this
  8417. %% label by jumping through trivial blocks. If the label is for a
  8418. %% non-trivial block, then the hash table should map the label to itself;
  8419. %% we do not want to change jumps to non-trivial blocks.
  8420. %% The first phase can be accomplished by constructing an empty hash
  8421. %% table, call it \code{short-cut}, and then iterating over the control
  8422. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8423. %% then update the hash table, mapping the block's source to the target
  8424. %% of the \code{goto}. Also, the hash table may already have mapped some
  8425. %% labels to the block's source, to you must iterate through the hash
  8426. %% table and update all of those so that they instead map to the target
  8427. %% of the \code{goto}.
  8428. %% For the second phase, we recommend iterating through the $\Tail$ of
  8429. %% each block in the program, updating the target of every \code{goto}
  8430. %% according to the mapping in \code{short-cut}.
  8431. \begin{exercise}\normalfont
  8432. Implement the improvements to the \code{explicate\_control} pass.
  8433. Check that it removes trivial blocks in a few example programs. Then
  8434. check that your compiler still passes all of your tests.
  8435. \end{exercise}
  8436. \subsection{Remove Jumps}
  8437. There is an opportunity for removing jumps that is apparent in the
  8438. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8439. ends with a jump to \code{block\_4} and there are no other jumps to
  8440. \code{block\_4} in the rest of the program. In this situation we can
  8441. avoid the runtime overhead of this jump by merging \code{block\_4}
  8442. into the preceding block, in this case the \code{start} block.
  8443. Figure~\ref{fig:remove-jumps} shows the output of
  8444. \code{select\_instructions} on the left and the result of this
  8445. optimization on the right.
  8446. \begin{figure}[tbp]
  8447. {\if\edition\racketEd
  8448. \begin{tabular}{lll}
  8449. \begin{minipage}{0.5\textwidth}
  8450. % cond_test_20.rkt
  8451. \begin{lstlisting}
  8452. start:
  8453. callq read_int
  8454. movq %rax, tmp7951
  8455. cmpq $1, tmp7951
  8456. je block7952
  8457. jmp block7953
  8458. block7953:
  8459. movq $0, %rax
  8460. jmp conclusion
  8461. block7952:
  8462. movq $42, %rax
  8463. jmp conclusion
  8464. \end{lstlisting}
  8465. \end{minipage}
  8466. &
  8467. $\Rightarrow\qquad$
  8468. \begin{minipage}{0.4\textwidth}
  8469. \begin{lstlisting}
  8470. start:
  8471. callq read_int
  8472. movq %rax, tmp7951
  8473. cmpq $1, tmp7951
  8474. je block7952
  8475. movq $0, %rax
  8476. jmp conclusion
  8477. block7952:
  8478. movq $42, %rax
  8479. jmp conclusion
  8480. \end{lstlisting}
  8481. \end{minipage}
  8482. \end{tabular}
  8483. \fi}
  8484. {\if\edition\pythonEd
  8485. \begin{tabular}{lll}
  8486. \begin{minipage}{0.5\textwidth}
  8487. % cond_test_20.rkt
  8488. \begin{lstlisting}
  8489. start:
  8490. callq read_int
  8491. movq %rax, tmp_0
  8492. cmpq 1, tmp_0
  8493. je block_3
  8494. jmp block_4
  8495. block_3:
  8496. movq 42, tmp_1
  8497. jmp block_2
  8498. block_4:
  8499. movq 0, tmp_1
  8500. jmp block_2
  8501. block_2:
  8502. movq tmp_1, %rdi
  8503. callq print_int
  8504. movq 0, %rax
  8505. jmp conclusion
  8506. \end{lstlisting}
  8507. \end{minipage}
  8508. &
  8509. $\Rightarrow\qquad$
  8510. \begin{minipage}{0.4\textwidth}
  8511. \begin{lstlisting}
  8512. start:
  8513. callq read_int
  8514. movq %rax, tmp_0
  8515. cmpq 1, tmp_0
  8516. je block_3
  8517. movq 0, tmp_1
  8518. jmp block_2
  8519. block_3:
  8520. movq 42, tmp_1
  8521. jmp block_2
  8522. block_2:
  8523. movq tmp_1, %rdi
  8524. callq print_int
  8525. movq 0, %rax
  8526. jmp conclusion
  8527. \end{lstlisting}
  8528. \end{minipage}
  8529. \end{tabular}
  8530. \fi}
  8531. \caption{Merging basic blocks by removing unnecessary jumps.}
  8532. \label{fig:remove-jumps}
  8533. \end{figure}
  8534. \begin{exercise}\normalfont
  8535. %
  8536. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8537. into their preceding basic block, when there is only one preceding
  8538. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8539. %
  8540. {\if\edition\racketEd
  8541. In the \code{run-tests.rkt} script, add the following entry to the
  8542. list of \code{passes} between \code{allocate\_registers}
  8543. and \code{patch\_instructions}.
  8544. \begin{lstlisting}
  8545. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8546. \end{lstlisting}
  8547. \fi}
  8548. %
  8549. Run the script to test your compiler.
  8550. %
  8551. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8552. blocks on several test programs.
  8553. \end{exercise}
  8554. \section{Further Reading}
  8555. \label{sec:cond-further-reading}
  8556. The algorithm for the \code{explicate\_control} pass comes from the
  8557. course notes of \citet{Dybvig:2010aa}. The use of lazy evaluation in
  8558. Section~\ref{sec:opt-jumps} to optimize basic blocks is new. There
  8559. are algorithms similar to \code{explicate\_control} in the literature,
  8560. such as the case-of-case transformation of \citet{PeytonJones:1998}.
  8561. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8562. \chapter{Loops and Dataflow Analysis}
  8563. \label{ch:Rwhile}
  8564. % TODO: define R'_8
  8565. % TODO: multi-graph
  8566. \if\edition\racketEd
  8567. %
  8568. In this chapter we study two features that are the hallmarks of
  8569. imperative programming languages: loops and assignments to local
  8570. variables. The following example demonstrates these new features by
  8571. computing the sum of the first five positive integers.
  8572. % similar to loop_test_1.rkt
  8573. \begin{lstlisting}
  8574. (let ([sum 0])
  8575. (let ([i 5])
  8576. (begin
  8577. (while (> i 0)
  8578. (begin
  8579. (set! sum (+ sum i))
  8580. (set! i (- i 1))))
  8581. sum)))
  8582. \end{lstlisting}
  8583. The \code{while} loop consists of a condition and a
  8584. body\footnote{The \code{while} loop in particular is not a built-in
  8585. feature of the Racket language, but Racket includes many looping
  8586. constructs and it is straightforward to define \code{while} as a
  8587. macro.}. The body is evaluated repeatedly so long as the condition
  8588. remains true.
  8589. %
  8590. The \code{set!} consists of a variable and a right-hand-side
  8591. expression. The \code{set!} updates value of the variable to the
  8592. value of the right-hand-side.
  8593. %
  8594. The primary purpose of both the \code{while} loop and \code{set!} is
  8595. to cause side effects, so it is convenient to also include in a
  8596. language feature for sequencing side effects: the \code{begin}
  8597. expression. It consists of one or more subexpressions that are
  8598. evaluated left-to-right.
  8599. %
  8600. \fi
  8601. \if\edition\pythonEd
  8602. %
  8603. In this chapter we study loops, one of the hallmarks of imperative
  8604. programming languages. The following example demonstrates the
  8605. \code{while} loop by computing the sum of the first five positive
  8606. integers.
  8607. \begin{lstlisting}
  8608. sum = 0
  8609. i = 5
  8610. while i > 0:
  8611. sum = sum + i
  8612. i = i - 1
  8613. print(sum)
  8614. \end{lstlisting}
  8615. The \code{while} loop consists of a condition expression and a body (a
  8616. sequence of statements). The body is evaluated repeatedly so long as
  8617. the condition remains true.
  8618. %
  8619. \fi
  8620. \section{The \LangLoop{} Language}
  8621. \begin{figure}[tp]
  8622. \centering
  8623. \fbox{
  8624. \begin{minipage}{0.96\textwidth}
  8625. \small
  8626. {\if\edition\racketEd
  8627. \[
  8628. \begin{array}{lcl}
  8629. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  8630. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8631. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8632. &\MID& \gray{\itm{bool}
  8633. \MID (\key{and}\;\Exp\;\Exp)
  8634. \MID (\key{or}\;\Exp\;\Exp)
  8635. \MID (\key{not}\;\Exp) } \\
  8636. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8637. &\MID& \CSETBANG{\Var}{\Exp}
  8638. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8639. \MID \CWHILE{\Exp}{\Exp} \\
  8640. \LangLoopM{} &::=& \gray{\Exp}
  8641. \end{array}
  8642. \]
  8643. \fi}
  8644. {\if\edition\pythonEd
  8645. \[
  8646. \begin{array}{rcl}
  8647. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  8648. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  8649. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{uniop}}{\Exp} \MID \CBINOP{\itm{binop}}{\Exp}{\Exp} \MID \Var{} \\
  8650. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  8651. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  8652. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  8653. &\MID& \key{while}~ \Exp \key{:}~ \Stmt^{+}\\
  8654. \LangLoopM{} &::=& \Stmt^{*}
  8655. \end{array}
  8656. \]
  8657. \fi}
  8658. \end{minipage}
  8659. }
  8660. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8661. \label{fig:Lwhile-concrete-syntax}
  8662. \end{figure}
  8663. \begin{figure}[tp]
  8664. \centering
  8665. \fbox{
  8666. \begin{minipage}{0.96\textwidth}
  8667. \small
  8668. {\if\edition\racketEd
  8669. \[
  8670. \begin{array}{lcl}
  8671. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8672. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8673. &\MID& \gray{ \BOOL{\itm{bool}}
  8674. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8675. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8676. \MID \WHILE{\Exp}{\Exp} \\
  8677. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8678. \end{array}
  8679. \]
  8680. \fi}
  8681. {\if\edition\pythonEd
  8682. \[
  8683. \begin{array}{lcl}
  8684. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  8685. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  8686. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8687. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  8688. \itm{bool} &::=& \code{True} \MID \code{False} \\
  8689. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  8690. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  8691. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  8692. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  8693. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  8694. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8695. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  8696. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  8697. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}\\
  8698. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  8699. \end{array}
  8700. \]
  8701. \fi}
  8702. \end{minipage}
  8703. }
  8704. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  8705. \label{fig:Lwhile-syntax}
  8706. \end{figure}
  8707. The concrete syntax of \LangLoop{} is defined in
  8708. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  8709. in Figure~\ref{fig:Lwhile-syntax}.
  8710. %
  8711. The definitional interpreter for \LangLoop{} is shown in
  8712. Figure~\ref{fig:interp-Rwhile}.
  8713. %
  8714. {\if\edition\racketEd
  8715. %
  8716. We add three new cases for \code{SetBang},
  8717. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  8718. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  8719. support assignment to variables and to make their lifetimes indefinite
  8720. (see the second example in Section~\ref{sec:assignment-scoping}), we
  8721. box the value that is bound to each variable (in \code{Let}) and
  8722. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  8723. the value.
  8724. %
  8725. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8726. variable in the environment to obtain a boxed value and then we change
  8727. it using \code{set-box!} to the result of evaluating the right-hand
  8728. side. The result value of a \code{SetBang} is \code{void}.
  8729. %
  8730. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8731. if the result is true, 2) evaluate the body.
  8732. The result value of a \code{while} loop is also \code{void}.
  8733. %
  8734. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8735. subexpressions \itm{es} for their effects and then evaluates
  8736. and returns the result from \itm{body}.
  8737. %
  8738. \fi}
  8739. {\if\edition\pythonEd
  8740. %
  8741. We add a new case for \code{While} in the \code{interp\_stmts}
  8742. function, where we repeatedly interpret the \code{body} so long as the
  8743. \code{test} expression remains true.
  8744. %
  8745. \fi}
  8746. \begin{figure}[tbp]
  8747. {\if\edition\racketEd
  8748. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8749. (define interp-Rwhile_class
  8750. (class interp-Rany_class
  8751. (super-new)
  8752. (define/override ((interp-exp env) e)
  8753. (define recur (interp-exp env))
  8754. (match e
  8755. [(SetBang x rhs)
  8756. (set-box! (lookup x env) (recur rhs))]
  8757. [(WhileLoop cnd body)
  8758. (define (loop)
  8759. (cond [(recur cnd) (recur body) (loop)]
  8760. [else (void)]))
  8761. (loop)]
  8762. [(Begin es body)
  8763. (for ([e es]) (recur e))
  8764. (recur body)]
  8765. [else ((super interp-exp env) e)]))
  8766. ))
  8767. (define (interp-Rwhile p)
  8768. (send (new interp-Rwhile_class) interp-program p))
  8769. \end{lstlisting}
  8770. \fi}
  8771. {\if\edition\pythonEd
  8772. \begin{lstlisting}
  8773. class InterpLwhile(InterpLif):
  8774. def interp_stmts(self, ss, env):
  8775. if len(ss) == 0:
  8776. return
  8777. match ss[0]:
  8778. case While(test, body, []):
  8779. while self.interp_exp(test, env):
  8780. self.interp_stmts(body, env)
  8781. return self.interp_stmts(ss[1:], env)
  8782. case _:
  8783. return super().interp_stmts(ss, env)
  8784. \end{lstlisting}
  8785. \fi}
  8786. \caption{Interpreter for \LangLoop{}.}
  8787. \label{fig:interp-Rwhile}
  8788. \end{figure}
  8789. The type checker for \LangLoop{} is defined in
  8790. Figure~\ref{fig:type-check-Rwhile}.
  8791. %
  8792. {\if\edition\racketEd
  8793. %
  8794. For \code{SetBang}, the type of the variable and the right-hand-side
  8795. must agree. The result type is \code{Void}. For the \code{WhileLoop},
  8796. the condition must be a \code{Boolean}. The result type is also
  8797. \code{Void}. For \code{Begin}, the result type is the type of its
  8798. last subexpression.
  8799. %
  8800. \fi}
  8801. %
  8802. {\if\edition\pythonEd
  8803. %
  8804. A \code{while} loop is well typed if the type of the \code{test}
  8805. expression is \code{bool} and the statements in the \code{body} are
  8806. well typed.
  8807. %
  8808. \fi}
  8809. \begin{figure}[tbp]
  8810. {\if\edition\racketEd
  8811. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8812. (define type-check-Rwhile_class
  8813. (class type-check-Rany_class
  8814. (super-new)
  8815. (inherit check-type-equal?)
  8816. (define/override (type-check-exp env)
  8817. (lambda (e)
  8818. (define recur (type-check-exp env))
  8819. (match e
  8820. [(SetBang x rhs)
  8821. (define-values (rhs^ rhsT) (recur rhs))
  8822. (define varT (dict-ref env x))
  8823. (check-type-equal? rhsT varT e)
  8824. (values (SetBang x rhs^) 'Void)]
  8825. [(WhileLoop cnd body)
  8826. (define-values (cnd^ Tc) (recur cnd))
  8827. (check-type-equal? Tc 'Boolean e)
  8828. (define-values (body^ Tbody) ((type-check-exp env) body))
  8829. (values (WhileLoop cnd^ body^) 'Void)]
  8830. [(Begin es body)
  8831. (define-values (es^ ts)
  8832. (for/lists (l1 l2) ([e es]) (recur e)))
  8833. (define-values (body^ Tbody) (recur body))
  8834. (values (Begin es^ body^) Tbody)]
  8835. [else ((super type-check-exp env) e)])))
  8836. ))
  8837. (define (type-check-Rwhile p)
  8838. (send (new type-check-Rwhile_class) type-check-program p))
  8839. \end{lstlisting}
  8840. \fi}
  8841. {\if\edition\pythonEd
  8842. \begin{lstlisting}
  8843. class TypeCheckLwhile(TypeCheckLif):
  8844. def type_check_stmts(self, ss, env):
  8845. if len(ss) == 0:
  8846. return
  8847. match ss[0]:
  8848. case While(test, body, []):
  8849. test_t = self.type_check_exp(test, env)
  8850. check_type_equal(bool, test_t, test)
  8851. body_t = self.type_check_stmts(body, env)
  8852. return self.type_check_stmts(ss[1:], env)
  8853. case _:
  8854. return super().type_check_stmts(ss, env)
  8855. \end{lstlisting}
  8856. \fi}
  8857. \caption{Type checker for the \LangLoop{} language.}
  8858. \label{fig:type-check-Rwhile}
  8859. \end{figure}
  8860. {\if\edition\racketEd
  8861. %
  8862. At first glance, the translation of these language features to x86
  8863. seems straightforward because the \LangCIf{} intermediate language
  8864. already supports all of the ingredients that we need: assignment,
  8865. \code{goto}, conditional branching, and sequencing. However, there are
  8866. complications that arise which we discuss in the next section. After
  8867. that we introduce the changes necessary to the existing passes.
  8868. %
  8869. \fi}
  8870. {\if\edition\pythonEd
  8871. %
  8872. At first glance, the translation of \code{while} loops to x86 seems
  8873. straightforward because the \LangCIf{} intermediate language already
  8874. supports \code{goto} and conditional branching. However, there are
  8875. complications that arise which we discuss in the next section. After
  8876. that we introduce the changes necessary to the existing passes.
  8877. %
  8878. \fi}
  8879. \section{Cyclic Control Flow and Dataflow Analysis}
  8880. \label{sec:dataflow-analysis}
  8881. Up until this point the control-flow graphs of the programs generated
  8882. in \code{explicate\_control} were guaranteed to be acyclic. However,
  8883. each \code{while} loop introduces a cycle in the control-flow graph.
  8884. But does that matter?
  8885. %
  8886. Indeed it does. Recall that for register allocation, the compiler
  8887. performs liveness analysis to determine which variables can share the
  8888. same register. To accomplish this we analyzed the control-flow graph
  8889. in reverse topological order
  8890. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  8891. only well-defined for acyclic graphs.
  8892. Let us return to the example of computing the sum of the first five
  8893. positive integers. Here is the program after instruction selection but
  8894. before register allocation.
  8895. \begin{center}
  8896. {\if\edition\racketEd
  8897. \begin{minipage}{0.45\textwidth}
  8898. \begin{lstlisting}
  8899. (define (main) : Integer
  8900. mainstart:
  8901. movq $0, sum
  8902. movq $5, i
  8903. jmp block5
  8904. block5:
  8905. movq i, tmp3
  8906. cmpq tmp3, $0
  8907. jl block7
  8908. jmp block8
  8909. \end{lstlisting}
  8910. \end{minipage}
  8911. \begin{minipage}{0.45\textwidth}
  8912. \begin{lstlisting}
  8913. block7:
  8914. addq i, sum
  8915. movq $1, tmp4
  8916. negq tmp4
  8917. addq tmp4, i
  8918. jmp block5
  8919. block8:
  8920. movq $27, %rax
  8921. addq sum, %rax
  8922. jmp mainconclusion
  8923. )
  8924. \end{lstlisting}
  8925. \end{minipage}
  8926. \fi}
  8927. {\if\edition\pythonEd
  8928. \begin{minipage}{0.45\textwidth}
  8929. \begin{lstlisting}
  8930. mainstart:
  8931. movq $0, sum
  8932. movq $5, i
  8933. jmp block5
  8934. block5:
  8935. cmpq $0, i
  8936. jg block7
  8937. jmp block8
  8938. \end{lstlisting}
  8939. \end{minipage}
  8940. \begin{minipage}{0.45\textwidth}
  8941. \begin{lstlisting}
  8942. block7:
  8943. addq i, sum
  8944. subq $1, i
  8945. jmp block5
  8946. block8:
  8947. movq sum, %rdi
  8948. callq print_int
  8949. movq $0, %rax
  8950. jmp mainconclusion
  8951. \end{lstlisting}
  8952. \end{minipage}
  8953. \fi}
  8954. \end{center}
  8955. Recall that liveness analysis works backwards, starting at the end
  8956. of each function. For this example we could start with \code{block8}
  8957. because we know what is live at the beginning of the conclusion,
  8958. just \code{rax} and \code{rsp}. So the live-before set
  8959. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  8960. %
  8961. Next we might try to analyze \code{block5} or \code{block7}, but
  8962. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  8963. we are stuck.
  8964. The way out of this impasse is to realize that we can compute an
  8965. under-approximation of the live-before set by starting with empty
  8966. live-after sets. By \emph{under-approximation}, we mean that the set
  8967. only contains variables that are really live, but it may be missing
  8968. some. Next, the under-approximations for each block can be improved
  8969. by 1) updating the live-after set for each block using the approximate
  8970. live-before sets from the other blocks and 2) perform liveness
  8971. analysis again on each block. In fact, by iterating this process, the
  8972. under-approximations eventually become the correct solutions!
  8973. %
  8974. This approach of iteratively analyzing a control-flow graph is
  8975. applicable to many static analysis problems and goes by the name
  8976. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  8977. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  8978. Washington.
  8979. Let us apply this approach to the above example. We use the empty set
  8980. for the initial live-before set for each block. Let $m_0$ be the
  8981. following mapping from label names to sets of locations (variables and
  8982. registers).
  8983. \begin{center}
  8984. \begin{lstlisting}
  8985. mainstart: {}
  8986. block5: {}
  8987. block7: {}
  8988. block8: {}
  8989. \end{lstlisting}
  8990. \end{center}
  8991. Using the above live-before approximations, we determine the
  8992. live-after for each block and then apply liveness analysis to each
  8993. block. This produces our next approximation $m_1$ of the live-before
  8994. sets.
  8995. \begin{center}
  8996. \begin{lstlisting}
  8997. mainstart: {}
  8998. block5: {i}
  8999. block7: {i, sum}
  9000. block8: {rsp, sum}
  9001. \end{lstlisting}
  9002. \end{center}
  9003. For the second round, the live-after for \code{mainstart} is the
  9004. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9005. liveness analysis for \code{mainstart} computes the empty set. The
  9006. live-after for \code{block5} is the union of the live-before sets for
  9007. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9008. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9009. sum\}}. The live-after for \code{block7} is the live-before for
  9010. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9011. So the liveness analysis for \code{block7} remains \code{\{i,
  9012. sum\}}. Together these yield the following approximation $m_2$ of
  9013. the live-before sets.
  9014. \begin{center}
  9015. \begin{lstlisting}
  9016. mainstart: {}
  9017. block5: {i, rsp, sum}
  9018. block7: {i, sum}
  9019. block8: {rsp, sum}
  9020. \end{lstlisting}
  9021. \end{center}
  9022. In the preceding iteration, only \code{block5} changed, so we can
  9023. limit our attention to \code{mainstart} and \code{block7}, the two
  9024. blocks that jump to \code{block5}. As a result, the live-before sets
  9025. for \code{mainstart} and \code{block7} are updated to include
  9026. \code{rsp}, yielding the following approximation $m_3$.
  9027. \begin{center}
  9028. \begin{lstlisting}
  9029. mainstart: {rsp}
  9030. block5: {i, rsp, sum}
  9031. block7: {i, rsp, sum}
  9032. block8: {rsp, sum}
  9033. \end{lstlisting}
  9034. \end{center}
  9035. Because \code{block7} changed, we analyze \code{block5} once more, but
  9036. its live-before set remains \code{\{ i, rsp, sum \}}. At this point
  9037. our approximations have converged, so $m_3$ is the solution.
  9038. This iteration process is guaranteed to converge to a solution by the
  9039. Kleene Fixed-Point Theorem, a general theorem about functions on
  9040. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9041. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9042. elements, a least element $\bot$ (pronounced bottom), and a join
  9043. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9044. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9045. working with join semi-lattices.} When two elements are ordered $m_i
  9046. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9047. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9048. approximation than $m_i$. The bottom element $\bot$ represents the
  9049. complete lack of information, i.e., the worst approximation. The join
  9050. operator takes two lattice elements and combines their information,
  9051. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9052. bound}
  9053. A dataflow analysis typically involves two lattices: one lattice to
  9054. represent abstract states and another lattice that aggregates the
  9055. abstract states of all the blocks in the control-flow graph. For
  9056. liveness analysis, an abstract state is a set of locations. We form
  9057. the lattice $L$ by taking its elements to be sets of locations, the
  9058. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9059. set, and the join operator to be set union.
  9060. %
  9061. We form a second lattice $M$ by taking its elements to be mappings
  9062. from the block labels to sets of locations (elements of $L$). We
  9063. order the mappings point-wise, using the ordering of $L$. So given any
  9064. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9065. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9066. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9067. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9068. We can think of one iteration of liveness analysis as being a function
  9069. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9070. mapping.
  9071. \[
  9072. f(m_i) = m_{i+1}
  9073. \]
  9074. Next let us think for a moment about what a final solution $m_s$
  9075. should look like. If we perform liveness analysis using the solution
  9076. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9077. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9078. \[
  9079. f(m_s) = m_s
  9080. \]
  9081. Furthermore, the solution should only include locations that are
  9082. forced to be there by performing liveness analysis on the program, so
  9083. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9084. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9085. monotone (better inputs produce better outputs), then the least fixed
  9086. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9087. chain} obtained by starting at $\bot$ and iterating $f$ as
  9088. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9089. \[
  9090. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9091. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9092. \]
  9093. When a lattice contains only finitely-long ascending chains, then
  9094. every Kleene chain tops out at some fixed point after a number of
  9095. iterations of $f$.
  9096. \[
  9097. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9098. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9099. \]
  9100. The liveness analysis is indeed a monotone function and the lattice
  9101. $M$ only has finitely-long ascending chains because there are only a
  9102. finite number of variables and blocks in the program. Thus we are
  9103. guaranteed that iteratively applying liveness analysis to all blocks
  9104. in the program will eventually produce the least fixed point solution.
  9105. Next let us consider dataflow analysis in general and discuss the
  9106. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9107. %
  9108. The algorithm has four parameters: the control-flow graph \code{G}, a
  9109. function \code{transfer} that applies the analysis to one block, the
  9110. \code{bottom} and \code{join} operator for the lattice of abstract
  9111. states. The algorithm begins by creating the bottom mapping,
  9112. represented by a hash table. It then pushes all of the nodes in the
  9113. control-flow graph onto the work list (a queue). The algorithm repeats
  9114. the \code{while} loop as long as there are items in the work list. In
  9115. each iteration, a node is popped from the work list and processed. The
  9116. \code{input} for the node is computed by taking the join of the
  9117. abstract states of all the predecessor nodes. The \code{transfer}
  9118. function is then applied to obtain the \code{output} abstract
  9119. state. If the output differs from the previous state for this block,
  9120. the mapping for this block is updated and its successor nodes are
  9121. pushed onto the work list.
  9122. \begin{figure}[tb]
  9123. {\if\edition\racketEd
  9124. \begin{lstlisting}
  9125. (define (analyze_dataflow G transfer bottom join)
  9126. (define mapping (make-hash))
  9127. (for ([v (in-vertices G)])
  9128. (dict-set! mapping v bottom))
  9129. (define worklist (make-queue))
  9130. (for ([v (in-vertices G)])
  9131. (enqueue! worklist v))
  9132. (define trans-G (transpose G))
  9133. (while (not (queue-empty? worklist))
  9134. (define node (dequeue! worklist))
  9135. (define input (for/fold ([state bottom])
  9136. ([pred (in-neighbors trans-G node)])
  9137. (join state (dict-ref mapping pred))))
  9138. (define output (transfer node input))
  9139. (cond [(not (equal? output (dict-ref mapping node)))
  9140. (dict-set! mapping node output)
  9141. (for ([v (in-neighbors G node)])
  9142. (enqueue! worklist v))]))
  9143. mapping)
  9144. \end{lstlisting}
  9145. \fi}
  9146. {\if\edition\pythonEd
  9147. \begin{lstlisting}
  9148. def analyze_dataflow(G, transfer, bottom, join):
  9149. trans_G = transpose(G)
  9150. mapping = {}
  9151. for v in G.vertices():
  9152. mapping[v] = bottom
  9153. worklist = deque()
  9154. for v in G.vertices():
  9155. worklist.append(v)
  9156. while worklist:
  9157. node = worklist.pop()
  9158. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9159. output = transfer(node, input)
  9160. if output != mapping[node]:
  9161. mapping[node] = output
  9162. for v in G.adjacent(node):
  9163. worklist.append(v)
  9164. \end{lstlisting}
  9165. \fi}
  9166. \caption{Generic work list algorithm for dataflow analysis}
  9167. \label{fig:generic-dataflow}
  9168. \end{figure}
  9169. Having discussed the complications that arise from adding support for
  9170. assignment and loops, we turn to discussing the significant changes to
  9171. existing passes.
  9172. \section{Remove Complex Operands}
  9173. \label{sec:rco-loop}
  9174. {\if\edition\racketEd
  9175. %
  9176. The three new language forms, \code{while}, \code{set!}, and
  9177. \code{begin} are all complex expressions and their subexpressions are
  9178. allowed to be complex.
  9179. %
  9180. \fi}
  9181. {\if\edition\pythonEd
  9182. %
  9183. The change needed for this pass is to add a case for the \code{while}
  9184. statement. The condition of a \code{while} loop is allowed to be a
  9185. complex expression, just like the condition of the \code{if}
  9186. statement.
  9187. %
  9188. \fi}
  9189. %
  9190. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9191. \LangLoopANF{} of this pass.
  9192. \begin{figure}[tp]
  9193. \centering
  9194. \fbox{
  9195. \begin{minipage}{0.96\textwidth}
  9196. \small
  9197. {\if\edition\racketEd
  9198. \[
  9199. \begin{array}{rcl}
  9200. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  9201. \MID \VOID{} } \\
  9202. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9203. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  9204. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9205. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9206. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9207. \end{array}
  9208. \]
  9209. \fi}
  9210. {\if\edition\pythonEd
  9211. \[
  9212. \begin{array}{rcl}
  9213. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9214. \Exp &::=& \Atm \MID \READ{} \\
  9215. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  9216. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9217. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9218. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9219. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9220. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9221. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9222. \end{array}
  9223. \]
  9224. \fi}
  9225. \end{minipage}
  9226. }
  9227. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  9228. \label{fig:Rwhile-anf-syntax}
  9229. \end{figure}
  9230. {\if\edition\racketEd
  9231. As usual, when a complex expression appears in a grammar position that
  9232. needs to be atomic, such as the argument of a primitive operator, we
  9233. must introduce a temporary variable and bind it to the complex
  9234. expression. This approach applies, unchanged, to handle the new
  9235. language forms. For example, in the following code there are two
  9236. \code{begin} expressions appearing as arguments to \code{+}. The
  9237. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9238. expressions have been bound to temporary variables. Recall that
  9239. \code{let} expressions in \LangLoopANF{} are allowed to have
  9240. arbitrary expressions in their right-hand-side expression, so it is
  9241. fine to place \code{begin} there.
  9242. \begin{lstlisting}
  9243. (let ([x0 10])
  9244. (let ([y1 0])
  9245. (+ (+ (begin (set! y1 (read)) x0)
  9246. (begin (set! x0 (read)) y1))
  9247. x0)))
  9248. |$\Rightarrow$|
  9249. (let ([x0 10])
  9250. (let ([y1 0])
  9251. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9252. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9253. (let ([tmp4 (+ tmp2 tmp3)])
  9254. (+ tmp4 x0))))))
  9255. \end{lstlisting}
  9256. \fi}
  9257. \section{Explicate Control \racket{and \LangCLoop{}}}
  9258. \label{sec:explicate-loop}
  9259. {\if\edition\racketEd
  9260. Recall that in the \code{explicate\_control} pass we define one helper
  9261. function for each kind of position in the program. For the \LangVar{}
  9262. language of integers and variables we needed kinds of positions:
  9263. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9264. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9265. yet another kind of position: effect position. Except for the last
  9266. subexpression, the subexpressions inside a \code{begin} are evaluated
  9267. only for their effect. Their result values are discarded. We can
  9268. generate better code by taking this fact into account.
  9269. The output language of \code{explicate\_control} is \LangCLoop{}
  9270. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9271. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9272. \code{read} may also appear as statements. The most significant
  9273. difference between \LangCLam{} and \LangCLoop{} is that the
  9274. control-flow graphs of the later may contain cycles.
  9275. \begin{figure}[tp]
  9276. \fbox{
  9277. \begin{minipage}{0.96\textwidth}
  9278. \small
  9279. \[
  9280. \begin{array}{lcl}
  9281. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9282. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9283. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  9284. % &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9285. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9286. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9287. \end{array}
  9288. \]
  9289. \end{minipage}
  9290. }
  9291. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9292. \label{fig:c7-syntax}
  9293. \end{figure}
  9294. The new auxiliary function \code{explicate\_effect} takes an expression
  9295. (in an effect position) and a promise of a continuation block. The
  9296. function returns a promise for a $\Tail$ that includes the generated
  9297. code for the input expression followed by the continuation block. If
  9298. the expression is obviously pure, that is, never causes side effects,
  9299. then the expression can be removed, so the result is just the
  9300. continuation block.
  9301. %
  9302. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9303. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9304. the loop. Recursively process the \itm{body} (in effect position)
  9305. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9306. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9307. \itm{body'} as the then-branch and the continuation block as the
  9308. else-branch. The result should be added to the control-flow graph with
  9309. the label \itm{loop}. The result for the whole \code{while} loop is a
  9310. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9311. added to the control-flow graph if the loop is indeed used, which can
  9312. be accomplished using \code{delay}.
  9313. The auxiliary functions for tail, assignment, and predicate positions
  9314. need to be updated. The three new language forms, \code{while},
  9315. \code{set!}, and \code{begin}, can appear in assignment and tail
  9316. positions. Only \code{begin} may appear in predicate positions; the
  9317. other two have result type \code{Void}.
  9318. \fi}
  9319. %
  9320. {\if\edition\pythonEd
  9321. %
  9322. The output of this pass is the language \LangCIf{}. No new language
  9323. features are needed in the output because a \code{while} loop can be
  9324. expressed in terms of \code{goto} and \code{if} statements, which are
  9325. already in \LangCIf{}.
  9326. %
  9327. Add a case for the \code{while} statement to the
  9328. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9329. the condition expression.
  9330. %
  9331. \fi}
  9332. {\if\edition\racketEd
  9333. \section{Select Instructions}
  9334. \label{sec:select-instructions-loop}
  9335. Only three small additions are needed in the
  9336. \code{select\_instructions} pass to handle the changes to \LangCLoop{}. That
  9337. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9338. stand-alone statements instead of only appearing on the right-hand
  9339. side of an assignment statement. The code generation is nearly
  9340. identical; just leave off the instruction for moving the result into
  9341. the left-hand side.
  9342. \fi}
  9343. \section{Register Allocation}
  9344. \label{sec:register-allocation-loop}
  9345. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9346. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9347. which complicates the liveness analysis needed for register
  9348. allocation.
  9349. \subsection{Liveness Analysis}
  9350. \label{sec:liveness-analysis-r8}
  9351. We recommend using the generic \code{analyze\_dataflow} function that
  9352. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9353. perform liveness analysis, replacing the code in
  9354. \code{uncover\_live} that processed the basic blocks in topological
  9355. order (Section~\ref{sec:liveness-analysis-Lif}).
  9356. The \code{analyze\_dataflow} function has four parameters.
  9357. \begin{enumerate}
  9358. \item The first parameter \code{G} should be a directed graph from the
  9359. \racket{
  9360. \code{racket/graph} package (see the sidebar in
  9361. Section~\ref{sec:build-interference})}
  9362. \python{\code{graph.py} file in the support code}
  9363. that represents the
  9364. control-flow graph.
  9365. \item The second parameter \code{transfer} is a function that applies
  9366. liveness analysis to a basic block. It takes two parameters: the
  9367. label for the block to analyze and the live-after set for that
  9368. block. The transfer function should return the live-before set for
  9369. the block.
  9370. %
  9371. \racket{Also, as a side-effect, it should update the block's
  9372. $\itm{info}$ with the liveness information for each instruction.}
  9373. %
  9374. \python{Also, as a side-effect, it should update the live-before and
  9375. live-after sets for each instruction.}
  9376. %
  9377. To implement the \code{transfer} function, you should be able to
  9378. reuse the code you already have for analyzing basic blocks.
  9379. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9380. \code{bottom} and \code{join} for the lattice of abstract states,
  9381. i.e. sets of locations. The bottom of the lattice is the empty set
  9382. and the join operator is set union.
  9383. \end{enumerate}
  9384. \begin{figure}[p]
  9385. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9386. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9387. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9388. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9389. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9390. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9391. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9392. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9393. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9394. \node (F1-5) at (9,2) {\large \LangLoop{}};
  9395. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9396. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9397. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9398. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9399. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9400. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9401. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9402. %% \path[->,bend left=15] (Rfun) edge [above] node
  9403. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9404. \path[->,bend left=15] (Rfun) edge [above] node
  9405. {\ttfamily\footnotesize shrink} (Rfun-2);
  9406. \path[->,bend left=15] (Rfun-2) edge [above] node
  9407. {\ttfamily\footnotesize uniquify} (F1-4);
  9408. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9409. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9410. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9411. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9412. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9413. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9414. %% \path[->,bend right=15] (F1-2) edge [above] node
  9415. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9416. %% \path[->,bend right=15] (F1-3) edge [above] node
  9417. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9418. \path[->,bend left=15] (F1-4) edge [above] node
  9419. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9420. \path[->,bend left=15] (F1-5) edge [right] node
  9421. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9422. \path[->,bend left=15] (C3-2) edge [left] node
  9423. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9424. \path[->,bend right=15] (x86-2) edge [left] node
  9425. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9426. \path[->,bend right=15] (x86-2-1) edge [below] node
  9427. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9428. \path[->,bend right=15] (x86-2-2) edge [left] node
  9429. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9430. \path[->,bend left=15] (x86-3) edge [above] node
  9431. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9432. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9433. \end{tikzpicture}
  9434. \caption{Diagram of the passes for \LangLoop{}.}
  9435. \label{fig:Rwhile-passes}
  9436. \end{figure}
  9437. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9438. for the compilation of \LangLoop{}.
  9439. % Further Reading: dataflow analysis
  9440. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9441. \chapter{Tuples and Garbage Collection}
  9442. \label{ch:Rvec}
  9443. \index{subject}{tuple}
  9444. \index{subject}{vector}
  9445. \if\edition\racketEd
  9446. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9447. %% all the IR grammars are spelled out! \\ --Jeremy}
  9448. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9449. %% the root stack. \\ --Jeremy}
  9450. In this chapter we study the implementation of mutable tuples, called
  9451. vectors in Racket. This language feature is the first to use the
  9452. computer's \emph{heap}\index{subject}{heap} because the lifetime of a
  9453. Racket tuple is indefinite, that is, a tuple lives forever from the
  9454. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  9455. is important to reclaim the space associated with a tuple when it is
  9456. no longer needed, which is why we also study \emph{garbage
  9457. collection} \index{garbage collection} techniques in this chapter.
  9458. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9459. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  9460. language of Chapter~\ref{ch:Lif} with vectors and Racket's
  9461. \code{void} value. The reason for including the later is that the
  9462. \code{vector-set!} operation returns a value of type
  9463. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  9464. called the \code{Unit} type in the programming languages
  9465. literature. Racket's \code{Void} type is inhabited by a single value
  9466. \code{void} which corresponds to \code{unit} or \code{()} in the
  9467. literature~\citep{Pierce:2002hj}.}.
  9468. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9469. copying live objects back and forth between two halves of the
  9470. heap. The garbage collector requires coordination with the compiler so
  9471. that it can see all of the \emph{root} pointers, that is, pointers in
  9472. registers or on the procedure call stack.
  9473. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9474. discuss all the necessary changes and additions to the compiler
  9475. passes, including a new compiler pass named \code{expose-allocation}.
  9476. \section{The \LangVec{} Language}
  9477. \label{sec:r3}
  9478. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  9479. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  9480. \LangVec{} language includes three new forms: \code{vector} for creating a
  9481. tuple, \code{vector-ref} for reading an element of a tuple, and
  9482. \code{vector-set!} for writing to an element of a tuple. The program
  9483. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  9484. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  9485. the 3-tuple, demonstrating that tuples are first-class values. The
  9486. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  9487. of the \key{if} is taken. The element at index $0$ of \code{t} is
  9488. \code{40}, to which we add \code{2}, the element at index $0$ of the
  9489. 1-tuple. So the result of the program is \code{42}.
  9490. \begin{figure}[tbp]
  9491. \centering
  9492. \fbox{
  9493. \begin{minipage}{0.96\textwidth}
  9494. \[
  9495. \begin{array}{lcl}
  9496. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  9497. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  9498. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9499. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9500. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  9501. \MID \LP\key{and}\;\Exp\;\Exp\RP
  9502. \MID \LP\key{or}\;\Exp\;\Exp\RP
  9503. \MID \LP\key{not}\;\Exp\RP } \\
  9504. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  9505. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9506. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  9507. \MID \LP\key{vector-length}\;\Exp\RP \\
  9508. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9509. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  9510. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  9511. \LangVecM{} &::=& \Exp
  9512. \end{array}
  9513. \]
  9514. \end{minipage}
  9515. }
  9516. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  9517. (Figure~\ref{fig:Lif-concrete-syntax}).}
  9518. \label{fig:Rvec-concrete-syntax}
  9519. \end{figure}
  9520. \begin{figure}[tbp]
  9521. \begin{lstlisting}
  9522. (let ([t (vector 40 #t (vector 2))])
  9523. (if (vector-ref t 1)
  9524. (+ (vector-ref t 0)
  9525. (vector-ref (vector-ref t 2) 0))
  9526. 44))
  9527. \end{lstlisting}
  9528. \caption{Example program that creates tuples and reads from them.}
  9529. \label{fig:vector-eg}
  9530. \end{figure}
  9531. \begin{figure}[tp]
  9532. \centering
  9533. \fbox{
  9534. \begin{minipage}{0.96\textwidth}
  9535. \[
  9536. \begin{array}{lcl}
  9537. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  9538. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9539. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  9540. \MID \BOOL{\itm{bool}}
  9541. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9542. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  9543. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9544. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  9545. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9546. \end{array}
  9547. \]
  9548. \end{minipage}
  9549. }
  9550. \caption{The abstract syntax of \LangVec{}.}
  9551. \label{fig:Rvec-syntax}
  9552. \end{figure}
  9553. \index{subject}{allocate}
  9554. \index{subject}{heap allocate}
  9555. Tuples are our first encounter with heap-allocated data, which raises
  9556. several interesting issues. First, variable binding performs a
  9557. shallow-copy when dealing with tuples, which means that different
  9558. variables can refer to the same tuple, that is, different variables
  9559. can be \emph{aliases} for the same entity. Consider the following
  9560. example in which both \code{t1} and \code{t2} refer to the same tuple.
  9561. Thus, the mutation through \code{t2} is visible when referencing the
  9562. tuple from \code{t1}, so the result of this program is \code{42}.
  9563. \index{subject}{alias}\index{subject}{mutation}
  9564. \begin{center}
  9565. \begin{minipage}{0.96\textwidth}
  9566. \begin{lstlisting}
  9567. (let ([t1 (vector 3 7)])
  9568. (let ([t2 t1])
  9569. (let ([_ (vector-set! t2 0 42)])
  9570. (vector-ref t1 0))))
  9571. \end{lstlisting}
  9572. \end{minipage}
  9573. \end{center}
  9574. The next issue concerns the lifetime of tuples. Of course, they are
  9575. created by the \code{vector} form, but when does their lifetime end?
  9576. Notice that \LangVec{} does not include an operation for deleting
  9577. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  9578. of static scoping. For example, the following program returns
  9579. \code{42} even though the variable \code{w} goes out of scope prior to
  9580. the \code{vector-ref} that reads from the vector it was bound to.
  9581. \begin{center}
  9582. \begin{minipage}{0.96\textwidth}
  9583. \begin{lstlisting}
  9584. (let ([v (vector (vector 44))])
  9585. (let ([x (let ([w (vector 42)])
  9586. (let ([_ (vector-set! v 0 w)])
  9587. 0))])
  9588. (+ x (vector-ref (vector-ref v 0) 0))))
  9589. \end{lstlisting}
  9590. \end{minipage}
  9591. \end{center}
  9592. From the perspective of programmer-observable behavior, tuples live
  9593. forever. Of course, if they really lived forever, then many programs
  9594. would run out of memory.\footnote{The \LangVec{} language does not have
  9595. looping or recursive functions, so it is nigh impossible to write a
  9596. program in \LangVec{} that will run out of memory. However, we add
  9597. recursive functions in the next Chapter!} A Racket implementation
  9598. must therefore perform automatic garbage collection.
  9599. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  9600. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  9601. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  9602. terms of the corresponding operations in Racket. One subtle point is
  9603. that the \code{vector-set!} operation returns the \code{\#<void>}
  9604. value. The \code{\#<void>} value can be passed around just like other
  9605. values inside an \LangVec{} program and a \code{\#<void>} value can be
  9606. compared for equality with another \code{\#<void>} value. However,
  9607. there are no other operations specific to the the \code{\#<void>}
  9608. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  9609. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  9610. otherwise.
  9611. \begin{figure}[tbp]
  9612. \begin{lstlisting}
  9613. (define interp-Rvec_class
  9614. (class interp-Lif_class
  9615. (super-new)
  9616. (define/override (interp-op op)
  9617. (match op
  9618. ['eq? (lambda (v1 v2)
  9619. (cond [(or (and (fixnum? v1) (fixnum? v2))
  9620. (and (boolean? v1) (boolean? v2))
  9621. (and (vector? v1) (vector? v2))
  9622. (and (void? v1) (void? v2)))
  9623. (eq? v1 v2)]))]
  9624. ['vector vector]
  9625. ['vector-length vector-length]
  9626. ['vector-ref vector-ref]
  9627. ['vector-set! vector-set!]
  9628. [else (super interp-op op)]
  9629. ))
  9630. (define/override ((interp-exp env) e)
  9631. (define recur (interp-exp env))
  9632. (match e
  9633. [(HasType e t) (recur e)]
  9634. [(Void) (void)]
  9635. [else ((super interp-exp env) e)]
  9636. ))
  9637. ))
  9638. (define (interp-Rvec p)
  9639. (send (new interp-Rvec_class) interp-program p))
  9640. \end{lstlisting}
  9641. \caption{Interpreter for the \LangVec{} language.}
  9642. \label{fig:interp-Rvec}
  9643. \end{figure}
  9644. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  9645. deserves some explanation. When allocating a vector, we need to know
  9646. which elements of the vector are pointers (i.e. are also vectors). We
  9647. can obtain this information during type checking. The type checker in
  9648. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  9649. expression, it also wraps every \key{vector} creation with the form
  9650. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  9651. %
  9652. To create the s-expression for the \code{Vector} type in
  9653. Figure~\ref{fig:type-check-Rvec}, we use the
  9654. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  9655. operator} \code{,@} to insert the list \code{t*} without its usual
  9656. start and end parentheses. \index{subject}{unquote-slicing}
  9657. \begin{figure}[tp]
  9658. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9659. (define type-check-Rvec_class
  9660. (class type-check-Lif_class
  9661. (super-new)
  9662. (inherit check-type-equal?)
  9663. (define/override (type-check-exp env)
  9664. (lambda (e)
  9665. (define recur (type-check-exp env))
  9666. (match e
  9667. [(Void) (values (Void) 'Void)]
  9668. [(Prim 'vector es)
  9669. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  9670. (define t `(Vector ,@t*))
  9671. (values (HasType (Prim 'vector e*) t) t)]
  9672. [(Prim 'vector-ref (list e1 (Int i)))
  9673. (define-values (e1^ t) (recur e1))
  9674. (match t
  9675. [`(Vector ,ts ...)
  9676. (unless (and (0 . <= . i) (i . < . (length ts)))
  9677. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  9678. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  9679. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  9680. [(Prim 'vector-set! (list e1 (Int i) arg) )
  9681. (define-values (e-vec t-vec) (recur e1))
  9682. (define-values (e-arg^ t-arg) (recur arg))
  9683. (match t-vec
  9684. [`(Vector ,ts ...)
  9685. (unless (and (0 . <= . i) (i . < . (length ts)))
  9686. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  9687. (check-type-equal? (list-ref ts i) t-arg e)
  9688. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  9689. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  9690. [(Prim 'vector-length (list e))
  9691. (define-values (e^ t) (recur e))
  9692. (match t
  9693. [`(Vector ,ts ...)
  9694. (values (Prim 'vector-length (list e^)) 'Integer)]
  9695. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  9696. [(Prim 'eq? (list arg1 arg2))
  9697. (define-values (e1 t1) (recur arg1))
  9698. (define-values (e2 t2) (recur arg2))
  9699. (match* (t1 t2)
  9700. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9701. [(other wise) (check-type-equal? t1 t2 e)])
  9702. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9703. [(HasType (Prim 'vector es) t)
  9704. ((type-check-exp env) (Prim 'vector es))]
  9705. [(HasType e1 t)
  9706. (define-values (e1^ t^) (recur e1))
  9707. (check-type-equal? t t^ e)
  9708. (values (HasType e1^ t) t)]
  9709. [else ((super type-check-exp env) e)]
  9710. )))
  9711. ))
  9712. (define (type-check-Rvec p)
  9713. (send (new type-check-Rvec_class) type-check-program p))
  9714. \end{lstlisting}
  9715. \caption{Type checker for the \LangVec{} language.}
  9716. \label{fig:type-check-Rvec}
  9717. \end{figure}
  9718. \section{Garbage Collection}
  9719. \label{sec:GC}
  9720. Here we study a relatively simple algorithm for garbage collection
  9721. that is the basis of state-of-the-art garbage
  9722. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  9723. particular, we describe a two-space copying
  9724. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  9725. perform the
  9726. copy~\citep{Cheney:1970aa}.
  9727. \index{subject}{copying collector}
  9728. \index{subject}{two-space copying collector}
  9729. Figure~\ref{fig:copying-collector} gives a
  9730. coarse-grained depiction of what happens in a two-space collector,
  9731. showing two time steps, prior to garbage collection (on the top) and
  9732. after garbage collection (on the bottom). In a two-space collector,
  9733. the heap is divided into two parts named the FromSpace and the
  9734. ToSpace. Initially, all allocations go to the FromSpace until there is
  9735. not enough room for the next allocation request. At that point, the
  9736. garbage collector goes to work to make more room.
  9737. \index{subject}{ToSpace}
  9738. \index{subject}{FromSpace}
  9739. The garbage collector must be careful not to reclaim tuples that will
  9740. be used by the program in the future. Of course, it is impossible in
  9741. general to predict what a program will do, but we can over approximate
  9742. the will-be-used tuples by preserving all tuples that could be
  9743. accessed by \emph{any} program given the current computer state. A
  9744. program could access any tuple whose address is in a register or on
  9745. the procedure call stack. These addresses are called the \emph{root
  9746. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  9747. transitively reachable from the root set. Thus, it is safe for the
  9748. garbage collector to reclaim the tuples that are not reachable in this
  9749. way.
  9750. So the goal of the garbage collector is twofold:
  9751. \begin{enumerate}
  9752. \item preserve all tuple that are reachable from the root set via a
  9753. path of pointers, that is, the \emph{live} tuples, and
  9754. \item reclaim the memory of everything else, that is, the
  9755. \emph{garbage}.
  9756. \end{enumerate}
  9757. A copying collector accomplishes this by copying all of the live
  9758. objects from the FromSpace into the ToSpace and then performs a sleight
  9759. of hand, treating the ToSpace as the new FromSpace and the old
  9760. FromSpace as the new ToSpace. In the example of
  9761. Figure~\ref{fig:copying-collector}, there are three pointers in the
  9762. root set, one in a register and two on the stack. All of the live
  9763. objects have been copied to the ToSpace (the right-hand side of
  9764. Figure~\ref{fig:copying-collector}) in a way that preserves the
  9765. pointer relationships. For example, the pointer in the register still
  9766. points to a 2-tuple whose first element is a 3-tuple and whose second
  9767. element is a 2-tuple. There are four tuples that are not reachable
  9768. from the root set and therefore do not get copied into the ToSpace.
  9769. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  9770. created by a well-typed program in \LangVec{} because it contains a
  9771. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  9772. We design the garbage collector to deal with cycles to begin with so
  9773. we will not need to revisit this issue.
  9774. \begin{figure}[tbp]
  9775. \centering
  9776. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  9777. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  9778. \caption{A copying collector in action.}
  9779. \label{fig:copying-collector}
  9780. \end{figure}
  9781. There are many alternatives to copying collectors (and their bigger
  9782. siblings, the generational collectors) when its comes to garbage
  9783. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  9784. reference counting~\citep{Collins:1960aa}. The strengths of copying
  9785. collectors are that allocation is fast (just a comparison and pointer
  9786. increment), there is no fragmentation, cyclic garbage is collected,
  9787. and the time complexity of collection only depends on the amount of
  9788. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  9789. main disadvantages of a two-space copying collector is that it uses a
  9790. lot of space and takes a long time to perform the copy, though these
  9791. problems are ameliorated in generational collectors. Racket and
  9792. Scheme programs tend to allocate many small objects and generate a lot
  9793. of garbage, so copying and generational collectors are a good fit.
  9794. Garbage collection is an active research topic, especially concurrent
  9795. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  9796. developing new techniques and revisiting old
  9797. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  9798. meet every year at the International Symposium on Memory Management to
  9799. present these findings.
  9800. \subsection{Graph Copying via Cheney's Algorithm}
  9801. \label{sec:cheney}
  9802. \index{subject}{Cheney's algorithm}
  9803. Let us take a closer look at the copying of the live objects. The
  9804. allocated objects and pointers can be viewed as a graph and we need to
  9805. copy the part of the graph that is reachable from the root set. To
  9806. make sure we copy all of the reachable vertices in the graph, we need
  9807. an exhaustive graph traversal algorithm, such as depth-first search or
  9808. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  9809. such algorithms take into account the possibility of cycles by marking
  9810. which vertices have already been visited, so as to ensure termination
  9811. of the algorithm. These search algorithms also use a data structure
  9812. such as a stack or queue as a to-do list to keep track of the vertices
  9813. that need to be visited. We use breadth-first search and a trick
  9814. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  9815. and copying tuples into the ToSpace.
  9816. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  9817. copy progresses. The queue is represented by a chunk of contiguous
  9818. memory at the beginning of the ToSpace, using two pointers to track
  9819. the front and the back of the queue. The algorithm starts by copying
  9820. all tuples that are immediately reachable from the root set into the
  9821. ToSpace to form the initial queue. When we copy a tuple, we mark the
  9822. old tuple to indicate that it has been visited. We discuss how this
  9823. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  9824. pointers inside the copied tuples in the queue still point back to the
  9825. FromSpace. Once the initial queue has been created, the algorithm
  9826. enters a loop in which it repeatedly processes the tuple at the front
  9827. of the queue and pops it off the queue. To process a tuple, the
  9828. algorithm copies all the tuple that are directly reachable from it to
  9829. the ToSpace, placing them at the back of the queue. The algorithm then
  9830. updates the pointers in the popped tuple so they point to the newly
  9831. copied tuples.
  9832. \begin{figure}[tbp]
  9833. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  9834. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  9835. \label{fig:cheney}
  9836. \end{figure}
  9837. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  9838. tuple whose second element is $42$ to the back of the queue. The other
  9839. pointer goes to a tuple that has already been copied, so we do not
  9840. need to copy it again, but we do need to update the pointer to the new
  9841. location. This can be accomplished by storing a \emph{forwarding
  9842. pointer} to the new location in the old tuple, back when we initially
  9843. copied the tuple into the ToSpace. This completes one step of the
  9844. algorithm. The algorithm continues in this way until the front of the
  9845. queue is empty, that is, until the front catches up with the back.
  9846. \subsection{Data Representation}
  9847. \label{sec:data-rep-gc}
  9848. The garbage collector places some requirements on the data
  9849. representations used by our compiler. First, the garbage collector
  9850. needs to distinguish between pointers and other kinds of data. There
  9851. are several ways to accomplish this.
  9852. \begin{enumerate}
  9853. \item Attached a tag to each object that identifies what type of
  9854. object it is~\citep{McCarthy:1960dz}.
  9855. \item Store different types of objects in different
  9856. regions~\citep{Steele:1977ab}.
  9857. \item Use type information from the program to either generate
  9858. type-specific code for collecting or to generate tables that can
  9859. guide the
  9860. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  9861. \end{enumerate}
  9862. Dynamically typed languages, such as Lisp, need to tag objects
  9863. anyways, so option 1 is a natural choice for those languages.
  9864. However, \LangVec{} is a statically typed language, so it would be
  9865. unfortunate to require tags on every object, especially small and
  9866. pervasive objects like integers and Booleans. Option 3 is the
  9867. best-performing choice for statically typed languages, but comes with
  9868. a relatively high implementation complexity. To keep this chapter
  9869. within a 2-week time budget, we recommend a combination of options 1
  9870. and 2, using separate strategies for the stack and the heap.
  9871. Regarding the stack, we recommend using a separate stack for pointers,
  9872. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  9873. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  9874. is, when a local variable needs to be spilled and is of type
  9875. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  9876. stack instead of the normal procedure call stack. Furthermore, we
  9877. always spill vector-typed variables if they are live during a call to
  9878. the collector, thereby ensuring that no pointers are in registers
  9879. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  9880. example from Figure~\ref{fig:copying-collector} and contrasts it with
  9881. the data layout using a root stack. The root stack contains the two
  9882. pointers from the regular stack and also the pointer in the second
  9883. register.
  9884. \begin{figure}[tbp]
  9885. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  9886. \caption{Maintaining a root stack to facilitate garbage collection.}
  9887. \label{fig:shadow-stack}
  9888. \end{figure}
  9889. The problem of distinguishing between pointers and other kinds of data
  9890. also arises inside of each tuple on the heap. We solve this problem by
  9891. attaching a tag, an extra 64-bits, to each
  9892. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  9893. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  9894. that we have drawn the bits in a big-endian way, from right-to-left,
  9895. with bit location 0 (the least significant bit) on the far right,
  9896. which corresponds to the direction of the x86 shifting instructions
  9897. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  9898. is dedicated to specifying which elements of the tuple are pointers,
  9899. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  9900. indicates there is a pointer and a 0 bit indicates some other kind of
  9901. data. The pointer mask starts at bit location 7. We have limited
  9902. tuples to a maximum size of 50 elements, so we just need 50 bits for
  9903. the pointer mask. The tag also contains two other pieces of
  9904. information. The length of the tuple (number of elements) is stored in
  9905. bits location 1 through 6. Finally, the bit at location 0 indicates
  9906. whether the tuple has yet to be copied to the ToSpace. If the bit has
  9907. value 1, then this tuple has not yet been copied. If the bit has
  9908. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  9909. of a pointer are always zero anyways because our tuples are 8-byte
  9910. aligned.)
  9911. \begin{figure}[tbp]
  9912. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  9913. \caption{Representation of tuples in the heap.}
  9914. \label{fig:tuple-rep}
  9915. \end{figure}
  9916. \subsection{Implementation of the Garbage Collector}
  9917. \label{sec:organize-gz}
  9918. \index{subject}{prelude}
  9919. An implementation of the copying collector is provided in the
  9920. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  9921. interface to the garbage collector that is used by the compiler. The
  9922. \code{initialize} function creates the FromSpace, ToSpace, and root
  9923. stack and should be called in the prelude of the \code{main}
  9924. function. The arguments of \code{initialize} are the root stack size
  9925. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  9926. good choice for both. The \code{initialize} function puts the address
  9927. of the beginning of the FromSpace into the global variable
  9928. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  9929. the address that is 1-past the last element of the FromSpace. (We use
  9930. half-open intervals to represent chunks of
  9931. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  9932. points to the first element of the root stack.
  9933. As long as there is room left in the FromSpace, your generated code
  9934. can allocate tuples simply by moving the \code{free\_ptr} forward.
  9935. %
  9936. The amount of room left in FromSpace is the difference between the
  9937. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  9938. function should be called when there is not enough room left in the
  9939. FromSpace for the next allocation. The \code{collect} function takes
  9940. a pointer to the current top of the root stack (one past the last item
  9941. that was pushed) and the number of bytes that need to be
  9942. allocated. The \code{collect} function performs the copying collection
  9943. and leaves the heap in a state such that the next allocation will
  9944. succeed.
  9945. \begin{figure}[tbp]
  9946. \begin{lstlisting}
  9947. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  9948. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  9949. int64_t* free_ptr;
  9950. int64_t* fromspace_begin;
  9951. int64_t* fromspace_end;
  9952. int64_t** rootstack_begin;
  9953. \end{lstlisting}
  9954. \caption{The compiler's interface to the garbage collector.}
  9955. \label{fig:gc-header}
  9956. \end{figure}
  9957. %% \begin{exercise}
  9958. %% In the file \code{runtime.c} you will find the implementation of
  9959. %% \code{initialize} and a partial implementation of \code{collect}.
  9960. %% The \code{collect} function calls another function, \code{cheney},
  9961. %% to perform the actual copy, and that function is left to the reader
  9962. %% to implement. The following is the prototype for \code{cheney}.
  9963. %% \begin{lstlisting}
  9964. %% static void cheney(int64_t** rootstack_ptr);
  9965. %% \end{lstlisting}
  9966. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  9967. %% rootstack (which is an array of pointers). The \code{cheney} function
  9968. %% also communicates with \code{collect} through the global
  9969. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  9970. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  9971. %% the ToSpace:
  9972. %% \begin{lstlisting}
  9973. %% static int64_t* tospace_begin;
  9974. %% static int64_t* tospace_end;
  9975. %% \end{lstlisting}
  9976. %% The job of the \code{cheney} function is to copy all the live
  9977. %% objects (reachable from the root stack) into the ToSpace, update
  9978. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  9979. %% update the root stack so that it points to the objects in the
  9980. %% ToSpace, and finally to swap the global pointers for the FromSpace
  9981. %% and ToSpace.
  9982. %% \end{exercise}
  9983. %% \section{Compiler Passes}
  9984. %% \label{sec:code-generation-gc}
  9985. The introduction of garbage collection has a non-trivial impact on our
  9986. compiler passes. We introduce a new compiler pass named
  9987. \code{expose-allocation}. We make
  9988. significant changes to \code{select\_instructions},
  9989. \code{build\_interference}, \code{allocate\_registers}, and
  9990. \code{print\_x86} and make minor changes in several more passes. The
  9991. following program will serve as our running example. It creates two
  9992. tuples, one nested inside the other. Both tuples have length one. The
  9993. program accesses the element in the inner tuple tuple via two vector
  9994. references.
  9995. % tests/s2_17.rkt
  9996. \begin{lstlisting}
  9997. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  9998. \end{lstlisting}
  9999. \section{Shrink}
  10000. \label{sec:shrink-Rvec}
  10001. Recall that the \code{shrink} pass translates the primitives operators
  10002. into a smaller set of primitives. Because this pass comes after type
  10003. checking, but before the passes that require the type information in
  10004. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  10005. to wrap \code{HasType} around each AST node that it generates.
  10006. \section{Expose Allocation}
  10007. \label{sec:expose-allocation}
  10008. The pass \code{expose-allocation} lowers the \code{vector} creation
  10009. form into a conditional call to the collector followed by the
  10010. allocation. We choose to place the \code{expose-allocation} pass
  10011. before \code{remove\_complex\_operands} because the code generated by
  10012. \code{expose-allocation} contains complex operands. We also place
  10013. \code{expose-allocation} before \code{explicate\_control} because
  10014. \code{expose-allocation} introduces new variables using \code{let},
  10015. but \code{let} is gone after \code{explicate\_control}.
  10016. The output of \code{expose-allocation} is a language \LangAlloc{} that
  10017. extends \LangVec{} with the three new forms that we use in the translation
  10018. of the \code{vector} form.
  10019. \[
  10020. \begin{array}{lcl}
  10021. \Exp &::=& \cdots
  10022. \MID (\key{collect} \,\itm{int})
  10023. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10024. \MID (\key{global-value} \,\itm{name})
  10025. \end{array}
  10026. \]
  10027. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  10028. $n$ bytes. It will become a call to the \code{collect} function in
  10029. \code{runtime.c} in \code{select\_instructions}. The
  10030. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  10031. \index{subject}{allocate}
  10032. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  10033. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  10034. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  10035. a global variable, such as \code{free\_ptr}.
  10036. In the following, we show the transformation for the \code{vector}
  10037. form into 1) a sequence of let-bindings for the initializing
  10038. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10039. \code{allocate}, and 4) the initialization of the vector. In the
  10040. following, \itm{len} refers to the length of the vector and
  10041. \itm{bytes} is how many total bytes need to be allocated for the
  10042. vector, which is 8 for the tag plus \itm{len} times 8.
  10043. \begin{lstlisting}
  10044. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10045. |$\Longrightarrow$|
  10046. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10047. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10048. (global-value fromspace_end))
  10049. (void)
  10050. (collect |\itm{bytes}|))])
  10051. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10052. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10053. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10054. |$v$|) ... )))) ...)
  10055. \end{lstlisting}
  10056. In the above, we suppressed all of the \code{has-type} forms in the
  10057. output for the sake of readability. The placement of the initializing
  10058. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  10059. sequence of \code{vector-set!} is important, as those expressions may
  10060. trigger garbage collection and we cannot have an allocated but
  10061. uninitialized tuple on the heap during a collection.
  10062. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10063. \code{expose-allocation} pass on our running example.
  10064. \begin{figure}[tbp]
  10065. % tests/s2_17.rkt
  10066. \begin{lstlisting}
  10067. (vector-ref
  10068. (vector-ref
  10069. (let ([vecinit7976
  10070. (let ([vecinit7972 42])
  10071. (let ([collectret7974
  10072. (if (< (+ (global-value free_ptr) 16)
  10073. (global-value fromspace_end))
  10074. (void)
  10075. (collect 16)
  10076. )])
  10077. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10078. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10079. alloc7971)
  10080. )
  10081. )
  10082. )
  10083. ])
  10084. (let ([collectret7978
  10085. (if (< (+ (global-value free_ptr) 16)
  10086. (global-value fromspace_end))
  10087. (void)
  10088. (collect 16)
  10089. )])
  10090. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10091. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10092. alloc7975)
  10093. )
  10094. )
  10095. )
  10096. 0)
  10097. 0)
  10098. \end{lstlisting}
  10099. \caption{Output of the \code{expose-allocation} pass, minus
  10100. all of the \code{has-type} forms.}
  10101. \label{fig:expose-alloc-output}
  10102. \end{figure}
  10103. \section{Remove Complex Operands}
  10104. \label{sec:remove-complex-opera-Rvec}
  10105. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  10106. should all be treated as complex operands.
  10107. %% A new case for
  10108. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10109. %% handled carefully to prevent the \code{Prim} node from being separated
  10110. %% from its enclosing \code{HasType}.
  10111. Figure~\ref{fig:Rvec-anf-syntax}
  10112. shows the grammar for the output language \LangVecANF{} of this
  10113. pass, which is \LangVec{} in administrative normal form.
  10114. \begin{figure}[tp]
  10115. \centering
  10116. \fbox{
  10117. \begin{minipage}{0.96\textwidth}
  10118. \small
  10119. \[
  10120. \begin{array}{rcl}
  10121. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  10122. \MID \VOID{} \\
  10123. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10124. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10125. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10126. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10127. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10128. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  10129. \MID \LP\key{GlobalValue}~\Var\RP\\
  10130. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10131. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10132. \end{array}
  10133. \]
  10134. \end{minipage}
  10135. }
  10136. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  10137. \label{fig:Rvec-anf-syntax}
  10138. \end{figure}
  10139. \section{Explicate Control and the \LangCVec{} language}
  10140. \label{sec:explicate-control-r3}
  10141. \begin{figure}[tp]
  10142. \fbox{
  10143. \begin{minipage}{0.96\textwidth}
  10144. \small
  10145. \[
  10146. \begin{array}{lcl}
  10147. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  10148. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  10149. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  10150. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  10151. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  10152. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10153. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  10154. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  10155. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  10156. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  10157. \MID \LP\key{Collect} \,\itm{int}\RP \\
  10158. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10159. \MID \GOTO{\itm{label}} } \\
  10160. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10161. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  10162. \end{array}
  10163. \]
  10164. \end{minipage}
  10165. }
  10166. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  10167. (Figure~\ref{fig:c1-syntax}).}
  10168. \label{fig:c2-syntax}
  10169. \end{figure}
  10170. The output of \code{explicate\_control} is a program in the
  10171. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10172. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  10173. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  10174. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  10175. \key{vector-set!}, and \key{global-value} expressions and the
  10176. \code{collect} statement. The \code{explicate\_control} pass can treat
  10177. these new forms much like the other expression forms that we've
  10178. already encoutered.
  10179. \section{Select Instructions and the \LangXGlobal{} Language}
  10180. \label{sec:select-instructions-gc}
  10181. \index{subject}{instruction selection}
  10182. %% void (rep as zero)
  10183. %% allocate
  10184. %% collect (callq collect)
  10185. %% vector-ref
  10186. %% vector-set!
  10187. %% global (postpone)
  10188. In this pass we generate x86 code for most of the new operations that
  10189. were needed to compile tuples, including \code{Allocate},
  10190. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  10191. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  10192. the later has a different concrete syntax (see
  10193. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  10194. \index{subject}{x86}
  10195. The \code{vector-ref} and \code{vector-set!} forms translate into
  10196. \code{movq} instructions. (The plus one in the offset is to get past
  10197. the tag at the beginning of the tuple representation.)
  10198. \begin{lstlisting}
  10199. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  10200. |$\Longrightarrow$|
  10201. movq |$\itm{vec}'$|, %r11
  10202. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10203. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  10204. |$\Longrightarrow$|
  10205. movq |$\itm{vec}'$|, %r11
  10206. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  10207. movq $0, |$\itm{lhs'}$|
  10208. \end{lstlisting}
  10209. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  10210. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  10211. register \code{r11} ensures that offset expression
  10212. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10213. removing \code{r11} from consideration by the register allocating.
  10214. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10215. \code{rax}. Then the generated code for \code{vector-set!} would be
  10216. \begin{lstlisting}
  10217. movq |$\itm{vec}'$|, %rax
  10218. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  10219. movq $0, |$\itm{lhs}'$|
  10220. \end{lstlisting}
  10221. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  10222. \code{patch\_instructions} would insert a move through \code{rax}
  10223. as follows.
  10224. \begin{lstlisting}
  10225. movq |$\itm{vec}'$|, %rax
  10226. movq |$\itm{arg}'$|, %rax
  10227. movq %rax, |$8(n+1)$|(%rax)
  10228. movq $0, |$\itm{lhs}'$|
  10229. \end{lstlisting}
  10230. But the above sequence of instructions does not work because we're
  10231. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  10232. $\itm{arg}'$) at the same time!
  10233. We compile the \code{allocate} form to operations on the
  10234. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10235. is the next free address in the FromSpace, so we copy it into
  10236. \code{r11} and then move it forward by enough space for the tuple
  10237. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10238. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10239. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10240. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10241. tag is organized. We recommend using the Racket operations
  10242. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  10243. during compilation. The type annotation in the \code{vector} form is
  10244. used to determine the pointer mask region of the tag.
  10245. \begin{lstlisting}
  10246. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  10247. |$\Longrightarrow$|
  10248. movq free_ptr(%rip), %r11
  10249. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10250. movq $|$\itm{tag}$|, 0(%r11)
  10251. movq %r11, |$\itm{lhs}'$|
  10252. \end{lstlisting}
  10253. The \code{collect} form is compiled to a call to the \code{collect}
  10254. function in the runtime. The arguments to \code{collect} are 1) the
  10255. top of the root stack and 2) the number of bytes that need to be
  10256. allocated. We use another dedicated register, \code{r15}, to
  10257. store the pointer to the top of the root stack. So \code{r15} is not
  10258. available for use by the register allocator.
  10259. \begin{lstlisting}
  10260. (collect |$\itm{bytes}$|)
  10261. |$\Longrightarrow$|
  10262. movq %r15, %rdi
  10263. movq $|\itm{bytes}|, %rsi
  10264. callq collect
  10265. \end{lstlisting}
  10266. \begin{figure}[tp]
  10267. \fbox{
  10268. \begin{minipage}{0.96\textwidth}
  10269. \[
  10270. \begin{array}{lcl}
  10271. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  10272. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  10273. & & \gray{ \key{main:} \; \Instr\ldots }
  10274. \end{array}
  10275. \]
  10276. \end{minipage}
  10277. }
  10278. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  10279. \label{fig:x86-2-concrete}
  10280. \end{figure}
  10281. \begin{figure}[tp]
  10282. \fbox{
  10283. \begin{minipage}{0.96\textwidth}
  10284. \small
  10285. \[
  10286. \begin{array}{lcl}
  10287. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  10288. \MID \BYTEREG{\Reg}} \\
  10289. &\MID& (\key{Global}~\Var) \\
  10290. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  10291. \end{array}
  10292. \]
  10293. \end{minipage}
  10294. }
  10295. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  10296. \label{fig:x86-2}
  10297. \end{figure}
  10298. The concrete and abstract syntax of the \LangXGlobal{} language is
  10299. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  10300. differs from \LangXIf{} just in the addition of the form for global
  10301. variables.
  10302. %
  10303. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  10304. \code{select\_instructions} pass on the running example.
  10305. \begin{figure}[tbp]
  10306. \centering
  10307. % tests/s2_17.rkt
  10308. \begin{minipage}[t]{0.5\textwidth}
  10309. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10310. block35:
  10311. movq free_ptr(%rip), alloc9024
  10312. addq $16, free_ptr(%rip)
  10313. movq alloc9024, %r11
  10314. movq $131, 0(%r11)
  10315. movq alloc9024, %r11
  10316. movq vecinit9025, 8(%r11)
  10317. movq $0, initret9026
  10318. movq alloc9024, %r11
  10319. movq 8(%r11), tmp9034
  10320. movq tmp9034, %r11
  10321. movq 8(%r11), %rax
  10322. jmp conclusion
  10323. block36:
  10324. movq $0, collectret9027
  10325. jmp block35
  10326. block38:
  10327. movq free_ptr(%rip), alloc9020
  10328. addq $16, free_ptr(%rip)
  10329. movq alloc9020, %r11
  10330. movq $3, 0(%r11)
  10331. movq alloc9020, %r11
  10332. movq vecinit9021, 8(%r11)
  10333. movq $0, initret9022
  10334. movq alloc9020, vecinit9025
  10335. movq free_ptr(%rip), tmp9031
  10336. movq tmp9031, tmp9032
  10337. addq $16, tmp9032
  10338. movq fromspace_end(%rip), tmp9033
  10339. cmpq tmp9033, tmp9032
  10340. jl block36
  10341. jmp block37
  10342. block37:
  10343. movq %r15, %rdi
  10344. movq $16, %rsi
  10345. callq 'collect
  10346. jmp block35
  10347. block39:
  10348. movq $0, collectret9023
  10349. jmp block38
  10350. \end{lstlisting}
  10351. \end{minipage}
  10352. \begin{minipage}[t]{0.45\textwidth}
  10353. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10354. start:
  10355. movq $42, vecinit9021
  10356. movq free_ptr(%rip), tmp9028
  10357. movq tmp9028, tmp9029
  10358. addq $16, tmp9029
  10359. movq fromspace_end(%rip), tmp9030
  10360. cmpq tmp9030, tmp9029
  10361. jl block39
  10362. jmp block40
  10363. block40:
  10364. movq %r15, %rdi
  10365. movq $16, %rsi
  10366. callq 'collect
  10367. jmp block38
  10368. \end{lstlisting}
  10369. \end{minipage}
  10370. \caption{Output of the \code{select\_instructions} pass.}
  10371. \label{fig:select-instr-output-gc}
  10372. \end{figure}
  10373. \clearpage
  10374. \section{Register Allocation}
  10375. \label{sec:reg-alloc-gc}
  10376. \index{subject}{register allocation}
  10377. As discussed earlier in this chapter, the garbage collector needs to
  10378. access all the pointers in the root set, that is, all variables that
  10379. are vectors. It will be the responsibility of the register allocator
  10380. to make sure that:
  10381. \begin{enumerate}
  10382. \item the root stack is used for spilling vector-typed variables, and
  10383. \item if a vector-typed variable is live during a call to the
  10384. collector, it must be spilled to ensure it is visible to the
  10385. collector.
  10386. \end{enumerate}
  10387. The later responsibility can be handled during construction of the
  10388. interference graph, by adding interference edges between the call-live
  10389. vector-typed variables and all the callee-saved registers. (They
  10390. already interfere with the caller-saved registers.) The type
  10391. information for variables is in the \code{Program} form, so we
  10392. recommend adding another parameter to the \code{build\_interference}
  10393. function to communicate this alist.
  10394. The spilling of vector-typed variables to the root stack can be
  10395. handled after graph coloring, when choosing how to assign the colors
  10396. (integers) to registers and stack locations. The \code{Program} output
  10397. of this pass changes to also record the number of spills to the root
  10398. stack.
  10399. % build-interference
  10400. %
  10401. % callq
  10402. % extra parameter for var->type assoc. list
  10403. % update 'program' and 'if'
  10404. % allocate-registers
  10405. % allocate spilled vectors to the rootstack
  10406. % don't change color-graph
  10407. \section{Generate Prelude and Conclusion}
  10408. \label{sec:print-x86-gc}
  10409. \label{sec:prelude-conclusion-x86-gc}
  10410. \index{subject}{prelude}\index{subject}{conclusion}
  10411. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  10412. \code{prelude\_and\_conclusion} pass on the running example. In the
  10413. prelude and conclusion of the \code{main} function, we treat the root
  10414. stack very much like the regular stack in that we move the root stack
  10415. pointer (\code{r15}) to make room for the spills to the root stack,
  10416. except that the root stack grows up instead of down. For the running
  10417. example, there was just one spill so we increment \code{r15} by 8
  10418. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  10419. One issue that deserves special care is that there may be a call to
  10420. \code{collect} prior to the initializing assignments for all the
  10421. variables in the root stack. We do not want the garbage collector to
  10422. accidentally think that some uninitialized variable is a pointer that
  10423. needs to be followed. Thus, we zero-out all locations on the root
  10424. stack in the prelude of \code{main}. In
  10425. Figure~\ref{fig:print-x86-output-gc}, the instruction
  10426. %
  10427. \lstinline{movq $0, (%r15)}
  10428. %
  10429. accomplishes this task. The garbage collector tests each root to see
  10430. if it is null prior to dereferencing it.
  10431. \begin{figure}[htbp]
  10432. \begin{minipage}[t]{0.5\textwidth}
  10433. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10434. block35:
  10435. movq free_ptr(%rip), %rcx
  10436. addq $16, free_ptr(%rip)
  10437. movq %rcx, %r11
  10438. movq $131, 0(%r11)
  10439. movq %rcx, %r11
  10440. movq -8(%r15), %rax
  10441. movq %rax, 8(%r11)
  10442. movq $0, %rdx
  10443. movq %rcx, %r11
  10444. movq 8(%r11), %rcx
  10445. movq %rcx, %r11
  10446. movq 8(%r11), %rax
  10447. jmp conclusion
  10448. block36:
  10449. movq $0, %rcx
  10450. jmp block35
  10451. block38:
  10452. movq free_ptr(%rip), %rcx
  10453. addq $16, free_ptr(%rip)
  10454. movq %rcx, %r11
  10455. movq $3, 0(%r11)
  10456. movq %rcx, %r11
  10457. movq %rbx, 8(%r11)
  10458. movq $0, %rdx
  10459. movq %rcx, -8(%r15)
  10460. movq free_ptr(%rip), %rcx
  10461. addq $16, %rcx
  10462. movq fromspace_end(%rip), %rdx
  10463. cmpq %rdx, %rcx
  10464. jl block36
  10465. movq %r15, %rdi
  10466. movq $16, %rsi
  10467. callq collect
  10468. jmp block35
  10469. block39:
  10470. movq $0, %rcx
  10471. jmp block38
  10472. \end{lstlisting}
  10473. \end{minipage}
  10474. \begin{minipage}[t]{0.45\textwidth}
  10475. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10476. start:
  10477. movq $42, %rbx
  10478. movq free_ptr(%rip), %rdx
  10479. addq $16, %rdx
  10480. movq fromspace_end(%rip), %rcx
  10481. cmpq %rcx, %rdx
  10482. jl block39
  10483. movq %r15, %rdi
  10484. movq $16, %rsi
  10485. callq collect
  10486. jmp block38
  10487. .globl main
  10488. main:
  10489. pushq %rbp
  10490. movq %rsp, %rbp
  10491. pushq %r13
  10492. pushq %r12
  10493. pushq %rbx
  10494. pushq %r14
  10495. subq $0, %rsp
  10496. movq $16384, %rdi
  10497. movq $16384, %rsi
  10498. callq initialize
  10499. movq rootstack_begin(%rip), %r15
  10500. movq $0, (%r15)
  10501. addq $8, %r15
  10502. jmp start
  10503. conclusion:
  10504. subq $8, %r15
  10505. addq $0, %rsp
  10506. popq %r14
  10507. popq %rbx
  10508. popq %r12
  10509. popq %r13
  10510. popq %rbp
  10511. retq
  10512. \end{lstlisting}
  10513. \end{minipage}
  10514. \caption{Output of the \code{print\_x86} pass.}
  10515. \label{fig:print-x86-output-gc}
  10516. \end{figure}
  10517. \begin{figure}[p]
  10518. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10519. \node (Rvec) at (0,2) {\large \LangVec{}};
  10520. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  10521. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  10522. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  10523. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  10524. \node (C2-4) at (3,0) {\large \LangCVec{}};
  10525. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  10526. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  10527. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  10528. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  10529. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  10530. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  10531. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  10532. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  10533. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  10534. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Rvec-4);
  10535. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvec-5);
  10536. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  10537. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  10538. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10539. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10540. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10541. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10542. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  10543. \end{tikzpicture}
  10544. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  10545. \label{fig:Rvec-passes}
  10546. \end{figure}
  10547. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  10548. for the compilation of \LangVec{}.
  10549. \section{Challenge: Simple Structures}
  10550. \label{sec:simple-structures}
  10551. \index{subject}{struct}
  10552. \index{subject}{structure}
  10553. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  10554. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  10555. Recall that a \code{struct} in Typed Racket is a user-defined data
  10556. type that contains named fields and that is heap allocated, similar to
  10557. a vector. The following is an example of a structure definition, in
  10558. this case the definition of a \code{point} type.
  10559. \begin{lstlisting}
  10560. (struct point ([x : Integer] [y : Integer]) #:mutable)
  10561. \end{lstlisting}
  10562. \begin{figure}[tbp]
  10563. \centering
  10564. \fbox{
  10565. \begin{minipage}{0.96\textwidth}
  10566. \[
  10567. \begin{array}{lcl}
  10568. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  10569. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  10570. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  10571. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  10572. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  10573. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  10574. \MID (\key{and}\;\Exp\;\Exp)
  10575. \MID (\key{or}\;\Exp\;\Exp)
  10576. \MID (\key{not}\;\Exp) } \\
  10577. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  10578. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  10579. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  10580. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  10581. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  10582. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  10583. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  10584. \LangStruct{} &::=& \Def \ldots \; \Exp
  10585. \end{array}
  10586. \]
  10587. \end{minipage}
  10588. }
  10589. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  10590. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  10591. \label{fig:r3s-concrete-syntax}
  10592. \end{figure}
  10593. An instance of a structure is created using function call syntax, with
  10594. the name of the structure in the function position:
  10595. \begin{lstlisting}
  10596. (point 7 12)
  10597. \end{lstlisting}
  10598. Function-call syntax is also used to read the value in a field of a
  10599. structure. The function name is formed by the structure name, a dash,
  10600. and the field name. The following example uses \code{point-x} and
  10601. \code{point-y} to access the \code{x} and \code{y} fields of two point
  10602. instances.
  10603. \begin{center}
  10604. \begin{lstlisting}
  10605. (let ([pt1 (point 7 12)])
  10606. (let ([pt2 (point 4 3)])
  10607. (+ (- (point-x pt1) (point-x pt2))
  10608. (- (point-y pt1) (point-y pt2)))))
  10609. \end{lstlisting}
  10610. \end{center}
  10611. Similarly, to write to a field of a structure, use its set function,
  10612. whose name starts with \code{set-}, followed by the structure name,
  10613. then a dash, then the field name, and concluded with an exclamation
  10614. mark. The following example uses \code{set-point-x!} to change the
  10615. \code{x} field from \code{7} to \code{42}.
  10616. \begin{center}
  10617. \begin{lstlisting}
  10618. (let ([pt (point 7 12)])
  10619. (let ([_ (set-point-x! pt 42)])
  10620. (point-x pt)))
  10621. \end{lstlisting}
  10622. \end{center}
  10623. \begin{exercise}\normalfont
  10624. Extend your compiler with support for simple structures, compiling
  10625. \LangStruct{} to x86 assembly code. Create five new test cases that use
  10626. structures and test your compiler.
  10627. \end{exercise}
  10628. \section{Challenge: Arrays}
  10629. \label{sec:arrays}
  10630. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10631. elements whose length is determined at compile-time and where each
  10632. element of a tuple may have a different type (they are
  10633. heterogeous). This challenge is also about sequences, but this time
  10634. the length is determined at run-time and all the elements have the same
  10635. type (they are homogeneous). We use the term ``array'' for this later
  10636. kind of sequence.
  10637. The Racket language does not distinguish between tuples and arrays,
  10638. they are both represented by vectors. However, Typed Racket
  10639. distinguishes between tuples and arrays: the \code{Vector} type is for
  10640. tuples and the \code{Vectorof} type is for arrays.
  10641. %
  10642. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10643. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10644. and the \code{make-vector} primitive operator for creating an array,
  10645. whose arguments are the length of the array and an initial value for
  10646. all the elements in the array. The \code{vector-length},
  10647. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10648. for tuples become overloaded for use with arrays.
  10649. %
  10650. We also include integer multiplication in \LangArray{}, as it is
  10651. useful in many examples involving arrays such as computing the
  10652. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10653. \begin{figure}[tp]
  10654. \centering
  10655. \fbox{
  10656. \begin{minipage}{0.96\textwidth}
  10657. \small
  10658. \[
  10659. \begin{array}{lcl}
  10660. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  10661. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10662. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  10663. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  10664. &\MID& \gray{\key{\#t} \MID \key{\#f}
  10665. \MID \LP\key{and}\;\Exp\;\Exp\RP
  10666. \MID \LP\key{or}\;\Exp\;\Exp\RP
  10667. \MID \LP\key{not}\;\Exp\RP } \\
  10668. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  10669. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  10670. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10671. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  10672. \MID \LP\Exp \; \Exp\ldots\RP } \\
  10673. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10674. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10675. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  10676. \MID \CBEGIN{\Exp\ldots}{\Exp}
  10677. \MID \CWHILE{\Exp}{\Exp} } \\
  10678. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  10679. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10680. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10681. \end{array}
  10682. \]
  10683. \end{minipage}
  10684. }
  10685. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10686. \label{fig:Rvecof-concrete-syntax}
  10687. \end{figure}
  10688. \begin{figure}[tp]
  10689. \begin{lstlisting}
  10690. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10691. [n : Integer]) : Integer
  10692. (let ([i 0])
  10693. (let ([prod 0])
  10694. (begin
  10695. (while (< i n)
  10696. (begin
  10697. (set! prod (+ prod (* (vector-ref A i)
  10698. (vector-ref B i))))
  10699. (set! i (+ i 1))
  10700. ))
  10701. prod))))
  10702. (let ([A (make-vector 2 2)])
  10703. (let ([B (make-vector 2 3)])
  10704. (+ (inner-product A B 2)
  10705. 30)))
  10706. \end{lstlisting}
  10707. \caption{Example program that computes the inner-product.}
  10708. \label{fig:inner-product}
  10709. \end{figure}
  10710. The type checker for \LangArray{} is define in
  10711. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10712. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10713. of the intializing expression. The length expression is required to
  10714. have type \code{Integer}. The type checking of the operators
  10715. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10716. updated to handle the situation where the vector has type
  10717. \code{Vectorof}. In these cases we translate the operators to their
  10718. \code{vectorof} form so that later passes can easily distinguish
  10719. between operations on tuples versus arrays. We override the
  10720. \code{operator-types} method to provide the type signature for
  10721. multiplication: it takes two integers and returns an integer. To
  10722. support injection and projection of arrays to the \code{Any} type
  10723. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10724. predicate.
  10725. \begin{figure}[tbp]
  10726. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10727. (define type-check-Rvecof_class
  10728. (class type-check-Rwhile_class
  10729. (super-new)
  10730. (inherit check-type-equal?)
  10731. (define/override (flat-ty? ty)
  10732. (match ty
  10733. ['(Vectorof Any) #t]
  10734. [else (super flat-ty? ty)]))
  10735. (define/override (operator-types)
  10736. (append '((* . ((Integer Integer) . Integer)))
  10737. (super operator-types)))
  10738. (define/override (type-check-exp env)
  10739. (lambda (e)
  10740. (define recur (type-check-exp env))
  10741. (match e
  10742. [(Prim 'make-vector (list e1 e2))
  10743. (define-values (e1^ t1) (recur e1))
  10744. (define-values (e2^ elt-type) (recur e2))
  10745. (define vec-type `(Vectorof ,elt-type))
  10746. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10747. vec-type)]
  10748. [(Prim 'vector-ref (list e1 e2))
  10749. (define-values (e1^ t1) (recur e1))
  10750. (define-values (e2^ t2) (recur e2))
  10751. (match* (t1 t2)
  10752. [(`(Vectorof ,elt-type) 'Integer)
  10753. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10754. [(other wise) ((super type-check-exp env) e)])]
  10755. [(Prim 'vector-set! (list e1 e2 e3) )
  10756. (define-values (e-vec t-vec) (recur e1))
  10757. (define-values (e2^ t2) (recur e2))
  10758. (define-values (e-arg^ t-arg) (recur e3))
  10759. (match t-vec
  10760. [`(Vectorof ,elt-type)
  10761. (check-type-equal? elt-type t-arg e)
  10762. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10763. [else ((super type-check-exp env) e)])]
  10764. [(Prim 'vector-length (list e1))
  10765. (define-values (e1^ t1) (recur e1))
  10766. (match t1
  10767. [`(Vectorof ,t)
  10768. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10769. [else ((super type-check-exp env) e)])]
  10770. [else ((super type-check-exp env) e)])))
  10771. ))
  10772. (define (type-check-Rvecof p)
  10773. (send (new type-check-Rvecof_class) type-check-program p))
  10774. \end{lstlisting}
  10775. \caption{Type checker for the \LangArray{} language.}
  10776. \label{fig:type-check-Rvecof}
  10777. \end{figure}
  10778. The interpreter for \LangArray{} is defined in
  10779. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10780. implemented with Racket's \code{make-vector} function and
  10781. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10782. integers.
  10783. \begin{figure}[tbp]
  10784. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10785. (define interp-Rvecof_class
  10786. (class interp-Rwhile_class
  10787. (super-new)
  10788. (define/override (interp-op op)
  10789. (verbose "Rvecof/interp-op" op)
  10790. (match op
  10791. ['make-vector make-vector]
  10792. ['* fx*]
  10793. [else (super interp-op op)]))
  10794. ))
  10795. (define (interp-Rvecof p)
  10796. (send (new interp-Rvecof_class) interp-program p))
  10797. \end{lstlisting}
  10798. \caption{Interpreter for \LangArray{}.}
  10799. \label{fig:interp-Rvecof}
  10800. \end{figure}
  10801. \subsection{Data Representation}
  10802. \label{sec:array-rep}
  10803. Just like tuples, we store arrays on the heap which means that the
  10804. garbage collector will need to inspect arrays. An immediate thought is
  10805. to use the same representation for arrays that we use for tuples.
  10806. However, we limit tuples to a length of $50$ so that their length and
  10807. pointer mask can fit into the 64-bit tag at the beginning of each
  10808. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10809. millions of elements, so we need more bits to store the length.
  10810. However, because arrays are homogeneous, we only need $1$ bit for the
  10811. pointer mask instead of one bit per array elements. Finally, the
  10812. garbage collector will need to be able to distinguish between tuples
  10813. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10814. arrive at the following layout for the 64-bit tag at the beginning of
  10815. an array:
  10816. \begin{itemize}
  10817. \item The right-most bit is the forwarding bit, just like in a tuple.
  10818. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10819. it is not.
  10820. \item The next bit to the left is the pointer mask. A $0$ indicates
  10821. that none of the elements are pointers to the heap and a $1$
  10822. indicates that all of the elements are pointers.
  10823. \item The next $61$ bits store the length of the array.
  10824. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10825. array ($1$).
  10826. \end{itemize}
  10827. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10828. differentiate the kinds of values that have been injected into the
  10829. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10830. to indicate that the value is an array.
  10831. In the following subsections we provide hints regarding how to update
  10832. the passes to handle arrays.
  10833. \subsection{Reveal Casts}
  10834. The array-access operators \code{vectorof-ref} and
  10835. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10836. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10837. that the type checker cannot tell whether the index will be in bounds,
  10838. so the bounds check must be performed at run time. Recall that the
  10839. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10840. an \code{If} arround a vector reference for update to check whether
  10841. the index is less than the length. You should do the same for
  10842. \code{vectorof-ref} and \code{vectorof-set!} .
  10843. In addition, the handling of the \code{any-vector} operators in
  10844. \code{reveal-casts} needs to be updated to account for arrays that are
  10845. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10846. generated code should test whether the tag is for tuples (\code{010})
  10847. or arrays (\code{110}) and then dispatch to either
  10848. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10849. we add a case in \code{select\_instructions} to generate the
  10850. appropriate instructions for accessing the array length from the
  10851. header of an array.
  10852. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10853. the generated code needs to check that the index is less than the
  10854. vector length, so like the code for \code{any-vector-length}, check
  10855. the tag to determine whether to use \code{any-vector-length} or
  10856. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10857. is complete, the generated code can use \code{any-vector-ref} and
  10858. \code{any-vector-set!} for both tuples and arrays because the
  10859. instructions used for those operators do not look at the tag at the
  10860. front of the tuple or array.
  10861. \subsection{Expose Allocation}
  10862. This pass should translate the \code{make-vector} operator into
  10863. lower-level operations. In particular, the new AST node
  10864. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10865. length specified by the $\Exp$, but does not initialize the elements
  10866. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10867. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10868. element type for the array. Regarding the initialization of the array,
  10869. we recommend generated a \code{while} loop that uses
  10870. \code{vector-set!} to put the initializing value into every element of
  10871. the array.
  10872. \subsection{Remove Complex Operands}
  10873. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  10874. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10875. complex and its subexpression must be atomic.
  10876. \subsection{Explicate Control}
  10877. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  10878. \code{explicate\_assign}.
  10879. \subsection{Select Instructions}
  10880. Generate instructions for \code{AllocateArray} similar to those for
  10881. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10882. that the tag at the front of the array should instead use the
  10883. representation discussed in Section~\ref{sec:array-rep}.
  10884. Regarding \code{vectorof-length}, extract the length from the tag
  10885. according to the representation discussed in
  10886. Section~\ref{sec:array-rep}.
  10887. The instructions generated for \code{vectorof-ref} differ from those
  10888. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10889. that the index is not a constant so the offset must be computed at
  10890. runtime, similar to the instructions generated for
  10891. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10892. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10893. appear in an assignment and as a stand-alone statement, so make sure
  10894. to handle both situations in this pass.
  10895. Finally, the instructions for \code{any-vectorof-length} should be
  10896. similar to those for \code{vectorof-length}, except that one must
  10897. first project the array by writing zeroes into the $3$-bit tag
  10898. \begin{exercise}\normalfont
  10899. Implement a compiler for the \LangArray{} language by extending your
  10900. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10901. programs, including the one in Figure~\ref{fig:inner-product} and also
  10902. a program that multiplies two matrices. Note that matrices are
  10903. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10904. arrays by laying out each row in the array, one after the next.
  10905. \end{exercise}
  10906. \section{Challenge: Generational Collection}
  10907. The copying collector described in Section~\ref{sec:GC} can incur
  10908. significant runtime overhead because the call to \code{collect} takes
  10909. time proportional to all of the live data. One way to reduce this
  10910. overhead is to reduce how much data is inspected in each call to
  10911. \code{collect}. In particular, researchers have observed that recently
  10912. allocated data is more likely to become garbage then data that has
  10913. survived one or more previous calls to \code{collect}. This insight
  10914. motivated the creation of \emph{generational garbage collectors}
  10915. \index{subject}{generational garbage collector} that
  10916. 1) segregates data according to its age into two or more generations,
  10917. 2) allocates less space for younger generations, so collecting them is
  10918. faster, and more space for the older generations, and 3) performs
  10919. collection on the younger generations more frequently then for older
  10920. generations~\citep{Wilson:1992fk}.
  10921. For this challenge assignment, the goal is to adapt the copying
  10922. collector implemented in \code{runtime.c} to use two generations, one
  10923. for young data and one for old data. Each generation consists of a
  10924. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  10925. \code{collect} function to use the two generations.
  10926. \begin{enumerate}
  10927. \item Copy the young generation's FromSpace to its ToSpace then switch
  10928. the role of the ToSpace and FromSpace
  10929. \item If there is enough space for the requested number of bytes in
  10930. the young FromSpace, then return from \code{collect}.
  10931. \item If there is not enough space in the young FromSpace for the
  10932. requested bytes, then move the data from the young generation to the
  10933. old one with the following steps:
  10934. \begin{enumerate}
  10935. \item If there is enough room in the old FromSpace, copy the young
  10936. FromSpace to the old FromSpace and then return.
  10937. \item If there is not enough room in the old FromSpace, then collect
  10938. the old generation by copying the old FromSpace to the old ToSpace
  10939. and swap the roles of the old FromSpace and ToSpace.
  10940. \item If there is enough room now, copy the young FromSpace to the
  10941. old FromSpace and return. Otherwise, allocate a larger FromSpace
  10942. and ToSpace for the old generation. Copy the young FromSpace and
  10943. the old FromSpace into the larger FromSpace for the old
  10944. generation and then return.
  10945. \end{enumerate}
  10946. \end{enumerate}
  10947. We recommend that you generalize the \code{cheney} function so that it
  10948. can be used for all the copies mentioned above: between the young
  10949. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  10950. between the young FromSpace and old FromSpace. This can be
  10951. accomplished by adding parameters to \code{cheney} that replace its
  10952. use of the global variables \code{fromspace\_begin},
  10953. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  10954. Note that the collection of the young generation does not traverse the
  10955. old generation. This introduces a potential problem: there may be
  10956. young data that is only reachable through pointers in the old
  10957. generation. If these pointers are not taken into account, the
  10958. collector could throw away young data that is live! One solution,
  10959. called \emph{pointer recording}, is to maintain a set of all the
  10960. pointers from the old generation into the new generation and consider
  10961. this set as part of the root set. To maintain this set, the compiler
  10962. must insert extra instructions around every \code{vector-set!}. If the
  10963. vector being modified is in the old generation, and if the value being
  10964. written is a pointer into the new generation, than that pointer must
  10965. be added to the set. Also, if the value being overwritten was a
  10966. pointer into the new generation, then that pointer should be removed
  10967. from the set.
  10968. \begin{exercise}\normalfont
  10969. Adapt the \code{collect} function in \code{runtime.c} to implement
  10970. generational garbage collection, as outlined in this section.
  10971. Update the code generation for \code{vector-set!} to implement
  10972. pointer recording. Make sure that your new compiler and runtime
  10973. passes your test suite.
  10974. \end{exercise}
  10975. % Further Reading
  10976. \fi % racketEd
  10977. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10978. \chapter{Functions}
  10979. \label{ch:Rfun}
  10980. \index{subject}{function}
  10981. \if\edition\racketEd
  10982. This chapter studies the compilation of functions similar to those
  10983. found in the C language. This corresponds to a subset of Typed Racket
  10984. in which only top-level function definitions are allowed. This kind of
  10985. function is an important stepping stone to implementing
  10986. lexically-scoped functions, that is, \key{lambda} abstractions, which
  10987. is the topic of Chapter~\ref{ch:Rlam}.
  10988. \section{The \LangFun{} Language}
  10989. The concrete and abstract syntax for function definitions and function
  10990. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  10991. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  10992. \LangFun{} begin with zero or more function definitions. The function
  10993. names from these definitions are in-scope for the entire program,
  10994. including all other function definitions (so the ordering of function
  10995. definitions does not matter). The concrete syntax for function
  10996. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  10997. where the first expression must
  10998. evaluate to a function and the rest are the arguments.
  10999. The abstract syntax for function application is
  11000. $\APPLY{\Exp}{\Exp\ldots}$.
  11001. %% The syntax for function application does not include an explicit
  11002. %% keyword, which is error prone when using \code{match}. To alleviate
  11003. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11004. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11005. Functions are first-class in the sense that a function pointer
  11006. \index{subject}{function pointer} is data and can be stored in memory or passed
  11007. as a parameter to another function. Thus, we introduce a function
  11008. type, written
  11009. \begin{lstlisting}
  11010. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11011. \end{lstlisting}
  11012. for a function whose $n$ parameters have the types $\Type_1$ through
  11013. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  11014. these functions (with respect to Racket functions) is that they are
  11015. not lexically scoped. That is, the only external entities that can be
  11016. referenced from inside a function body are other globally-defined
  11017. functions. The syntax of \LangFun{} prevents functions from being nested
  11018. inside each other.
  11019. \begin{figure}[tp]
  11020. \centering
  11021. \fbox{
  11022. \begin{minipage}{0.96\textwidth}
  11023. \small
  11024. \[
  11025. \begin{array}{lcl}
  11026. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  11027. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  11028. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11029. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11030. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11031. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11032. \MID (\key{and}\;\Exp\;\Exp)
  11033. \MID (\key{or}\;\Exp\;\Exp)
  11034. \MID (\key{not}\;\Exp)} \\
  11035. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11036. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  11037. (\key{vector-ref}\;\Exp\;\Int)} \\
  11038. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11039. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  11040. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  11041. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11042. \LangFunM{} &::=& \Def \ldots \; \Exp
  11043. \end{array}
  11044. \]
  11045. \end{minipage}
  11046. }
  11047. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  11048. \label{fig:Rfun-concrete-syntax}
  11049. \end{figure}
  11050. \begin{figure}[tp]
  11051. \centering
  11052. \fbox{
  11053. \begin{minipage}{0.96\textwidth}
  11054. \small
  11055. \[
  11056. \begin{array}{lcl}
  11057. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11058. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11059. &\MID& \gray{ \BOOL{\itm{bool}}
  11060. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11061. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  11062. \MID \APPLY{\Exp}{\Exp\ldots}\\
  11063. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  11064. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11065. \end{array}
  11066. \]
  11067. \end{minipage}
  11068. }
  11069. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  11070. \label{fig:Rfun-syntax}
  11071. \end{figure}
  11072. The program in Figure~\ref{fig:Rfun-function-example} is a
  11073. representative example of defining and using functions in \LangFun{}. We
  11074. define a function \code{map-vec} that applies some other function
  11075. \code{f} to both elements of a vector and returns a new
  11076. vector containing the results. We also define a function \code{add1}.
  11077. The program applies
  11078. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  11079. \code{(vector 1 42)}, from which we return the \code{42}.
  11080. \begin{figure}[tbp]
  11081. \begin{lstlisting}
  11082. (define (map-vec [f : (Integer -> Integer)]
  11083. [v : (Vector Integer Integer)])
  11084. : (Vector Integer Integer)
  11085. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11086. (define (add1 [x : Integer]) : Integer
  11087. (+ x 1))
  11088. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11089. \end{lstlisting}
  11090. \caption{Example of using functions in \LangFun{}.}
  11091. \label{fig:Rfun-function-example}
  11092. \end{figure}
  11093. The definitional interpreter for \LangFun{} is in
  11094. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  11095. responsible for setting up the mutual recursion between the top-level
  11096. function definitions. We use the classic back-patching \index{subject}{back-patching}
  11097. approach that uses mutable variables and makes two passes over the function
  11098. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  11099. top-level environment using a mutable cons cell for each function
  11100. definition. Note that the \code{lambda} value for each function is
  11101. incomplete; it does not yet include the environment. Once the
  11102. top-level environment is constructed, we then iterate over it and
  11103. update the \code{lambda} values to use the top-level environment.
  11104. \begin{figure}[tp]
  11105. \begin{lstlisting}
  11106. (define interp-Rfun_class
  11107. (class interp-Rvec_class
  11108. (super-new)
  11109. (define/override ((interp-exp env) e)
  11110. (define recur (interp-exp env))
  11111. (match e
  11112. [(Var x) (unbox (dict-ref env x))]
  11113. [(Let x e body)
  11114. (define new-env (dict-set env x (box (recur e))))
  11115. ((interp-exp new-env) body)]
  11116. [(Apply fun args)
  11117. (define fun-val (recur fun))
  11118. (define arg-vals (for/list ([e args]) (recur e)))
  11119. (match fun-val
  11120. [`(function (,xs ...) ,body ,fun-env)
  11121. (define params-args (for/list ([x xs] [arg arg-vals])
  11122. (cons x (box arg))))
  11123. (define new-env (append params-args fun-env))
  11124. ((interp-exp new-env) body)]
  11125. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  11126. [else ((super interp-exp env) e)]
  11127. ))
  11128. (define/public (interp-def d)
  11129. (match d
  11130. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  11131. (cons f (box `(function ,xs ,body ())))]))
  11132. (define/override (interp-program p)
  11133. (match p
  11134. [(ProgramDefsExp info ds body)
  11135. (let ([top-level (for/list ([d ds]) (interp-def d))])
  11136. (for/list ([f (in-dict-values top-level)])
  11137. (set-box! f (match (unbox f)
  11138. [`(function ,xs ,body ())
  11139. `(function ,xs ,body ,top-level)])))
  11140. ((interp-exp top-level) body))]))
  11141. ))
  11142. (define (interp-Rfun p)
  11143. (send (new interp-Rfun_class) interp-program p))
  11144. \end{lstlisting}
  11145. \caption{Interpreter for the \LangFun{} language.}
  11146. \label{fig:interp-Rfun}
  11147. \end{figure}
  11148. %\margincomment{TODO: explain type checker}
  11149. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  11150. \begin{figure}[tp]
  11151. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11152. (define type-check-Rfun_class
  11153. (class type-check-Rvec_class
  11154. (super-new)
  11155. (inherit check-type-equal?)
  11156. (define/public (type-check-apply env e es)
  11157. (define-values (e^ ty) ((type-check-exp env) e))
  11158. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  11159. ((type-check-exp env) e)))
  11160. (match ty
  11161. [`(,ty^* ... -> ,rt)
  11162. (for ([arg-ty ty*] [param-ty ty^*])
  11163. (check-type-equal? arg-ty param-ty (Apply e es)))
  11164. (values e^ e* rt)]))
  11165. (define/override (type-check-exp env)
  11166. (lambda (e)
  11167. (match e
  11168. [(FunRef f)
  11169. (values (FunRef f) (dict-ref env f))]
  11170. [(Apply e es)
  11171. (define-values (e^ es^ rt) (type-check-apply env e es))
  11172. (values (Apply e^ es^) rt)]
  11173. [(Call e es)
  11174. (define-values (e^ es^ rt) (type-check-apply env e es))
  11175. (values (Call e^ es^) rt)]
  11176. [else ((super type-check-exp env) e)])))
  11177. (define/public (type-check-def env)
  11178. (lambda (e)
  11179. (match e
  11180. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  11181. (define new-env (append (map cons xs ps) env))
  11182. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11183. (check-type-equal? ty^ rt body)
  11184. (Def f p:t* rt info body^)])))
  11185. (define/public (fun-def-type d)
  11186. (match d
  11187. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  11188. (define/override (type-check-program e)
  11189. (match e
  11190. [(ProgramDefsExp info ds body)
  11191. (define new-env (for/list ([d ds])
  11192. (cons (Def-name d) (fun-def-type d))))
  11193. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  11194. (define-values (body^ ty) ((type-check-exp new-env) body))
  11195. (check-type-equal? ty 'Integer body)
  11196. (ProgramDefsExp info ds^ body^)]))))
  11197. (define (type-check-Rfun p)
  11198. (send (new type-check-Rfun_class) type-check-program p))
  11199. \end{lstlisting}
  11200. \caption{Type checker for the \LangFun{} language.}
  11201. \label{fig:type-check-Rfun}
  11202. \end{figure}
  11203. \section{Functions in x86}
  11204. \label{sec:fun-x86}
  11205. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  11206. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  11207. %% \margincomment{\tiny Talk about the return address on the
  11208. %% stack and what callq and retq does.\\ --Jeremy }
  11209. The x86 architecture provides a few features to support the
  11210. implementation of functions. We have already seen that x86 provides
  11211. labels so that one can refer to the location of an instruction, as is
  11212. needed for jump instructions. Labels can also be used to mark the
  11213. beginning of the instructions for a function. Going further, we can
  11214. obtain the address of a label by using the \key{leaq} instruction and
  11215. PC-relative addressing. For example, the following puts the
  11216. address of the \code{add1} label into the \code{rbx} register.
  11217. \begin{lstlisting}
  11218. leaq add1(%rip), %rbx
  11219. \end{lstlisting}
  11220. The instruction pointer register \key{rip} (aka. the program counter
  11221. \index{subject}{program counter}) always points to the next instruction to be
  11222. executed. When combined with an label, as in \code{add1(\%rip)}, the
  11223. linker computes the distance $d$ between the address of \code{add1}
  11224. and where the \code{rip} would be at that moment and then changes
  11225. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  11226. the address of \code{add1}.
  11227. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  11228. jump to a function whose location is given by a label. To support
  11229. function calls in this chapter we instead will be jumping to a
  11230. function whose location is given by an address in a register, that is,
  11231. we need to make an \emph{indirect function call}. The x86 syntax for
  11232. this is a \code{callq} instruction but with an asterisk before the
  11233. register name.\index{subject}{indirect function call}
  11234. \begin{lstlisting}
  11235. callq *%rbx
  11236. \end{lstlisting}
  11237. \subsection{Calling Conventions}
  11238. \index{subject}{calling conventions}
  11239. The \code{callq} instruction provides partial support for implementing
  11240. functions: it pushes the return address on the stack and it jumps to
  11241. the target. However, \code{callq} does not handle
  11242. \begin{enumerate}
  11243. \item parameter passing,
  11244. \item pushing frames on the procedure call stack and popping them off,
  11245. or
  11246. \item determining how registers are shared by different functions.
  11247. \end{enumerate}
  11248. Regarding (1) parameter passing, recall that the following six
  11249. registers are used to pass arguments to a function, in this order.
  11250. \begin{lstlisting}
  11251. rdi rsi rdx rcx r8 r9
  11252. \end{lstlisting}
  11253. If there are
  11254. more than six arguments, then the convention is to use space on the
  11255. frame of the caller for the rest of the arguments. However, to ease
  11256. the implementation of efficient tail calls
  11257. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  11258. arguments.
  11259. %
  11260. Also recall that the register \code{rax} is for the return value of
  11261. the function.
  11262. \index{subject}{prelude}\index{subject}{conclusion}
  11263. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  11264. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  11265. the stack grows down, with each function call using a chunk of space
  11266. called a frame. The caller sets the stack pointer, register
  11267. \code{rsp}, to the last data item in its frame. The callee must not
  11268. change anything in the caller's frame, that is, anything that is at or
  11269. above the stack pointer. The callee is free to use locations that are
  11270. below the stack pointer.
  11271. Recall that we are storing variables of vector type on the root stack.
  11272. So the prelude needs to move the root stack pointer \code{r15} up and
  11273. the conclusion needs to move the root stack pointer back down. Also,
  11274. the prelude must initialize to \code{0} this frame's slots in the root
  11275. stack to signal to the garbage collector that those slots do not yet
  11276. contain a pointer to a vector. Otherwise the garbage collector will
  11277. interpret the garbage bits in those slots as memory addresses and try
  11278. to traverse them, causing serious mayhem!
  11279. Regarding (3) the sharing of registers between different functions,
  11280. recall from Section~\ref{sec:calling-conventions} that the registers
  11281. are divided into two groups, the caller-saved registers and the
  11282. callee-saved registers. The caller should assume that all the
  11283. caller-saved registers get overwritten with arbitrary values by the
  11284. callee. That is why we recommend in
  11285. Section~\ref{sec:calling-conventions} that variables that are live
  11286. during a function call should not be assigned to caller-saved
  11287. registers.
  11288. On the flip side, if the callee wants to use a callee-saved register,
  11289. the callee must save the contents of those registers on their stack
  11290. frame and then put them back prior to returning to the caller. That
  11291. is why we recommended in Section~\ref{sec:calling-conventions} that if
  11292. the register allocator assigns a variable to a callee-saved register,
  11293. then the prelude of the \code{main} function must save that register
  11294. to the stack and the conclusion of \code{main} must restore it. This
  11295. recommendation now generalizes to all functions.
  11296. Also recall that the base pointer, register \code{rbp}, is used as a
  11297. point-of-reference within a frame, so that each local variable can be
  11298. accessed at a fixed offset from the base pointer
  11299. (Section~\ref{sec:x86}).
  11300. %
  11301. Figure~\ref{fig:call-frames} shows the general layout of the caller
  11302. and callee frames.
  11303. \begin{figure}[tbp]
  11304. \centering
  11305. \begin{tabular}{r|r|l|l} \hline
  11306. Caller View & Callee View & Contents & Frame \\ \hline
  11307. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  11308. 0(\key{\%rbp}) & & old \key{rbp} \\
  11309. -8(\key{\%rbp}) & & callee-saved $1$ \\
  11310. \ldots & & \ldots \\
  11311. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  11312. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  11313. \ldots & & \ldots \\
  11314. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  11315. %% & & \\
  11316. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  11317. %% & \ldots & \ldots \\
  11318. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  11319. \hline
  11320. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  11321. & 0(\key{\%rbp}) & old \key{rbp} \\
  11322. & -8(\key{\%rbp}) & callee-saved $1$ \\
  11323. & \ldots & \ldots \\
  11324. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  11325. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  11326. & \ldots & \ldots \\
  11327. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  11328. \end{tabular}
  11329. \caption{Memory layout of caller and callee frames.}
  11330. \label{fig:call-frames}
  11331. \end{figure}
  11332. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  11333. %% local variables and for storing the values of callee-saved registers
  11334. %% (we shall refer to all of these collectively as ``locals''), and that
  11335. %% at the beginning of a function we move the stack pointer \code{rsp}
  11336. %% down to make room for them.
  11337. %% We recommend storing the local variables
  11338. %% first and then the callee-saved registers, so that the local variables
  11339. %% can be accessed using \code{rbp} the same as before the addition of
  11340. %% functions.
  11341. %% To make additional room for passing arguments, we shall
  11342. %% move the stack pointer even further down. We count how many stack
  11343. %% arguments are needed for each function call that occurs inside the
  11344. %% body of the function and find their maximum. Adding this number to the
  11345. %% number of locals gives us how much the \code{rsp} should be moved at
  11346. %% the beginning of the function. In preparation for a function call, we
  11347. %% offset from \code{rsp} to set up the stack arguments. We put the first
  11348. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  11349. %% so on.
  11350. %% Upon calling the function, the stack arguments are retrieved by the
  11351. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  11352. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  11353. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  11354. %% the layout of the caller and callee frames. Notice how important it is
  11355. %% that we correctly compute the maximum number of arguments needed for
  11356. %% function calls; if that number is too small then the arguments and
  11357. %% local variables will smash into each other!
  11358. \subsection{Efficient Tail Calls}
  11359. \label{sec:tail-call}
  11360. In general, the amount of stack space used by a program is determined
  11361. by the longest chain of nested function calls. That is, if function
  11362. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  11363. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  11364. $n$ can grow quite large in the case of recursive or mutually
  11365. recursive functions. However, in some cases we can arrange to use only
  11366. constant space, i.e. $O(1)$, instead of $O(n)$.
  11367. If a function call is the last action in a function body, then that
  11368. call is said to be a \emph{tail call}\index{subject}{tail call}.
  11369. For example, in the following
  11370. program, the recursive call to \code{tail-sum} is a tail call.
  11371. \begin{center}
  11372. \begin{lstlisting}
  11373. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  11374. (if (eq? n 0)
  11375. r
  11376. (tail-sum (- n 1) (+ n r))))
  11377. (+ (tail-sum 5 0) 27)
  11378. \end{lstlisting}
  11379. \end{center}
  11380. At a tail call, the frame of the caller is no longer needed, so we
  11381. can pop the caller's frame before making the tail call. With this
  11382. approach, a recursive function that only makes tail calls will only
  11383. use $O(1)$ stack space. Functional languages like Racket typically
  11384. rely heavily on recursive functions, so they typically guarantee that
  11385. all tail calls will be optimized in this way.
  11386. \index{subject}{frame}
  11387. However, some care is needed with regards to argument passing in tail
  11388. calls. As mentioned above, for arguments beyond the sixth, the
  11389. convention is to use space in the caller's frame for passing
  11390. arguments. But for a tail call we pop the caller's frame and can no
  11391. longer use it. Another alternative is to use space in the callee's
  11392. frame for passing arguments. However, this option is also problematic
  11393. because the caller and callee's frame overlap in memory. As we begin
  11394. to copy the arguments from their sources in the caller's frame, the
  11395. target locations in the callee's frame might overlap with the sources
  11396. for later arguments! We solve this problem by using the heap instead
  11397. of the stack for passing more than six arguments, as we describe in
  11398. the Section~\ref{sec:limit-functions-r4}.
  11399. As mentioned above, for a tail call we pop the caller's frame prior to
  11400. making the tail call. The instructions for popping a frame are the
  11401. instructions that we usually place in the conclusion of a
  11402. function. Thus, we also need to place such code immediately before
  11403. each tail call. These instructions include restoring the callee-saved
  11404. registers, so it is good that the argument passing registers are all
  11405. caller-saved registers.
  11406. One last note regarding which instruction to use to make the tail
  11407. call. When the callee is finished, it should not return to the current
  11408. function, but it should return to the function that called the current
  11409. one. Thus, the return address that is already on the stack is the
  11410. right one, and we should not use \key{callq} to make the tail call, as
  11411. that would unnecessarily overwrite the return address. Instead we can
  11412. simply use the \key{jmp} instruction. Like the indirect function call,
  11413. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  11414. prefixed with an asterisk. We recommend using \code{rax} to hold the
  11415. jump target because the preceding conclusion overwrites just about
  11416. everything else.
  11417. \begin{lstlisting}
  11418. jmp *%rax
  11419. \end{lstlisting}
  11420. \section{Shrink \LangFun{}}
  11421. \label{sec:shrink-r4}
  11422. The \code{shrink} pass performs a minor modification to ease the
  11423. later passes. This pass introduces an explicit \code{main} function
  11424. and changes the top \code{ProgramDefsExp} form to
  11425. \code{ProgramDefs} as follows.
  11426. \begin{lstlisting}
  11427. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  11428. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  11429. \end{lstlisting}
  11430. where $\itm{mainDef}$ is
  11431. \begin{lstlisting}
  11432. (Def 'main '() 'Integer '() |$\Exp'$|)
  11433. \end{lstlisting}
  11434. \section{Reveal Functions and the \LangFunRef{} language}
  11435. \label{sec:reveal-functions-r4}
  11436. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  11437. respect: it conflates the use of function names and local
  11438. variables. This is a problem because we need to compile the use of a
  11439. function name differently than the use of a local variable; we need to
  11440. use \code{leaq} to convert the function name (a label in x86) to an
  11441. address in a register. Thus, it is a good idea to create a new pass
  11442. that changes function references from just a symbol $f$ to
  11443. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  11444. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  11445. The concrete syntax for a function reference is $\CFUNREF{f}$.
  11446. \begin{figure}[tp]
  11447. \centering
  11448. \fbox{
  11449. \begin{minipage}{0.96\textwidth}
  11450. \[
  11451. \begin{array}{lcl}
  11452. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  11453. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11454. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  11455. \end{array}
  11456. \]
  11457. \end{minipage}
  11458. }
  11459. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  11460. (Figure~\ref{fig:Rfun-syntax}).}
  11461. \label{fig:f1-syntax}
  11462. \end{figure}
  11463. %% Distinguishing between calls in tail position and non-tail position
  11464. %% requires the pass to have some notion of context. We recommend using
  11465. %% two mutually recursive functions, one for processing expressions in
  11466. %% tail position and another for the rest.
  11467. Placing this pass after \code{uniquify} will make sure that there are
  11468. no local variables and functions that share the same name. On the
  11469. other hand, \code{reveal-functions} needs to come before the
  11470. \code{explicate\_control} pass because that pass helps us compile
  11471. \code{FunRef} forms into assignment statements.
  11472. \section{Limit Functions}
  11473. \label{sec:limit-functions-r4}
  11474. Recall that we wish to limit the number of function parameters to six
  11475. so that we do not need to use the stack for argument passing, which
  11476. makes it easier to implement efficient tail calls. However, because
  11477. the input language \LangFun{} supports arbitrary numbers of function
  11478. arguments, we have some work to do!
  11479. This pass transforms functions and function calls that involve more
  11480. than six arguments to pass the first five arguments as usual, but it
  11481. packs the rest of the arguments into a vector and passes it as the
  11482. sixth argument.
  11483. Each function definition with too many parameters is transformed as
  11484. follows.
  11485. \begin{lstlisting}
  11486. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  11487. |$\Rightarrow$|
  11488. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  11489. \end{lstlisting}
  11490. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  11491. the occurrences of the later parameters with vector references.
  11492. \begin{lstlisting}
  11493. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  11494. \end{lstlisting}
  11495. For function calls with too many arguments, the \code{limit-functions}
  11496. pass transforms them in the following way.
  11497. \begin{tabular}{lll}
  11498. \begin{minipage}{0.2\textwidth}
  11499. \begin{lstlisting}
  11500. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  11501. \end{lstlisting}
  11502. \end{minipage}
  11503. &
  11504. $\Rightarrow$
  11505. &
  11506. \begin{minipage}{0.4\textwidth}
  11507. \begin{lstlisting}
  11508. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  11509. \end{lstlisting}
  11510. \end{minipage}
  11511. \end{tabular}
  11512. \section{Remove Complex Operands}
  11513. \label{sec:rco-r4}
  11514. The primary decisions to make for this pass is whether to classify
  11515. \code{FunRef} and \code{Apply} as either atomic or complex
  11516. expressions. Recall that a simple expression will eventually end up as
  11517. just an immediate argument of an x86 instruction. Function
  11518. application will be translated to a sequence of instructions, so
  11519. \code{Apply} must be classified as complex expression.
  11520. On the other hand, the arguments of \code{Apply} should be
  11521. atomic expressions.
  11522. %
  11523. Regarding \code{FunRef}, as discussed above, the function label needs
  11524. to be converted to an address using the \code{leaq} instruction. Thus,
  11525. even though \code{FunRef} seems rather simple, it needs to be
  11526. classified as a complex expression so that we generate an assignment
  11527. statement with a left-hand side that can serve as the target of the
  11528. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  11529. output language \LangFunANF{} of this pass.
  11530. \begin{figure}[tp]
  11531. \centering
  11532. \fbox{
  11533. \begin{minipage}{0.96\textwidth}
  11534. \small
  11535. \[
  11536. \begin{array}{rcl}
  11537. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  11538. \MID \VOID{} } \\
  11539. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  11540. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  11541. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  11542. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  11543. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  11544. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  11545. \MID \LP\key{GlobalValue}~\Var\RP }\\
  11546. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  11547. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11548. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  11549. \end{array}
  11550. \]
  11551. \end{minipage}
  11552. }
  11553. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  11554. \label{fig:Rfun-anf-syntax}
  11555. \end{figure}
  11556. \section{Explicate Control and the \LangCFun{} language}
  11557. \label{sec:explicate-control-r4}
  11558. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  11559. output of \code{explicate\_control}. (The concrete syntax is given in
  11560. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  11561. functions for assignment and tail contexts should be updated with
  11562. cases for \code{Apply} and \code{FunRef} and the function for
  11563. predicate context should be updated for \code{Apply} but not
  11564. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  11565. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  11566. tail position \code{Apply} becomes \code{TailCall}. We recommend
  11567. defining a new auxiliary function for processing function definitions.
  11568. This code is similar to the case for \code{Program} in \LangVec{}. The
  11569. top-level \code{explicate\_control} function that handles the
  11570. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  11571. all the function definitions.
  11572. \begin{figure}[tp]
  11573. \fbox{
  11574. \begin{minipage}{0.96\textwidth}
  11575. \small
  11576. \[
  11577. \begin{array}{lcl}
  11578. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  11579. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  11580. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  11581. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  11582. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  11583. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  11584. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  11585. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  11586. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  11587. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  11588. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  11589. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  11590. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  11591. \MID \GOTO{\itm{label}} } \\
  11592. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  11593. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  11594. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  11595. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11596. \end{array}
  11597. \]
  11598. \end{minipage}
  11599. }
  11600. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  11601. \label{fig:c3-syntax}
  11602. \end{figure}
  11603. \section{Select Instructions and the \LangXIndCall{} Language}
  11604. \label{sec:select-r4}
  11605. \index{subject}{instruction selection}
  11606. The output of select instructions is a program in the \LangXIndCall{}
  11607. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  11608. \index{subject}{x86}
  11609. \begin{figure}[tp]
  11610. \fbox{
  11611. \begin{minipage}{0.96\textwidth}
  11612. \small
  11613. \[
  11614. \begin{array}{lcl}
  11615. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  11616. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  11617. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  11618. \Instr &::=& \ldots
  11619. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  11620. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  11621. \Block &::= & \Instr\ldots \\
  11622. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  11623. \LangXIndCallM{} &::= & \Def\ldots
  11624. \end{array}
  11625. \]
  11626. \end{minipage}
  11627. }
  11628. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  11629. \label{fig:x86-3-concrete}
  11630. \end{figure}
  11631. \begin{figure}[tp]
  11632. \fbox{
  11633. \begin{minipage}{0.96\textwidth}
  11634. \small
  11635. \[
  11636. \begin{array}{lcl}
  11637. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11638. \MID \BYTEREG{\Reg} } \\
  11639. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  11640. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  11641. \MID \TAILJMP{\Arg}{\itm{int}}\\
  11642. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  11643. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  11644. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  11645. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11646. \end{array}
  11647. \]
  11648. \end{minipage}
  11649. }
  11650. \caption{The abstract syntax of \LangXIndCall{} (extends
  11651. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  11652. \label{fig:x86-3}
  11653. \end{figure}
  11654. An assignment of a function reference to a variable becomes a
  11655. load-effective-address instruction as follows, where $\itm{lhs}'$
  11656. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  11657. to \Arg{} in \LangXIndCallVar{}. \\
  11658. \begin{tabular}{lcl}
  11659. \begin{minipage}{0.35\textwidth}
  11660. \begin{lstlisting}
  11661. |$\itm{lhs}$| = (fun-ref |$f$|);
  11662. \end{lstlisting}
  11663. \end{minipage}
  11664. &
  11665. $\Rightarrow$\qquad\qquad
  11666. &
  11667. \begin{minipage}{0.3\textwidth}
  11668. \begin{lstlisting}
  11669. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  11670. \end{lstlisting}
  11671. \end{minipage}
  11672. \end{tabular} \\
  11673. Regarding function definitions, we need to remove the parameters and
  11674. instead perform parameter passing using the conventions discussed in
  11675. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  11676. registers. We recommend turning the parameters into local variables
  11677. and generating instructions at the beginning of the function to move
  11678. from the argument passing registers to these local variables.
  11679. \begin{lstlisting}
  11680. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  11681. |$\Rightarrow$|
  11682. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  11683. \end{lstlisting}
  11684. The $G'$ control-flow graph is the same as $G$ except that the
  11685. \code{start} block is modified to add the instructions for moving from
  11686. the argument registers to the parameter variables. So the \code{start}
  11687. block of $G$ shown on the left is changed to the code on the right.
  11688. \begin{center}
  11689. \begin{minipage}{0.3\textwidth}
  11690. \begin{lstlisting}
  11691. start:
  11692. |$\itm{instr}_1$|
  11693. |$\vdots$|
  11694. |$\itm{instr}_n$|
  11695. \end{lstlisting}
  11696. \end{minipage}
  11697. $\Rightarrow$
  11698. \begin{minipage}{0.3\textwidth}
  11699. \begin{lstlisting}
  11700. start:
  11701. movq %rdi, |$x_1$|
  11702. movq %rsi, |$x_2$|
  11703. |$\vdots$|
  11704. |$\itm{instr}_1$|
  11705. |$\vdots$|
  11706. |$\itm{instr}_n$|
  11707. \end{lstlisting}
  11708. \end{minipage}
  11709. \end{center}
  11710. By changing the parameters to local variables, we are giving the
  11711. register allocator control over which registers or stack locations to
  11712. use for them. If you implemented the move-biasing challenge
  11713. (Section~\ref{sec:move-biasing}), the register allocator will try to
  11714. assign the parameter variables to the corresponding argument register,
  11715. in which case the \code{patch\_instructions} pass will remove the
  11716. \code{movq} instruction. This happens in the example translation in
  11717. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  11718. the \code{add} function.
  11719. %
  11720. Also, note that the register allocator will perform liveness analysis
  11721. on this sequence of move instructions and build the interference
  11722. graph. So, for example, $x_1$ will be marked as interfering with
  11723. \code{rsi} and that will prevent the assignment of $x_1$ to
  11724. \code{rsi}, which is good, because that would overwrite the argument
  11725. that needs to move into $x_2$.
  11726. Next, consider the compilation of function calls. In the mirror image
  11727. of handling the parameters of function definitions, the arguments need
  11728. to be moved to the argument passing registers. The function call
  11729. itself is performed with an indirect function call. The return value
  11730. from the function is stored in \code{rax}, so it needs to be moved
  11731. into the \itm{lhs}.
  11732. \begin{lstlisting}
  11733. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  11734. |$\Rightarrow$|
  11735. movq |$\itm{arg}_1$|, %rdi
  11736. movq |$\itm{arg}_2$|, %rsi
  11737. |$\vdots$|
  11738. callq *|\itm{fun}|
  11739. movq %rax, |\itm{lhs}|
  11740. \end{lstlisting}
  11741. The \code{IndirectCallq} AST node includes an integer for the arity of
  11742. the function, i.e., the number of parameters. That information is
  11743. useful in the \code{uncover-live} pass for determining which
  11744. argument-passing registers are potentially read during the call.
  11745. For tail calls, the parameter passing is the same as non-tail calls:
  11746. generate instructions to move the arguments into to the argument
  11747. passing registers. After that we need to pop the frame from the
  11748. procedure call stack. However, we do not yet know how big the frame
  11749. is; that gets determined during register allocation. So instead of
  11750. generating those instructions here, we invent a new instruction that
  11751. means ``pop the frame and then do an indirect jump'', which we name
  11752. \code{TailJmp}. The abstract syntax for this instruction includes an
  11753. argument that specifies where to jump and an integer that represents
  11754. the arity of the function being called.
  11755. Recall that in Section~\ref{sec:explicate-control-Lvar} we recommended
  11756. using the label \code{start} for the initial block of a program, and
  11757. in Section~\ref{sec:select-Lvar} we recommended labeling the conclusion
  11758. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  11759. can be compiled to an assignment to \code{rax} followed by a jump to
  11760. \code{conclusion}. With the addition of function definitions, we will
  11761. have a starting block and conclusion for each function, but their
  11762. labels need to be unique. We recommend prepending the function's name
  11763. to \code{start} and \code{conclusion}, respectively, to obtain unique
  11764. labels. (Alternatively, one could \code{gensym} labels for the start
  11765. and conclusion and store them in the $\itm{info}$ field of the
  11766. function definition.)
  11767. \section{Register Allocation}
  11768. \label{sec:register-allocation-r4}
  11769. \subsection{Liveness Analysis}
  11770. \label{sec:liveness-analysis-r4}
  11771. \index{subject}{liveness analysis}
  11772. %% The rest of the passes need only minor modifications to handle the new
  11773. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  11774. %% \code{leaq}.
  11775. The \code{IndirectCallq} instruction should be treated like
  11776. \code{Callq} regarding its written locations $W$, in that they should
  11777. include all the caller-saved registers. Recall that the reason for
  11778. that is to force call-live variables to be assigned to callee-saved
  11779. registers or to be spilled to the stack.
  11780. Regarding the set of read locations $R$ the arity field of
  11781. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  11782. argument-passing registers should be considered as read by those
  11783. instructions.
  11784. \subsection{Build Interference Graph}
  11785. \label{sec:build-interference-r4}
  11786. With the addition of function definitions, we compute an interference
  11787. graph for each function (not just one for the whole program).
  11788. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  11789. spill vector-typed variables that are live during a call to the
  11790. \code{collect}. With the addition of functions to our language, we
  11791. need to revisit this issue. Many functions perform allocation and
  11792. therefore have calls to the collector inside of them. Thus, we should
  11793. not only spill a vector-typed variable when it is live during a call
  11794. to \code{collect}, but we should spill the variable if it is live
  11795. during any function call. Thus, in the \code{build\_interference} pass,
  11796. we recommend adding interference edges between call-live vector-typed
  11797. variables and the callee-saved registers (in addition to the usual
  11798. addition of edges between call-live variables and the caller-saved
  11799. registers).
  11800. \subsection{Allocate Registers}
  11801. The primary change to the \code{allocate\_registers} pass is adding an
  11802. auxiliary function for handling definitions (the \Def{} non-terminal
  11803. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  11804. logic is the same as described in
  11805. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  11806. allocation is performed many times, once for each function definition,
  11807. instead of just once for the whole program.
  11808. \section{Patch Instructions}
  11809. In \code{patch\_instructions}, you should deal with the x86
  11810. idiosyncrasy that the destination argument of \code{leaq} must be a
  11811. register. Additionally, you should ensure that the argument of
  11812. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  11813. code generation more convenient, because we trample many registers
  11814. before the tail call (as explained in the next section).
  11815. \section{Print x86}
  11816. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  11817. \code{IndirectCallq} are straightforward: output their concrete
  11818. syntax.
  11819. \begin{lstlisting}
  11820. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  11821. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  11822. \end{lstlisting}
  11823. The \code{TailJmp} node requires a bit work. A straightforward
  11824. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  11825. before the jump we need to pop the current frame. This sequence of
  11826. instructions is the same as the code for the conclusion of a function,
  11827. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  11828. Regarding function definitions, you will need to generate a prelude
  11829. and conclusion for each one. This code is similar to the prelude and
  11830. conclusion that you generated for the \code{main} function in
  11831. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  11832. should carry out the following steps.
  11833. \begin{enumerate}
  11834. \item Start with \code{.global} and \code{.align} directives followed
  11835. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  11836. example.)
  11837. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  11838. pointer.
  11839. \item Push to the stack all of the callee-saved registers that were
  11840. used for register allocation.
  11841. \item Move the stack pointer \code{rsp} down by the size of the stack
  11842. frame for this function, which depends on the number of regular
  11843. spills. (Aligned to 16 bytes.)
  11844. \item Move the root stack pointer \code{r15} up by the size of the
  11845. root-stack frame for this function, which depends on the number of
  11846. spilled vectors. \label{root-stack-init}
  11847. \item Initialize to zero all of the entries in the root-stack frame.
  11848. \item Jump to the start block.
  11849. \end{enumerate}
  11850. The prelude of the \code{main} function has one additional task: call
  11851. the \code{initialize} function to set up the garbage collector and
  11852. move the value of the global \code{rootstack\_begin} in
  11853. \code{r15}. This should happen before step \ref{root-stack-init}
  11854. above, which depends on \code{r15}.
  11855. The conclusion of every function should do the following.
  11856. \begin{enumerate}
  11857. \item Move the stack pointer back up by the size of the stack frame
  11858. for this function.
  11859. \item Restore the callee-saved registers by popping them from the
  11860. stack.
  11861. \item Move the root stack pointer back down by the size of the
  11862. root-stack frame for this function.
  11863. \item Restore \code{rbp} by popping it from the stack.
  11864. \item Return to the caller with the \code{retq} instruction.
  11865. \end{enumerate}
  11866. \begin{exercise}\normalfont
  11867. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  11868. Create 5 new programs that use functions, including examples that pass
  11869. functions and return functions from other functions, recursive
  11870. functions, functions that create vectors, and functions that make tail
  11871. calls. Test your compiler on these new programs and all of your
  11872. previously created test programs.
  11873. \end{exercise}
  11874. \begin{figure}[tbp]
  11875. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11876. \node (Rfun) at (0,2) {\large \LangFun{}};
  11877. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  11878. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  11879. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  11880. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  11881. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  11882. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  11883. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  11884. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11885. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11886. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11887. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11888. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11889. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11890. \path[->,bend left=15] (Rfun) edge [above] node
  11891. {\ttfamily\footnotesize shrink} (Rfun-1);
  11892. \path[->,bend left=15] (Rfun-1) edge [above] node
  11893. {\ttfamily\footnotesize uniquify} (Rfun-2);
  11894. \path[->,bend left=15] (Rfun-2) edge [right] node
  11895. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  11896. \path[->,bend left=15] (F1-1) edge [below] node
  11897. {\ttfamily\footnotesize limit\_functions} (F1-2);
  11898. \path[->,bend right=15] (F1-2) edge [above] node
  11899. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  11900. \path[->,bend right=15] (F1-3) edge [above] node
  11901. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  11902. \path[->,bend left=15] (F1-4) edge [right] node
  11903. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11904. \path[->,bend right=15] (C3-2) edge [left] node
  11905. {\ttfamily\footnotesize select\_instr.} (x86-2);
  11906. \path[->,bend left=15] (x86-2) edge [left] node
  11907. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11908. \path[->,bend right=15] (x86-2-1) edge [below] node
  11909. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11910. \path[->,bend right=15] (x86-2-2) edge [left] node
  11911. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11912. \path[->,bend left=15] (x86-3) edge [above] node
  11913. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11914. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  11915. \end{tikzpicture}
  11916. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  11917. \label{fig:Rfun-passes}
  11918. \end{figure}
  11919. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  11920. compiling \LangFun{} to x86.
  11921. \section{An Example Translation}
  11922. \label{sec:functions-example}
  11923. Figure~\ref{fig:add-fun} shows an example translation of a simple
  11924. function in \LangFun{} to x86. The figure also includes the results of the
  11925. \code{explicate\_control} and \code{select\_instructions} passes.
  11926. \begin{figure}[htbp]
  11927. \begin{tabular}{ll}
  11928. \begin{minipage}{0.5\textwidth}
  11929. % s3_2.rkt
  11930. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11931. (define (add [x : Integer] [y : Integer])
  11932. : Integer
  11933. (+ x y))
  11934. (add 40 2)
  11935. \end{lstlisting}
  11936. $\Downarrow$
  11937. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11938. (define (add86 [x87 : Integer]
  11939. [y88 : Integer]) : Integer
  11940. add86start:
  11941. return (+ x87 y88);
  11942. )
  11943. (define (main) : Integer ()
  11944. mainstart:
  11945. tmp89 = (fun-ref add86);
  11946. (tail-call tmp89 40 2)
  11947. )
  11948. \end{lstlisting}
  11949. \end{minipage}
  11950. &
  11951. $\Rightarrow$
  11952. \begin{minipage}{0.5\textwidth}
  11953. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11954. (define (add86) : Integer
  11955. add86start:
  11956. movq %rdi, x87
  11957. movq %rsi, y88
  11958. movq x87, %rax
  11959. addq y88, %rax
  11960. jmp add11389conclusion
  11961. )
  11962. (define (main) : Integer
  11963. mainstart:
  11964. leaq (fun-ref add86), tmp89
  11965. movq $40, %rdi
  11966. movq $2, %rsi
  11967. tail-jmp tmp89
  11968. )
  11969. \end{lstlisting}
  11970. $\Downarrow$
  11971. \end{minipage}
  11972. \end{tabular}
  11973. \begin{tabular}{ll}
  11974. \begin{minipage}{0.3\textwidth}
  11975. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11976. .globl add86
  11977. .align 16
  11978. add86:
  11979. pushq %rbp
  11980. movq %rsp, %rbp
  11981. jmp add86start
  11982. add86start:
  11983. movq %rdi, %rax
  11984. addq %rsi, %rax
  11985. jmp add86conclusion
  11986. add86conclusion:
  11987. popq %rbp
  11988. retq
  11989. \end{lstlisting}
  11990. \end{minipage}
  11991. &
  11992. \begin{minipage}{0.5\textwidth}
  11993. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11994. .globl main
  11995. .align 16
  11996. main:
  11997. pushq %rbp
  11998. movq %rsp, %rbp
  11999. movq $16384, %rdi
  12000. movq $16384, %rsi
  12001. callq initialize
  12002. movq rootstack_begin(%rip), %r15
  12003. jmp mainstart
  12004. mainstart:
  12005. leaq add86(%rip), %rcx
  12006. movq $40, %rdi
  12007. movq $2, %rsi
  12008. movq %rcx, %rax
  12009. popq %rbp
  12010. jmp *%rax
  12011. mainconclusion:
  12012. popq %rbp
  12013. retq
  12014. \end{lstlisting}
  12015. \end{minipage}
  12016. \end{tabular}
  12017. \caption{Example compilation of a simple function to x86.}
  12018. \label{fig:add-fun}
  12019. \end{figure}
  12020. % Challenge idea: inlining! (simple version)
  12021. % Further Reading
  12022. \fi % racketEd
  12023. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12024. \chapter{Lexically Scoped Functions}
  12025. \label{ch:Rlam}
  12026. \index{subject}{lambda}
  12027. \index{subject}{lexical scoping}
  12028. \if\edition\racketEd
  12029. This chapter studies lexically scoped functions as they appear in
  12030. functional languages such as Racket. By lexical scoping we mean that a
  12031. function's body may refer to variables whose binding site is outside
  12032. of the function, in an enclosing scope.
  12033. %
  12034. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  12035. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  12036. \key{lambda} form. The body of the \key{lambda}, refers to three
  12037. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  12038. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  12039. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  12040. parameter of function \code{f}. The \key{lambda} is returned from the
  12041. function \code{f}. The main expression of the program includes two
  12042. calls to \code{f} with different arguments for \code{x}, first
  12043. \code{5} then \code{3}. The functions returned from \code{f} are bound
  12044. to variables \code{g} and \code{h}. Even though these two functions
  12045. were created by the same \code{lambda}, they are really different
  12046. functions because they use different values for \code{x}. Applying
  12047. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  12048. \code{15} produces \code{22}. The result of this program is \code{42}.
  12049. \begin{figure}[btp]
  12050. % s4_6.rkt
  12051. \begin{lstlisting}
  12052. (define (f [x : Integer]) : (Integer -> Integer)
  12053. (let ([y 4])
  12054. (lambda: ([z : Integer]) : Integer
  12055. (+ x (+ y z)))))
  12056. (let ([g (f 5)])
  12057. (let ([h (f 3)])
  12058. (+ (g 11) (h 15))))
  12059. \end{lstlisting}
  12060. \caption{Example of a lexically scoped function.}
  12061. \label{fig:lexical-scoping}
  12062. \end{figure}
  12063. The approach that we take for implementing lexically scoped
  12064. functions is to compile them into top-level function definitions,
  12065. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  12066. provide special treatment for variable occurrences such as \code{x}
  12067. and \code{y} in the body of the \code{lambda} of
  12068. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  12069. refer to variables defined outside of it. To identify such variable
  12070. occurrences, we review the standard notion of free variable.
  12071. \begin{definition}
  12072. A variable is \emph{free in expression} $e$ if the variable occurs
  12073. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  12074. variable}
  12075. \end{definition}
  12076. For example, in the expression \code{(+ x (+ y z))} the variables
  12077. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  12078. only \code{x} and \code{y} are free in the following expression
  12079. because \code{z} is bound by the \code{lambda}.
  12080. \begin{lstlisting}
  12081. (lambda: ([z : Integer]) : Integer
  12082. (+ x (+ y z)))
  12083. \end{lstlisting}
  12084. So the free variables of a \code{lambda} are the ones that will need
  12085. special treatment. We need to arrange for some way to transport, at
  12086. runtime, the values of those variables from the point where the
  12087. \code{lambda} was created to the point where the \code{lambda} is
  12088. applied. An efficient solution to the problem, due to
  12089. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  12090. free variables together with the function pointer for the lambda's
  12091. code, an arrangement called a \emph{flat closure} (which we shorten to
  12092. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  12093. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  12094. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  12095. pointers. The function pointer resides at index $0$ and the
  12096. values for the free variables will fill in the rest of the vector.
  12097. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  12098. how closures work. It's a three-step dance. The program first calls
  12099. function \code{f}, which creates a closure for the \code{lambda}. The
  12100. closure is a vector whose first element is a pointer to the top-level
  12101. function that we will generate for the \code{lambda}, the second
  12102. element is the value of \code{x}, which is \code{5}, and the third
  12103. element is \code{4}, the value of \code{y}. The closure does not
  12104. contain an element for \code{z} because \code{z} is not a free
  12105. variable of the \code{lambda}. Creating the closure is step 1 of the
  12106. dance. The closure is returned from \code{f} and bound to \code{g}, as
  12107. shown in Figure~\ref{fig:closures}.
  12108. %
  12109. The second call to \code{f} creates another closure, this time with
  12110. \code{3} in the second slot (for \code{x}). This closure is also
  12111. returned from \code{f} but bound to \code{h}, which is also shown in
  12112. Figure~\ref{fig:closures}.
  12113. \begin{figure}[tbp]
  12114. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  12115. \caption{Example closure representation for the \key{lambda}'s
  12116. in Figure~\ref{fig:lexical-scoping}.}
  12117. \label{fig:closures}
  12118. \end{figure}
  12119. Continuing with the example, consider the application of \code{g} to
  12120. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  12121. obtain the function pointer in the first element of the closure and
  12122. call it, passing in the closure itself and then the regular arguments,
  12123. in this case \code{11}. This technique for applying a closure is step
  12124. 2 of the dance.
  12125. %
  12126. But doesn't this \code{lambda} only take 1 argument, for parameter
  12127. \code{z}? The third and final step of the dance is generating a
  12128. top-level function for a \code{lambda}. We add an additional
  12129. parameter for the closure and we insert a \code{let} at the beginning
  12130. of the function for each free variable, to bind those variables to the
  12131. appropriate elements from the closure parameter.
  12132. %
  12133. This three-step dance is known as \emph{closure conversion}. We
  12134. discuss the details of closure conversion in
  12135. Section~\ref{sec:closure-conversion} and the code generated from the
  12136. example in Section~\ref{sec:example-lambda}. But first we define the
  12137. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  12138. \section{The \LangLam{} Language}
  12139. \label{sec:r5}
  12140. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  12141. functions and lexical scoping, is defined in
  12142. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  12143. the \key{lambda} form to the grammar for \LangFun{}, which already has
  12144. syntax for function application.
  12145. \begin{figure}[tp]
  12146. \centering
  12147. \fbox{
  12148. \begin{minipage}{0.96\textwidth}
  12149. \small
  12150. \[
  12151. \begin{array}{lcl}
  12152. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  12153. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  12154. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  12155. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12156. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12157. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12158. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12159. \MID (\key{and}\;\Exp\;\Exp)
  12160. \MID (\key{or}\;\Exp\;\Exp)
  12161. \MID (\key{not}\;\Exp) } \\
  12162. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12163. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12164. (\key{vector-ref}\;\Exp\;\Int)} \\
  12165. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12166. \MID (\Exp \; \Exp\ldots) } \\
  12167. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  12168. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  12169. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12170. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  12171. \end{array}
  12172. \]
  12173. \end{minipage}
  12174. }
  12175. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  12176. with \key{lambda}.}
  12177. \label{fig:Rlam-concrete-syntax}
  12178. \end{figure}
  12179. \begin{figure}[tp]
  12180. \centering
  12181. \fbox{
  12182. \begin{minipage}{0.96\textwidth}
  12183. \small
  12184. \[
  12185. \begin{array}{lcl}
  12186. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  12187. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12188. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12189. &\MID& \gray{ \BOOL{\itm{bool}}
  12190. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12191. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12192. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12193. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  12194. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  12195. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12196. \end{array}
  12197. \]
  12198. \end{minipage}
  12199. }
  12200. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  12201. \label{fig:Rlam-syntax}
  12202. \end{figure}
  12203. \index{subject}{interpreter}
  12204. \label{sec:interp-Rlambda}
  12205. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  12206. \LangLam{}. The case for \key{lambda} saves the current environment
  12207. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  12208. the environment from the \key{lambda}, the \code{lam-env}, when
  12209. interpreting the body of the \key{lambda}. The \code{lam-env}
  12210. environment is extended with the mapping of parameters to argument
  12211. values.
  12212. \begin{figure}[tbp]
  12213. \begin{lstlisting}
  12214. (define interp-Rlambda_class
  12215. (class interp-Rfun_class
  12216. (super-new)
  12217. (define/override (interp-op op)
  12218. (match op
  12219. ['procedure-arity
  12220. (lambda (v)
  12221. (match v
  12222. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  12223. [else (error 'interp-op "expected a function, not ~a" v)]))]
  12224. [else (super interp-op op)]))
  12225. (define/override ((interp-exp env) e)
  12226. (define recur (interp-exp env))
  12227. (match e
  12228. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  12229. `(function ,xs ,body ,env)]
  12230. [else ((super interp-exp env) e)]))
  12231. ))
  12232. (define (interp-Rlambda p)
  12233. (send (new interp-Rlambda_class) interp-program p))
  12234. \end{lstlisting}
  12235. \caption{Interpreter for \LangLam{}.}
  12236. \label{fig:interp-Rlambda}
  12237. \end{figure}
  12238. \label{sec:type-check-r5}
  12239. \index{subject}{type checking}
  12240. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  12241. \key{lambda} form. The body of the \key{lambda} is checked in an
  12242. environment that includes the current environment (because it is
  12243. lexically scoped) and also includes the \key{lambda}'s parameters. We
  12244. require the body's type to match the declared return type.
  12245. \begin{figure}[tbp]
  12246. \begin{lstlisting}
  12247. (define (type-check-Rlambda env)
  12248. (lambda (e)
  12249. (match e
  12250. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  12251. (define-values (new-body bodyT)
  12252. ((type-check-exp (append (map cons xs Ts) env)) body))
  12253. (define ty `(,@Ts -> ,rT))
  12254. (cond
  12255. [(equal? rT bodyT)
  12256. (values (HasType (Lambda params rT new-body) ty) ty)]
  12257. [else
  12258. (error "mismatch in return type" bodyT rT)])]
  12259. ...
  12260. )))
  12261. \end{lstlisting}
  12262. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  12263. \label{fig:type-check-Rlambda}
  12264. \end{figure}
  12265. \section{Assignment and Lexically Scoped Functions}
  12266. \label{sec:assignment-scoping}
  12267. [UNDER CONSTRUCTION: This section was just moved into this location
  12268. and may need to be updated. -Jeremy]
  12269. The combination of lexically-scoped functions and assignment
  12270. (i.e. \code{set!}) raises a challenge with our approach to
  12271. implementing lexically-scoped functions. Consider the following
  12272. example in which function \code{f} has a free variable \code{x} that
  12273. is changed after \code{f} is created but before the call to \code{f}.
  12274. % loop_test_11.rkt
  12275. \begin{lstlisting}
  12276. (let ([x 0])
  12277. (let ([y 0])
  12278. (let ([z 20])
  12279. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  12280. (begin
  12281. (set! x 10)
  12282. (set! y 12)
  12283. (f y))))))
  12284. \end{lstlisting}
  12285. The correct output for this example is \code{42} because the call to
  12286. \code{f} is required to use the current value of \code{x} (which is
  12287. \code{10}). Unfortunately, the closure conversion pass
  12288. (Section~\ref{sec:closure-conversion}) generates code for the
  12289. \code{lambda} that copies the old value of \code{x} into a
  12290. closure. Thus, if we naively add support for assignment to our current
  12291. compiler, the output of this program would be \code{32}.
  12292. A first attempt at solving this problem would be to save a pointer to
  12293. \code{x} in the closure and change the occurrences of \code{x} inside
  12294. the lambda to dereference the pointer. Of course, this would require
  12295. assigning \code{x} to the stack and not to a register. However, the
  12296. problem goes a bit deeper. Consider the following example in which we
  12297. create a counter abstraction by creating a pair of functions that
  12298. share the free variable \code{x}.
  12299. % similar to loop_test_10.rkt
  12300. \begin{lstlisting}
  12301. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  12302. (vector
  12303. (lambda: () : Integer x)
  12304. (lambda: () : Void (set! x (+ 1 x)))))
  12305. (let ([counter (f 0)])
  12306. (let ([get (vector-ref counter 0)])
  12307. (let ([inc (vector-ref counter 1)])
  12308. (begin
  12309. (inc)
  12310. (get)))))
  12311. \end{lstlisting}
  12312. In this example, the lifetime of \code{x} extends beyond the lifetime
  12313. of the call to \code{f}. Thus, if we were to store \code{x} on the
  12314. stack frame for the call to \code{f}, it would be gone by the time we
  12315. call \code{inc} and \code{get}, leaving us with dangling pointers for
  12316. \code{x}. This example demonstrates that when a variable occurs free
  12317. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  12318. value of the variable needs to live on the heap. The verb ``box'' is
  12319. often used for allocating a single value on the heap, producing a
  12320. pointer, and ``unbox'' for dereferencing the pointer.
  12321. We recommend solving these problems by ``boxing'' the local variables
  12322. that are in the intersection of 1) variables that appear on the
  12323. left-hand-side of a \code{set!} and 2) variables that occur free
  12324. inside a \code{lambda}. We shall introduce a new pass named
  12325. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  12326. perform this translation. But before diving into the compiler passes,
  12327. we one more problem to discuss.
  12328. \section{Reveal Functions and the $F_2$ language}
  12329. \label{sec:reveal-functions-r5}
  12330. To support the \code{procedure-arity} operator we need to communicate
  12331. the arity of a function to the point of closure creation. We can
  12332. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  12333. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  12334. output of this pass is the language $F_2$, whose syntax is defined in
  12335. Figure~\ref{fig:f2-syntax}.
  12336. \begin{figure}[tp]
  12337. \centering
  12338. \fbox{
  12339. \begin{minipage}{0.96\textwidth}
  12340. \[
  12341. \begin{array}{lcl}
  12342. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  12343. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12344. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  12345. \end{array}
  12346. \]
  12347. \end{minipage}
  12348. }
  12349. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  12350. (Figure~\ref{fig:Rlam-syntax}).}
  12351. \label{fig:f2-syntax}
  12352. \end{figure}
  12353. \section{Convert Assignments}
  12354. \label{sec:convert-assignments}
  12355. [UNDER CONSTRUCTION: This section was just moved into this location
  12356. and may need to be updated. -Jeremy]
  12357. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  12358. the combination of assignments and lexically-scoped functions requires
  12359. that we box those variables that are both assigned-to and that appear
  12360. free inside a \code{lambda}. The purpose of the
  12361. \code{convert-assignments} pass is to carry out that transformation.
  12362. We recommend placing this pass after \code{uniquify} but before
  12363. \code{reveal-functions}.
  12364. Consider again the first example from
  12365. Section~\ref{sec:assignment-scoping}:
  12366. \begin{lstlisting}
  12367. (let ([x 0])
  12368. (let ([y 0])
  12369. (let ([z 20])
  12370. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  12371. (begin
  12372. (set! x 10)
  12373. (set! y 12)
  12374. (f y))))))
  12375. \end{lstlisting}
  12376. The variables \code{x} and \code{y} are assigned-to. The variables
  12377. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  12378. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  12379. The boxing of \code{x} consists of three transformations: initialize
  12380. \code{x} with a vector, replace reads from \code{x} with
  12381. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  12382. \code{vector-set!}. The output of \code{convert-assignments} for this
  12383. example is as follows.
  12384. \begin{lstlisting}
  12385. (define (main) : Integer
  12386. (let ([x0 (vector 0)])
  12387. (let ([y1 0])
  12388. (let ([z2 20])
  12389. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  12390. (+ a3 (+ (vector-ref x0 0) z2)))])
  12391. (begin
  12392. (vector-set! x0 0 10)
  12393. (set! y1 12)
  12394. (f4 y1)))))))
  12395. \end{lstlisting}
  12396. \paragraph{Assigned \& Free}
  12397. We recommend defining an auxiliary function named
  12398. \code{assigned\&free} that takes an expression and simultaneously
  12399. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  12400. that occur free within lambda's, and 3) a new version of the
  12401. expression that records which bound variables occurred in the
  12402. intersection of $A$ and $F$. You can use the struct
  12403. \code{AssignedFree} to do this. Consider the case for
  12404. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  12405. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  12406. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  12407. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  12408. \begin{lstlisting}
  12409. (Let |$x$| |$rhs$| |$body$|)
  12410. |$\Rightarrow$|
  12411. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  12412. \end{lstlisting}
  12413. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  12414. The set of assigned variables for this \code{Let} is
  12415. $A_r \cup (A_b - \{x\})$
  12416. and the set of variables free in lambda's is
  12417. $F_r \cup (F_b - \{x\})$.
  12418. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  12419. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  12420. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  12421. and $F_r$.
  12422. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  12423. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  12424. recursively processing \itm{body}. Wrap each of parameter that occurs
  12425. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  12426. Let $P$ be the set of parameter names in \itm{params}. The result is
  12427. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  12428. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  12429. variables of an expression (see Chapter~\ref{ch:Rlam}).
  12430. \paragraph{Convert Assignments}
  12431. Next we discuss the \code{convert-assignment} pass with its auxiliary
  12432. functions for expressions and definitions. The function for
  12433. expressions, \code{cnvt-assign-exp}, should take an expression and a
  12434. set of assigned-and-free variables (obtained from the result of
  12435. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  12436. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  12437. \code{vector-ref}.
  12438. \begin{lstlisting}
  12439. (Var |$x$|)
  12440. |$\Rightarrow$|
  12441. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  12442. \end{lstlisting}
  12443. %
  12444. In the case for $\LET{\LP\code{AssignedFree}\,
  12445. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  12446. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  12447. \itm{body'} but with $x$ added to the set of assigned-and-free
  12448. variables. Translate the let-expression as follows to bind $x$ to a
  12449. boxed value.
  12450. \begin{lstlisting}
  12451. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  12452. |$\Rightarrow$|
  12453. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  12454. \end{lstlisting}
  12455. %
  12456. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  12457. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  12458. variables, translate the \code{set!} into a \code{vector-set!}
  12459. as follows.
  12460. \begin{lstlisting}
  12461. (SetBang |$x$| |$\itm{rhs}$|)
  12462. |$\Rightarrow$|
  12463. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  12464. \end{lstlisting}
  12465. %
  12466. The case for \code{Lambda} is non-trivial, but it is similar to the
  12467. case for function definitions, which we discuss next.
  12468. The auxiliary function for definitions, \code{cnvt-assign-def},
  12469. applies assignment conversion to function definitions.
  12470. We translate a function definition as follows.
  12471. \begin{lstlisting}
  12472. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  12473. |$\Rightarrow$|
  12474. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  12475. \end{lstlisting}
  12476. So it remains to explain \itm{params'} and $\itm{body}_4$.
  12477. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  12478. \code{assigned\&free} on $\itm{body_1}$.
  12479. Let $P$ be the parameter names in \itm{params}.
  12480. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  12481. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  12482. as the set of assigned-and-free variables.
  12483. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  12484. in a sequence of let-expressions that box the parameters
  12485. that are in $A_b \cap F_b$.
  12486. %
  12487. Regarding \itm{params'}, change the names of the parameters that are
  12488. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  12489. variables can retain the original names). Recall the second example in
  12490. Section~\ref{sec:assignment-scoping} involving a counter
  12491. abstraction. The following is the output of assignment version for
  12492. function \code{f}.
  12493. \begin{lstlisting}
  12494. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  12495. (vector
  12496. (lambda: () : Integer x1)
  12497. (lambda: () : Void (set! x1 (+ 1 x1)))))
  12498. |$\Rightarrow$|
  12499. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  12500. (let ([x1 (vector param_x1)])
  12501. (vector (lambda: () : Integer (vector-ref x1 0))
  12502. (lambda: () : Void
  12503. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  12504. \end{lstlisting}
  12505. \section{Closure Conversion}
  12506. \label{sec:closure-conversion}
  12507. \index{subject}{closure conversion}
  12508. The compiling of lexically-scoped functions into top-level function
  12509. definitions is accomplished in the pass \code{convert-to-closures}
  12510. that comes after \code{reveal-functions} and before
  12511. \code{limit-functions}.
  12512. As usual, we implement the pass as a recursive function over the
  12513. AST. All of the action is in the cases for \key{Lambda} and
  12514. \key{Apply}. We transform a \key{Lambda} expression into an expression
  12515. that creates a closure, that is, a vector whose first element is a
  12516. function pointer and the rest of the elements are the free variables
  12517. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  12518. using \code{vector} so that we can distinguish closures from vectors
  12519. in Section~\ref{sec:optimize-closures} and to record the arity. In
  12520. the generated code below, the \itm{name} is a unique symbol generated
  12521. to identify the function and the \itm{arity} is the number of
  12522. parameters (the length of \itm{ps}).
  12523. \begin{lstlisting}
  12524. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  12525. |$\Rightarrow$|
  12526. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  12527. \end{lstlisting}
  12528. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  12529. create a top-level function definition for each \key{Lambda}, as
  12530. shown below.\\
  12531. \begin{minipage}{0.8\textwidth}
  12532. \begin{lstlisting}
  12533. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  12534. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  12535. ...
  12536. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  12537. |\itm{body'}|)...))
  12538. \end{lstlisting}
  12539. \end{minipage}\\
  12540. The \code{clos} parameter refers to the closure. Translate the type
  12541. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  12542. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  12543. $\itm{fvts}$ are the types of the free variables in the lambda and the
  12544. underscore \code{\_} is a dummy type that we use because it is rather
  12545. difficult to give a type to the function in the closure's
  12546. type.\footnote{To give an accurate type to a closure, we would need to
  12547. add existential types to the type checker~\citep{Minamide:1996ys}.}
  12548. The dummy type is considered to be equal to any other type during type
  12549. checking. The sequence of \key{Let} forms bind the free variables to
  12550. their values obtained from the closure.
  12551. Closure conversion turns functions into vectors, so the type
  12552. annotations in the program must also be translated. We recommend
  12553. defining a auxiliary recursive function for this purpose. Function
  12554. types should be translated as follows.
  12555. \begin{lstlisting}
  12556. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  12557. |$\Rightarrow$|
  12558. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  12559. \end{lstlisting}
  12560. The above type says that the first thing in the vector is a function
  12561. pointer. The first parameter of the function pointer is a vector (a
  12562. closure) and the rest of the parameters are the ones from the original
  12563. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  12564. the closure omits the types of the free variables because 1) those
  12565. types are not available in this context and 2) we do not need them in
  12566. the code that is generated for function application.
  12567. We transform function application into code that retrieves the
  12568. function pointer from the closure and then calls the function, passing
  12569. in the closure as the first argument. We bind $e'$ to a temporary
  12570. variable to avoid code duplication.
  12571. \begin{lstlisting}
  12572. (Apply |$e$| |\itm{es}|)
  12573. |$\Rightarrow$|
  12574. (Let |\itm{tmp}| |$e'$|
  12575. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  12576. \end{lstlisting}
  12577. There is also the question of what to do with references top-level
  12578. function definitions. To maintain a uniform translation of function
  12579. application, we turn function references into closures.
  12580. \begin{tabular}{lll}
  12581. \begin{minipage}{0.3\textwidth}
  12582. \begin{lstlisting}
  12583. (FunRefArity |$f$| |$n$|)
  12584. \end{lstlisting}
  12585. \end{minipage}
  12586. &
  12587. $\Rightarrow$
  12588. &
  12589. \begin{minipage}{0.5\textwidth}
  12590. \begin{lstlisting}
  12591. (Closure |$n$| (FunRef |$f$|) '())
  12592. \end{lstlisting}
  12593. \end{minipage}
  12594. \end{tabular} \\
  12595. %
  12596. The top-level function definitions need to be updated as well to take
  12597. an extra closure parameter.
  12598. \section{An Example Translation}
  12599. \label{sec:example-lambda}
  12600. Figure~\ref{fig:lexical-functions-example} shows the result of
  12601. \code{reveal-functions} and \code{convert-to-closures} for the example
  12602. program demonstrating lexical scoping that we discussed at the
  12603. beginning of this chapter.
  12604. \begin{figure}[tbp]
  12605. \begin{minipage}{0.8\textwidth}
  12606. % tests/lambda_test_6.rkt
  12607. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12608. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  12609. (let ([y8 4])
  12610. (lambda: ([z9 : Integer]) : Integer
  12611. (+ x7 (+ y8 z9)))))
  12612. (define (main) : Integer
  12613. (let ([g0 ((fun-ref-arity f6 1) 5)])
  12614. (let ([h1 ((fun-ref-arity f6 1) 3)])
  12615. (+ (g0 11) (h1 15)))))
  12616. \end{lstlisting}
  12617. $\Rightarrow$
  12618. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12619. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  12620. (let ([y8 4])
  12621. (closure 1 (list (fun-ref lambda2) x7 y8))))
  12622. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  12623. (let ([x7 (vector-ref fvs3 1)])
  12624. (let ([y8 (vector-ref fvs3 2)])
  12625. (+ x7 (+ y8 z9)))))
  12626. (define (main) : Integer
  12627. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  12628. ((vector-ref clos5 0) clos5 5))])
  12629. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  12630. ((vector-ref clos6 0) clos6 3))])
  12631. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  12632. \end{lstlisting}
  12633. \end{minipage}
  12634. \caption{Example of closure conversion.}
  12635. \label{fig:lexical-functions-example}
  12636. \end{figure}
  12637. \begin{exercise}\normalfont
  12638. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  12639. Create 5 new programs that use \key{lambda} functions and make use of
  12640. lexical scoping. Test your compiler on these new programs and all of
  12641. your previously created test programs.
  12642. \end{exercise}
  12643. \section{Expose Allocation}
  12644. \label{sec:expose-allocation-r5}
  12645. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  12646. that allocates and initializes a vector, similar to the translation of
  12647. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  12648. The only difference is replacing the use of
  12649. \ALLOC{\itm{len}}{\itm{type}} with
  12650. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  12651. \section{Explicate Control and \LangCLam{}}
  12652. \label{sec:explicate-r5}
  12653. The output language of \code{explicate\_control} is \LangCLam{} whose
  12654. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  12655. difference with respect to \LangCFun{} is the addition of the
  12656. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  12657. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  12658. similar to the handling of other expressions such as primitive
  12659. operators.
  12660. \begin{figure}[tp]
  12661. \fbox{
  12662. \begin{minipage}{0.96\textwidth}
  12663. \small
  12664. \[
  12665. \begin{array}{lcl}
  12666. \Exp &::= & \ldots
  12667. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  12668. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12669. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12670. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12671. \MID \GOTO{\itm{label}} } \\
  12672. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12673. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  12674. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  12675. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  12676. \end{array}
  12677. \]
  12678. \end{minipage}
  12679. }
  12680. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  12681. \label{fig:c4-syntax}
  12682. \end{figure}
  12683. \section{Select Instructions}
  12684. \label{sec:select-instructions-Rlambda}
  12685. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  12686. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  12687. (Section~\ref{sec:select-instructions-gc}). The only difference is
  12688. that you should place the \itm{arity} in the tag that is stored at
  12689. position $0$ of the vector. Recall that in
  12690. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  12691. was not used. We store the arity in the $5$ bits starting at position
  12692. $58$.
  12693. Compile the \code{procedure-arity} operator into a sequence of
  12694. instructions that access the tag from position $0$ of the vector and
  12695. extract the $5$-bits starting at position $58$ from the tag.
  12696. \begin{figure}[p]
  12697. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12698. \node (Rfun) at (0,2) {\large \LangFun{}};
  12699. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  12700. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  12701. \node (F1-0) at (9,2) {\large \LangFunRef{}};
  12702. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  12703. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  12704. \node (F1-3) at (6,0) {\large $F_1$};
  12705. \node (F1-4) at (3,0) {\large $F_1$};
  12706. \node (F1-5) at (0,0) {\large $F_1$};
  12707. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  12708. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12709. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12710. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12711. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12712. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12713. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12714. \path[->,bend left=15] (Rfun) edge [above] node
  12715. {\ttfamily\footnotesize shrink} (Rfun-2);
  12716. \path[->,bend left=15] (Rfun-2) edge [above] node
  12717. {\ttfamily\footnotesize uniquify} (Rfun-3);
  12718. \path[->,bend left=15] (Rfun-3) edge [above] node
  12719. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  12720. \path[->,bend left=15] (F1-0) edge [right] node
  12721. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  12722. \path[->,bend left=15] (F1-1) edge [below] node
  12723. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  12724. \path[->,bend right=15] (F1-2) edge [above] node
  12725. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  12726. \path[->,bend right=15] (F1-3) edge [above] node
  12727. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  12728. \path[->,bend right=15] (F1-4) edge [above] node
  12729. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  12730. \path[->,bend right=15] (F1-5) edge [right] node
  12731. {\ttfamily\footnotesize explicate\_control} (C3-2);
  12732. \path[->,bend left=15] (C3-2) edge [left] node
  12733. {\ttfamily\footnotesize select\_instr.} (x86-2);
  12734. \path[->,bend right=15] (x86-2) edge [left] node
  12735. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12736. \path[->,bend right=15] (x86-2-1) edge [below] node
  12737. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  12738. \path[->,bend right=15] (x86-2-2) edge [left] node
  12739. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  12740. \path[->,bend left=15] (x86-3) edge [above] node
  12741. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  12742. \path[->,bend left=15] (x86-4) edge [right] node
  12743. {\ttfamily\footnotesize print\_x86} (x86-5);
  12744. \end{tikzpicture}
  12745. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  12746. functions.}
  12747. \label{fig:Rlambda-passes}
  12748. \end{figure}
  12749. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  12750. for the compilation of \LangLam{}.
  12751. \clearpage
  12752. \section{Challenge: Optimize Closures}
  12753. \label{sec:optimize-closures}
  12754. In this chapter we compiled lexically-scoped functions into a
  12755. relatively efficient representation: flat closures. However, even this
  12756. representation comes with some overhead. For example, consider the
  12757. following program with a function \code{tail-sum} that does not have
  12758. any free variables and where all the uses of \code{tail-sum} are in
  12759. applications where we know that only \code{tail-sum} is being applied
  12760. (and not any other functions).
  12761. \begin{center}
  12762. \begin{minipage}{0.95\textwidth}
  12763. \begin{lstlisting}
  12764. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  12765. (if (eq? n 0)
  12766. r
  12767. (tail-sum (- n 1) (+ n r))))
  12768. (+ (tail-sum 5 0) 27)
  12769. \end{lstlisting}
  12770. \end{minipage}
  12771. \end{center}
  12772. As described in this chapter, we uniformly apply closure conversion to
  12773. all functions, obtaining the following output for this program.
  12774. \begin{center}
  12775. \begin{minipage}{0.95\textwidth}
  12776. \begin{lstlisting}
  12777. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  12778. (if (eq? n2 0)
  12779. r3
  12780. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  12781. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  12782. (define (main) : Integer
  12783. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  12784. ((vector-ref clos6 0) clos6 5 0)) 27))
  12785. \end{lstlisting}
  12786. \end{minipage}
  12787. \end{center}
  12788. In the previous Chapter, there would be no allocation in the program
  12789. and the calls to \code{tail-sum} would be direct calls. In contrast,
  12790. the above program allocates memory for each \code{closure} and the
  12791. calls to \code{tail-sum} are indirect. These two differences incur
  12792. considerable overhead in a program such as this one, where the
  12793. allocations and indirect calls occur inside a tight loop.
  12794. One might think that this problem is trivial to solve: can't we just
  12795. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  12796. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  12797. e'_n$)} instead of treating it like a call to a closure? We would
  12798. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  12799. %
  12800. However, this problem is not so trivial because a global function may
  12801. ``escape'' and become involved in applications that also involve
  12802. closures. Consider the following example in which the application
  12803. \code{(f 41)} needs to be compiled into a closure application, because
  12804. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  12805. function might also get bound to \code{f}.
  12806. \begin{lstlisting}
  12807. (define (add1 [x : Integer]) : Integer
  12808. (+ x 1))
  12809. (let ([y (read)])
  12810. (let ([f (if (eq? (read) 0)
  12811. add1
  12812. (lambda: ([x : Integer]) : Integer (- x y)))])
  12813. (f 41)))
  12814. \end{lstlisting}
  12815. If a global function name is used in any way other than as the
  12816. operator in a direct call, then we say that the function
  12817. \emph{escapes}. If a global function does not escape, then we do not
  12818. need to perform closure conversion on the function.
  12819. \begin{exercise}\normalfont
  12820. Implement an auxiliary function for detecting which global
  12821. functions escape. Using that function, implement an improved version
  12822. of closure conversion that does not apply closure conversion to
  12823. global functions that do not escape but instead compiles them as
  12824. regular functions. Create several new test cases that check whether
  12825. you properly detect whether global functions escape or not.
  12826. \end{exercise}
  12827. So far we have reduced the overhead of calling global functions, but
  12828. it would also be nice to reduce the overhead of calling a
  12829. \code{lambda} when we can determine at compile time which
  12830. \code{lambda} will be called. We refer to such calls as \emph{known
  12831. calls}. Consider the following example in which a \code{lambda} is
  12832. bound to \code{f} and then applied.
  12833. \begin{lstlisting}
  12834. (let ([y (read)])
  12835. (let ([f (lambda: ([x : Integer]) : Integer
  12836. (+ x y))])
  12837. (f 21)))
  12838. \end{lstlisting}
  12839. Closure conversion compiles \code{(f 21)} into an indirect call:
  12840. \begin{lstlisting}
  12841. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  12842. (let ([y2 (vector-ref fvs6 1)])
  12843. (+ x3 y2)))
  12844. (define (main) : Integer
  12845. (let ([y2 (read)])
  12846. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  12847. ((vector-ref f4 0) f4 21))))
  12848. \end{lstlisting}
  12849. but we can instead compile the application \code{(f 21)} into a direct call
  12850. to \code{lambda5}:
  12851. \begin{lstlisting}
  12852. (define (main) : Integer
  12853. (let ([y2 (read)])
  12854. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  12855. ((fun-ref lambda5) f4 21))))
  12856. \end{lstlisting}
  12857. The problem of determining which lambda will be called from a
  12858. particular application is quite challenging in general and the topic
  12859. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  12860. following exercise we recommend that you compile an application to a
  12861. direct call when the operator is a variable and the variable is
  12862. \code{let}-bound to a closure. This can be accomplished by maintaining
  12863. an environment mapping \code{let}-bound variables to function names.
  12864. Extend the environment whenever you encounter a closure on the
  12865. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  12866. to the name of the global function for the closure. This pass should
  12867. come after closure conversion.
  12868. \begin{exercise}\normalfont
  12869. Implement a compiler pass, named \code{optimize-known-calls}, that
  12870. compiles known calls into direct calls. Verify that your compiler is
  12871. successful in this regard on several example programs.
  12872. \end{exercise}
  12873. These exercises only scratches the surface of optimizing of
  12874. closures. A good next step for the interested reader is to look at the
  12875. work of \citet{Keep:2012ab}.
  12876. \section{Further Reading}
  12877. The notion of lexically scoped anonymous functions predates modern
  12878. computers by about a decade. They were invented by
  12879. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  12880. foundation for logic. Anonymous functions were included in the
  12881. LISP~\citep{McCarthy:1960dz} programming language but were initially
  12882. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  12883. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  12884. compile Scheme programs. However, environments were represented as
  12885. linked lists, so variable lookup was linear in the size of the
  12886. environment. In this chapter we represent environments using flat
  12887. closures, which were invented by
  12888. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  12889. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  12890. closures, variable lookup is constant time but the time to create a
  12891. closure is proportional to the number of its free variables. Flat
  12892. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  12893. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  12894. \fi
  12895. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12896. \chapter{Dynamic Typing}
  12897. \label{ch:Rdyn}
  12898. \index{subject}{dynamic typing}
  12899. \if\edition\racketEd
  12900. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  12901. typed language that is a subset of Racket. This is in contrast to the
  12902. previous chapters, which have studied the compilation of Typed
  12903. Racket. In dynamically typed languages such as \LangDyn{}, a given
  12904. expression may produce a value of a different type each time it is
  12905. executed. Consider the following example with a conditional \code{if}
  12906. expression that may return a Boolean or an integer depending on the
  12907. input to the program.
  12908. % part of dynamic_test_25.rkt
  12909. \begin{lstlisting}
  12910. (not (if (eq? (read) 1) #f 0))
  12911. \end{lstlisting}
  12912. Languages that allow expressions to produce different kinds of values
  12913. are called \emph{polymorphic}, a word composed of the Greek roots
  12914. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  12915. are several kinds of polymorphism in programming languages, such as
  12916. subtype polymorphism and parametric
  12917. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  12918. study in this chapter does not have a special name but it is the kind
  12919. that arises in dynamically typed languages.
  12920. Another characteristic of dynamically typed languages is that
  12921. primitive operations, such as \code{not}, are often defined to operate
  12922. on many different types of values. In fact, in Racket, the \code{not}
  12923. operator produces a result for any kind of value: given \code{\#f} it
  12924. returns \code{\#t} and given anything else it returns \code{\#f}.
  12925. Furthermore, even when primitive operations restrict their inputs to
  12926. values of a certain type, this restriction is enforced at runtime
  12927. instead of during compilation. For example, the following vector
  12928. reference results in a run-time contract violation because the index
  12929. must be in integer, not a Boolean such as \code{\#t}.
  12930. \begin{lstlisting}
  12931. (vector-ref (vector 42) #t)
  12932. \end{lstlisting}
  12933. \begin{figure}[tp]
  12934. \centering
  12935. \fbox{
  12936. \begin{minipage}{0.97\textwidth}
  12937. \[
  12938. \begin{array}{rcl}
  12939. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  12940. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12941. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  12942. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  12943. &\MID& \key{\#t} \MID \key{\#f}
  12944. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  12945. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  12946. \MID \CUNIOP{\key{not}}{\Exp} \\
  12947. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  12948. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  12949. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  12950. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  12951. &\MID& \LP\Exp \; \Exp\ldots\RP
  12952. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  12953. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  12954. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  12955. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  12956. \LangDynM{} &::=& \Def\ldots\; \Exp
  12957. \end{array}
  12958. \]
  12959. \end{minipage}
  12960. }
  12961. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  12962. \label{fig:r7-concrete-syntax}
  12963. \end{figure}
  12964. \begin{figure}[tp]
  12965. \centering
  12966. \fbox{
  12967. \begin{minipage}{0.96\textwidth}
  12968. \small
  12969. \[
  12970. \begin{array}{lcl}
  12971. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  12972. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  12973. &\MID& \BOOL{\itm{bool}}
  12974. \MID \IF{\Exp}{\Exp}{\Exp} \\
  12975. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  12976. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  12977. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  12978. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  12979. \end{array}
  12980. \]
  12981. \end{minipage}
  12982. }
  12983. \caption{The abstract syntax of \LangDyn{}.}
  12984. \label{fig:r7-syntax}
  12985. \end{figure}
  12986. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  12987. defined in Figures~\ref{fig:r7-concrete-syntax} and
  12988. \ref{fig:r7-syntax}.
  12989. %
  12990. There is no type checker for \LangDyn{} because it is not a statically
  12991. typed language (it's dynamically typed!).
  12992. The definitional interpreter for \LangDyn{} is presented in
  12993. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  12994. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  12995. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  12996. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  12997. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  12998. value} that combines an underlying value with a tag that identifies
  12999. what kind of value it is. We define the following struct
  13000. to represented tagged values.
  13001. \begin{lstlisting}
  13002. (struct Tagged (value tag) #:transparent)
  13003. \end{lstlisting}
  13004. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  13005. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  13006. but don't always capture all the information that a type does. For
  13007. example, a vector of type \code{(Vector Any Any)} is tagged with
  13008. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  13009. is tagged with \code{Procedure}.
  13010. Next consider the match case for \code{vector-ref}. The
  13011. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  13012. is used to ensure that the first argument is a vector and the second
  13013. is an integer. If they are not, a \code{trapped-error} is raised.
  13014. Recall from Section~\ref{sec:interp_Lint} that when a definition
  13015. interpreter raises a \code{trapped-error} error, the compiled code
  13016. must also signal an error by exiting with return code \code{255}. A
  13017. \code{trapped-error} is also raised if the index is not less than
  13018. length of the vector.
  13019. \begin{figure}[tbp]
  13020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13021. (define ((interp-Rdyn-exp env) ast)
  13022. (define recur (interp-Rdyn-exp env))
  13023. (match ast
  13024. [(Var x) (lookup x env)]
  13025. [(Int n) (Tagged n 'Integer)]
  13026. [(Bool b) (Tagged b 'Boolean)]
  13027. [(Lambda xs rt body)
  13028. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  13029. [(Prim 'vector es)
  13030. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  13031. [(Prim 'vector-ref (list e1 e2))
  13032. (define vec (recur e1)) (define i (recur e2))
  13033. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13034. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13035. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13036. (vector-ref (Tagged-value vec) (Tagged-value i))]
  13037. [(Prim 'vector-set! (list e1 e2 e3))
  13038. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  13039. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13040. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13041. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13042. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  13043. (Tagged (void) 'Void)]
  13044. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  13045. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  13046. [(Prim 'or (list e1 e2))
  13047. (define v1 (recur e1))
  13048. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  13049. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  13050. [(Prim op (list e1))
  13051. #:when (set-member? type-predicates op)
  13052. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  13053. [(Prim op es)
  13054. (define args (map recur es))
  13055. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  13056. (unless (for/or ([expected-tags (op-tags op)])
  13057. (equal? expected-tags tags))
  13058. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  13059. (tag-value
  13060. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  13061. [(If q t f)
  13062. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  13063. [(Apply f es)
  13064. (define new-f (recur f)) (define args (map recur es))
  13065. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  13066. (match f-val
  13067. [`(function ,xs ,body ,lam-env)
  13068. (unless (eq? (length xs) (length args))
  13069. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  13070. (define new-env (append (map cons xs args) lam-env))
  13071. ((interp-Rdyn-exp new-env) body)]
  13072. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  13073. \end{lstlisting}
  13074. \caption{Interpreter for the \LangDyn{} language.}
  13075. \label{fig:interp-Rdyn}
  13076. \end{figure}
  13077. \begin{figure}[tbp]
  13078. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13079. (define (interp-op op)
  13080. (match op
  13081. ['+ fx+]
  13082. ['- fx-]
  13083. ['read read-fixnum]
  13084. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  13085. ['< (lambda (v1 v2)
  13086. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  13087. ['<= (lambda (v1 v2)
  13088. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  13089. ['> (lambda (v1 v2)
  13090. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  13091. ['>= (lambda (v1 v2)
  13092. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  13093. ['boolean? boolean?]
  13094. ['integer? fixnum?]
  13095. ['void? void?]
  13096. ['vector? vector?]
  13097. ['vector-length vector-length]
  13098. ['procedure? (match-lambda
  13099. [`(functions ,xs ,body ,env) #t] [else #f])]
  13100. [else (error 'interp-op "unknown operator" op)]))
  13101. (define (op-tags op)
  13102. (match op
  13103. ['+ '((Integer Integer))]
  13104. ['- '((Integer Integer) (Integer))]
  13105. ['read '(())]
  13106. ['not '((Boolean))]
  13107. ['< '((Integer Integer))]
  13108. ['<= '((Integer Integer))]
  13109. ['> '((Integer Integer))]
  13110. ['>= '((Integer Integer))]
  13111. ['vector-length '((Vector))]))
  13112. (define type-predicates
  13113. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  13114. (define (tag-value v)
  13115. (cond [(boolean? v) (Tagged v 'Boolean)]
  13116. [(fixnum? v) (Tagged v 'Integer)]
  13117. [(procedure? v) (Tagged v 'Procedure)]
  13118. [(vector? v) (Tagged v 'Vector)]
  13119. [(void? v) (Tagged v 'Void)]
  13120. [else (error 'tag-value "unidentified value ~a" v)]))
  13121. (define (check-tag val expected ast)
  13122. (define tag (Tagged-tag val))
  13123. (unless (eq? tag expected)
  13124. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  13125. \end{lstlisting}
  13126. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  13127. \label{fig:interp-Rdyn-aux}
  13128. \end{figure}
  13129. \clearpage
  13130. \section{Representation of Tagged Values}
  13131. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  13132. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  13133. values at the bit level. Because almost every operation in \LangDyn{}
  13134. involves manipulating tagged values, the representation must be
  13135. efficient. Recall that all of our values are 64 bits. We shall steal
  13136. the 3 right-most bits to encode the tag. We use $001$ to identify
  13137. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  13138. and $101$ for the void value. We define the following auxiliary
  13139. function for mapping types to tag codes.
  13140. \begin{align*}
  13141. \itm{tagof}(\key{Integer}) &= 001 \\
  13142. \itm{tagof}(\key{Boolean}) &= 100 \\
  13143. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  13144. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  13145. \itm{tagof}(\key{Void}) &= 101
  13146. \end{align*}
  13147. This stealing of 3 bits comes at some price: our integers are reduced
  13148. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  13149. affect vectors and procedures because those values are addresses, and
  13150. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  13151. they are always $000$. Thus, we do not lose information by overwriting
  13152. the rightmost 3 bits with the tag and we can simply zero-out the tag
  13153. to recover the original address.
  13154. To make tagged values into first-class entities, we can give them a
  13155. type, called \code{Any}, and define operations such as \code{Inject}
  13156. and \code{Project} for creating and using them, yielding the \LangAny{}
  13157. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  13158. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  13159. in greater detail.
  13160. \section{The \LangAny{} Language}
  13161. \label{sec:Rany-lang}
  13162. \begin{figure}[tp]
  13163. \centering
  13164. \fbox{
  13165. \begin{minipage}{0.96\textwidth}
  13166. \small
  13167. \[
  13168. \begin{array}{lcl}
  13169. \Type &::= & \ldots \MID \key{Any} \\
  13170. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  13171. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  13172. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  13173. \MID \code{procedure?} \MID \code{void?} \\
  13174. \Exp &::=& \ldots
  13175. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  13176. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  13177. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  13178. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13179. \end{array}
  13180. \]
  13181. \end{minipage}
  13182. }
  13183. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  13184. \label{fig:Rany-syntax}
  13185. \end{figure}
  13186. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  13187. (The concrete syntax of \LangAny{} is in the Appendix,
  13188. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  13189. converts the value produced by expression $e$ of type $T$ into a
  13190. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  13191. produced by expression $e$ into a value of type $T$ or else halts the
  13192. program if the type tag is not equivalent to $T$.
  13193. %
  13194. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  13195. restricted to a flat type $\FType$, which simplifies the
  13196. implementation and corresponds with what is needed for compiling \LangDyn{}.
  13197. The \code{any-vector} operators adapt the vector operations so that
  13198. they can be applied to a value of type \code{Any}. They also
  13199. generalize the vector operations in that the index is not restricted
  13200. to be a literal integer in the grammar but is allowed to be any
  13201. expression.
  13202. The type predicates such as \key{boolean?} expect their argument to
  13203. produce a tagged value; they return \key{\#t} if the tag corresponds
  13204. to the predicate and they return \key{\#f} otherwise.
  13205. The type checker for \LangAny{} is shown in
  13206. Figures~\ref{fig:type-check-Rany-part-1} and
  13207. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  13208. Figure~\ref{fig:type-check-Rany-aux}.
  13209. %
  13210. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  13211. auxiliary functions \code{apply-inject} and \code{apply-project} are
  13212. in Figure~\ref{fig:apply-project}.
  13213. \begin{figure}[btp]
  13214. \begin{lstlisting}[basicstyle=\ttfamily\small]
  13215. (define type-check-Rany_class
  13216. (class type-check-Rlambda_class
  13217. (super-new)
  13218. (inherit check-type-equal?)
  13219. (define/override (type-check-exp env)
  13220. (lambda (e)
  13221. (define recur (type-check-exp env))
  13222. (match e
  13223. [(Inject e1 ty)
  13224. (unless (flat-ty? ty)
  13225. (error 'type-check "may only inject from flat type, not ~a" ty))
  13226. (define-values (new-e1 e-ty) (recur e1))
  13227. (check-type-equal? e-ty ty e)
  13228. (values (Inject new-e1 ty) 'Any)]
  13229. [(Project e1 ty)
  13230. (unless (flat-ty? ty)
  13231. (error 'type-check "may only project to flat type, not ~a" ty))
  13232. (define-values (new-e1 e-ty) (recur e1))
  13233. (check-type-equal? e-ty 'Any e)
  13234. (values (Project new-e1 ty) ty)]
  13235. [(Prim 'any-vector-length (list e1))
  13236. (define-values (e1^ t1) (recur e1))
  13237. (check-type-equal? t1 'Any e)
  13238. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  13239. [(Prim 'any-vector-ref (list e1 e2))
  13240. (define-values (e1^ t1) (recur e1))
  13241. (define-values (e2^ t2) (recur e2))
  13242. (check-type-equal? t1 'Any e)
  13243. (check-type-equal? t2 'Integer e)
  13244. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  13245. [(Prim 'any-vector-set! (list e1 e2 e3))
  13246. (define-values (e1^ t1) (recur e1))
  13247. (define-values (e2^ t2) (recur e2))
  13248. (define-values (e3^ t3) (recur e3))
  13249. (check-type-equal? t1 'Any e)
  13250. (check-type-equal? t2 'Integer e)
  13251. (check-type-equal? t3 'Any e)
  13252. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  13253. \end{lstlisting}
  13254. \caption{Type checker for the \LangAny{} language, part 1.}
  13255. \label{fig:type-check-Rany-part-1}
  13256. \end{figure}
  13257. \begin{figure}[btp]
  13258. \begin{lstlisting}[basicstyle=\ttfamily\small]
  13259. [(ValueOf e ty)
  13260. (define-values (new-e e-ty) (recur e))
  13261. (values (ValueOf new-e ty) ty)]
  13262. [(Prim pred (list e1))
  13263. #:when (set-member? (type-predicates) pred)
  13264. (define-values (new-e1 e-ty) (recur e1))
  13265. (check-type-equal? e-ty 'Any e)
  13266. (values (Prim pred (list new-e1)) 'Boolean)]
  13267. [(If cnd thn els)
  13268. (define-values (cnd^ Tc) (recur cnd))
  13269. (define-values (thn^ Tt) (recur thn))
  13270. (define-values (els^ Te) (recur els))
  13271. (check-type-equal? Tc 'Boolean cnd)
  13272. (check-type-equal? Tt Te e)
  13273. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  13274. [(Exit) (values (Exit) '_)]
  13275. [(Prim 'eq? (list arg1 arg2))
  13276. (define-values (e1 t1) (recur arg1))
  13277. (define-values (e2 t2) (recur arg2))
  13278. (match* (t1 t2)
  13279. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  13280. [(other wise) (check-type-equal? t1 t2 e)])
  13281. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  13282. [else ((super type-check-exp env) e)])))
  13283. ))
  13284. \end{lstlisting}
  13285. \caption{Type checker for the \LangAny{} language, part 2.}
  13286. \label{fig:type-check-Rany-part-2}
  13287. \end{figure}
  13288. \begin{figure}[tbp]
  13289. \begin{lstlisting}
  13290. (define/override (operator-types)
  13291. (append
  13292. '((integer? . ((Any) . Boolean))
  13293. (vector? . ((Any) . Boolean))
  13294. (procedure? . ((Any) . Boolean))
  13295. (void? . ((Any) . Boolean))
  13296. (tag-of-any . ((Any) . Integer))
  13297. (make-any . ((_ Integer) . Any))
  13298. )
  13299. (super operator-types)))
  13300. (define/public (type-predicates)
  13301. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  13302. (define/public (combine-types t1 t2)
  13303. (match (list t1 t2)
  13304. [(list '_ t2) t2]
  13305. [(list t1 '_) t1]
  13306. [(list `(Vector ,ts1 ...)
  13307. `(Vector ,ts2 ...))
  13308. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  13309. (combine-types t1 t2)))]
  13310. [(list `(,ts1 ... -> ,rt1)
  13311. `(,ts2 ... -> ,rt2))
  13312. `(,@(for/list ([t1 ts1] [t2 ts2])
  13313. (combine-types t1 t2))
  13314. -> ,(combine-types rt1 rt2))]
  13315. [else t1]))
  13316. (define/public (flat-ty? ty)
  13317. (match ty
  13318. [(or `Integer `Boolean '_ `Void) #t]
  13319. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  13320. [`(,ts ... -> ,rt)
  13321. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  13322. [else #f]))
  13323. \end{lstlisting}
  13324. \caption{Auxiliary methods for type checking \LangAny{}.}
  13325. \label{fig:type-check-Rany-aux}
  13326. \end{figure}
  13327. \begin{figure}[btp]
  13328. \begin{lstlisting}
  13329. (define interp-Rany_class
  13330. (class interp-Rlambda_class
  13331. (super-new)
  13332. (define/override (interp-op op)
  13333. (match op
  13334. ['boolean? (match-lambda
  13335. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  13336. [else #f])]
  13337. ['integer? (match-lambda
  13338. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  13339. [else #f])]
  13340. ['vector? (match-lambda
  13341. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  13342. [else #f])]
  13343. ['procedure? (match-lambda
  13344. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  13345. [else #f])]
  13346. ['eq? (match-lambda*
  13347. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  13348. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  13349. [ls (apply (super interp-op op) ls)])]
  13350. ['any-vector-ref (lambda (v i)
  13351. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  13352. ['any-vector-set! (lambda (v i a)
  13353. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  13354. ['any-vector-length (lambda (v)
  13355. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  13356. [else (super interp-op op)]))
  13357. (define/override ((interp-exp env) e)
  13358. (define recur (interp-exp env))
  13359. (match e
  13360. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  13361. [(Project e ty2) (apply-project (recur e) ty2)]
  13362. [else ((super interp-exp env) e)]))
  13363. ))
  13364. (define (interp-Rany p)
  13365. (send (new interp-Rany_class) interp-program p))
  13366. \end{lstlisting}
  13367. \caption{Interpreter for \LangAny{}.}
  13368. \label{fig:interp-Rany}
  13369. \end{figure}
  13370. \begin{figure}[tbp]
  13371. \begin{lstlisting}
  13372. (define/public (apply-inject v tg) (Tagged v tg))
  13373. (define/public (apply-project v ty2)
  13374. (define tag2 (any-tag ty2))
  13375. (match v
  13376. [(Tagged v1 tag1)
  13377. (cond
  13378. [(eq? tag1 tag2)
  13379. (match ty2
  13380. [`(Vector ,ts ...)
  13381. (define l1 ((interp-op 'vector-length) v1))
  13382. (cond
  13383. [(eq? l1 (length ts)) v1]
  13384. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  13385. l1 (length ts))])]
  13386. [`(,ts ... -> ,rt)
  13387. (match v1
  13388. [`(function ,xs ,body ,env)
  13389. (cond [(eq? (length xs) (length ts)) v1]
  13390. [else
  13391. (error 'apply-project "arity mismatch ~a != ~a"
  13392. (length xs) (length ts))])]
  13393. [else (error 'apply-project "expected function not ~a" v1)])]
  13394. [else v1])]
  13395. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  13396. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  13397. \end{lstlisting}
  13398. \caption{Auxiliary functions for injection and projection.}
  13399. \label{fig:apply-project}
  13400. \end{figure}
  13401. \clearpage
  13402. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  13403. \label{sec:compile-r7}
  13404. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  13405. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  13406. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  13407. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  13408. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  13409. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  13410. the Boolean \code{\#t}, which must be injected to produce an
  13411. expression of type \key{Any}.
  13412. %
  13413. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  13414. addition, is representative of compilation for many primitive
  13415. operations: the arguments have type \key{Any} and must be projected to
  13416. \key{Integer} before the addition can be performed.
  13417. The compilation of \key{lambda} (third row of
  13418. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  13419. produce type annotations: we simply use \key{Any}.
  13420. %
  13421. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  13422. has to account for some differences in behavior between \LangDyn{} and
  13423. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  13424. kind of values can be used in various places. For example, the
  13425. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  13426. the arguments need not be of the same type (in that case the
  13427. result is \code{\#f}).
  13428. \begin{figure}[btp]
  13429. \centering
  13430. \begin{tabular}{|lll|} \hline
  13431. \begin{minipage}{0.27\textwidth}
  13432. \begin{lstlisting}
  13433. #t
  13434. \end{lstlisting}
  13435. \end{minipage}
  13436. &
  13437. $\Rightarrow$
  13438. &
  13439. \begin{minipage}{0.65\textwidth}
  13440. \begin{lstlisting}
  13441. (inject #t Boolean)
  13442. \end{lstlisting}
  13443. \end{minipage}
  13444. \\[2ex]\hline
  13445. \begin{minipage}{0.27\textwidth}
  13446. \begin{lstlisting}
  13447. (+ |$e_1$| |$e_2$|)
  13448. \end{lstlisting}
  13449. \end{minipage}
  13450. &
  13451. $\Rightarrow$
  13452. &
  13453. \begin{minipage}{0.65\textwidth}
  13454. \begin{lstlisting}
  13455. (inject
  13456. (+ (project |$e'_1$| Integer)
  13457. (project |$e'_2$| Integer))
  13458. Integer)
  13459. \end{lstlisting}
  13460. \end{minipage}
  13461. \\[2ex]\hline
  13462. \begin{minipage}{0.27\textwidth}
  13463. \begin{lstlisting}
  13464. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  13465. \end{lstlisting}
  13466. \end{minipage}
  13467. &
  13468. $\Rightarrow$
  13469. &
  13470. \begin{minipage}{0.65\textwidth}
  13471. \begin{lstlisting}
  13472. (inject
  13473. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  13474. (Any|$\ldots$|Any -> Any))
  13475. \end{lstlisting}
  13476. \end{minipage}
  13477. \\[2ex]\hline
  13478. \begin{minipage}{0.27\textwidth}
  13479. \begin{lstlisting}
  13480. (|$e_0$| |$e_1 \ldots e_n$|)
  13481. \end{lstlisting}
  13482. \end{minipage}
  13483. &
  13484. $\Rightarrow$
  13485. &
  13486. \begin{minipage}{0.65\textwidth}
  13487. \begin{lstlisting}
  13488. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  13489. \end{lstlisting}
  13490. \end{minipage}
  13491. \\[2ex]\hline
  13492. \begin{minipage}{0.27\textwidth}
  13493. \begin{lstlisting}
  13494. (vector-ref |$e_1$| |$e_2$|)
  13495. \end{lstlisting}
  13496. \end{minipage}
  13497. &
  13498. $\Rightarrow$
  13499. &
  13500. \begin{minipage}{0.65\textwidth}
  13501. \begin{lstlisting}
  13502. (any-vector-ref |$e_1'$| |$e_2'$|)
  13503. \end{lstlisting}
  13504. \end{minipage}
  13505. \\[2ex]\hline
  13506. \begin{minipage}{0.27\textwidth}
  13507. \begin{lstlisting}
  13508. (if |$e_1$| |$e_2$| |$e_3$|)
  13509. \end{lstlisting}
  13510. \end{minipage}
  13511. &
  13512. $\Rightarrow$
  13513. &
  13514. \begin{minipage}{0.65\textwidth}
  13515. \begin{lstlisting}
  13516. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  13517. \end{lstlisting}
  13518. \end{minipage}
  13519. \\[2ex]\hline
  13520. \begin{minipage}{0.27\textwidth}
  13521. \begin{lstlisting}
  13522. (eq? |$e_1$| |$e_2$|)
  13523. \end{lstlisting}
  13524. \end{minipage}
  13525. &
  13526. $\Rightarrow$
  13527. &
  13528. \begin{minipage}{0.65\textwidth}
  13529. \begin{lstlisting}
  13530. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  13531. \end{lstlisting}
  13532. \end{minipage}
  13533. \\[2ex]\hline
  13534. \begin{minipage}{0.27\textwidth}
  13535. \begin{lstlisting}
  13536. (not |$e_1$|)
  13537. \end{lstlisting}
  13538. \end{minipage}
  13539. &
  13540. $\Rightarrow$
  13541. &
  13542. \begin{minipage}{0.65\textwidth}
  13543. \begin{lstlisting}
  13544. (if (eq? |$e'_1$| (inject #f Boolean))
  13545. (inject #t Boolean) (inject #f Boolean))
  13546. \end{lstlisting}
  13547. \end{minipage}
  13548. \\[2ex]\hline
  13549. \end{tabular}
  13550. \caption{Cast Insertion}
  13551. \label{fig:compile-r7-Rany}
  13552. \end{figure}
  13553. \section{Reveal Casts}
  13554. \label{sec:reveal-casts-Rany}
  13555. % TODO: define R'_6
  13556. In the \code{reveal-casts} pass we recommend compiling \code{project}
  13557. into an \code{if} expression that checks whether the value's tag
  13558. matches the target type; if it does, the value is converted to a value
  13559. of the target type by removing the tag; if it does not, the program
  13560. exits. To perform these actions we need a new primitive operation,
  13561. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  13562. The \code{tag-of-any} operation retrieves the type tag from a tagged
  13563. value of type \code{Any}. The \code{ValueOf} form retrieves the
  13564. underlying value from a tagged value. The \code{ValueOf} form
  13565. includes the type for the underlying value which is used by the type
  13566. checker. Finally, the \code{Exit} form ends the execution of the
  13567. program.
  13568. If the target type of the projection is \code{Boolean} or
  13569. \code{Integer}, then \code{Project} can be translated as follows.
  13570. \begin{center}
  13571. \begin{minipage}{1.0\textwidth}
  13572. \begin{lstlisting}
  13573. (Project |$e$| |$\FType$|)
  13574. |$\Rightarrow$|
  13575. (Let |$\itm{tmp}$| |$e'$|
  13576. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  13577. (Int |$\itm{tagof}(\FType)$|)))
  13578. (ValueOf |$\itm{tmp}$| |$\FType$|)
  13579. (Exit)))
  13580. \end{lstlisting}
  13581. \end{minipage}
  13582. \end{center}
  13583. If the target type of the projection is a vector or function type,
  13584. then there is a bit more work to do. For vectors, check that the
  13585. length of the vector type matches the length of the vector (using the
  13586. \code{vector-length} primitive). For functions, check that the number
  13587. of parameters in the function type matches the function's arity (using
  13588. \code{procedure-arity}).
  13589. Regarding \code{inject}, we recommend compiling it to a slightly
  13590. lower-level primitive operation named \code{make-any}. This operation
  13591. takes a tag instead of a type.
  13592. \begin{center}
  13593. \begin{minipage}{1.0\textwidth}
  13594. \begin{lstlisting}
  13595. (Inject |$e$| |$\FType$|)
  13596. |$\Rightarrow$|
  13597. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  13598. \end{lstlisting}
  13599. \end{minipage}
  13600. \end{center}
  13601. The type predicates (\code{boolean?}, etc.) can be translated into
  13602. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  13603. translation of \code{Project}.
  13604. The \code{any-vector-ref} and \code{any-vector-set!} operations
  13605. combine the projection action with the vector operation. Also, the
  13606. read and write operations allow arbitrary expressions for the index so
  13607. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  13608. cannot guarantee that the index is within bounds. Thus, we insert code
  13609. to perform bounds checking at runtime. The translation for
  13610. \code{any-vector-ref} is as follows and the other two operations are
  13611. translated in a similar way.
  13612. \begin{lstlisting}
  13613. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  13614. |$\Rightarrow$|
  13615. (Let |$v$| |$e'_1$|
  13616. (Let |$i$| |$e'_2$|
  13617. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  13618. (If (Prim '< (list (Var |$i$|)
  13619. (Prim 'any-vector-length (list (Var |$v$|)))))
  13620. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  13621. (Exit))))
  13622. \end{lstlisting}
  13623. \section{Remove Complex Operands}
  13624. \label{sec:rco-Rany}
  13625. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  13626. The subexpression of \code{ValueOf} must be atomic.
  13627. \section{Explicate Control and \LangCAny{}}
  13628. \label{sec:explicate-Rany}
  13629. The output of \code{explicate\_control} is the \LangCAny{} language whose
  13630. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  13631. form that we added to \LangAny{} remains an expression and the \code{Exit}
  13632. expression becomes a $\Tail$. Also, note that the index argument of
  13633. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  13634. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  13635. \begin{figure}[tp]
  13636. \fbox{
  13637. \begin{minipage}{0.96\textwidth}
  13638. \small
  13639. \[
  13640. \begin{array}{lcl}
  13641. \Exp &::= & \ldots
  13642. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  13643. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  13644. &\MID& \VALUEOF{\Exp}{\FType} \\
  13645. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  13646. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  13647. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  13648. \MID \GOTO{\itm{label}} } \\
  13649. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  13650. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  13651. \MID \LP\key{Exit}\RP \\
  13652. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  13653. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  13654. \end{array}
  13655. \]
  13656. \end{minipage}
  13657. }
  13658. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  13659. \label{fig:c5-syntax}
  13660. \end{figure}
  13661. \section{Select Instructions}
  13662. \label{sec:select-Rany}
  13663. In the \code{select\_instructions} pass we translate the primitive
  13664. operations on the \code{Any} type to x86 instructions that involve
  13665. manipulating the 3 tag bits of the tagged value.
  13666. \paragraph{Make-any}
  13667. We recommend compiling the \key{make-any} primitive as follows if the
  13668. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  13669. shifts the destination to the left by the number of bits specified its
  13670. source argument (in this case $3$, the length of the tag) and it
  13671. preserves the sign of the integer. We use the \key{orq} instruction to
  13672. combine the tag and the value to form the tagged value. \\
  13673. \begin{lstlisting}
  13674. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  13675. |$\Rightarrow$|
  13676. movq |$e'$|, |\itm{lhs'}|
  13677. salq $3, |\itm{lhs'}|
  13678. orq $|$\itm{tag}$|, |\itm{lhs'}|
  13679. \end{lstlisting}
  13680. The instruction selection for vectors and procedures is different
  13681. because their is no need to shift them to the left. The rightmost 3
  13682. bits are already zeros as described at the beginning of this
  13683. chapter. So we just combine the value and the tag using \key{orq}. \\
  13684. \begin{lstlisting}
  13685. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  13686. |$\Rightarrow$|
  13687. movq |$e'$|, |\itm{lhs'}|
  13688. orq $|$\itm{tag}$|, |\itm{lhs'}|
  13689. \end{lstlisting}
  13690. \paragraph{Tag-of-any}
  13691. Recall that the \code{tag-of-any} operation extracts the type tag from
  13692. a value of type \code{Any}. The type tag is the bottom three bits, so
  13693. we obtain the tag by taking the bitwise-and of the value with $111$
  13694. ($7$ in decimal).
  13695. \begin{lstlisting}
  13696. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  13697. |$\Rightarrow$|
  13698. movq |$e'$|, |\itm{lhs'}|
  13699. andq $7, |\itm{lhs'}|
  13700. \end{lstlisting}
  13701. \paragraph{ValueOf}
  13702. Like \key{make-any}, the instructions for \key{ValueOf} are different
  13703. depending on whether the type $T$ is a pointer (vector or procedure)
  13704. or not (Integer or Boolean). The following shows the instruction
  13705. selection for Integer and Boolean. We produce an untagged value by
  13706. shifting it to the right by 3 bits.
  13707. \begin{lstlisting}
  13708. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  13709. |$\Rightarrow$|
  13710. movq |$e'$|, |\itm{lhs'}|
  13711. sarq $3, |\itm{lhs'}|
  13712. \end{lstlisting}
  13713. %
  13714. In the case for vectors and procedures, there is no need to
  13715. shift. Instead we just need to zero-out the rightmost 3 bits. We
  13716. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  13717. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  13718. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  13719. then apply \code{andq} with the tagged value to get the desired
  13720. result. \\
  13721. \begin{lstlisting}
  13722. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  13723. |$\Rightarrow$|
  13724. movq $|$-8$|, |\itm{lhs'}|
  13725. andq |$e'$|, |\itm{lhs'}|
  13726. \end{lstlisting}
  13727. %% \paragraph{Type Predicates} We leave it to the reader to
  13728. %% devise a sequence of instructions to implement the type predicates
  13729. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  13730. \paragraph{Any-vector-length}
  13731. \begin{lstlisting}
  13732. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  13733. |$\Longrightarrow$|
  13734. movq |$\neg 111$|, %r11
  13735. andq |$a_1'$|, %r11
  13736. movq 0(%r11), %r11
  13737. andq $126, %r11
  13738. sarq $1, %r11
  13739. movq %r11, |$\itm{lhs'}$|
  13740. \end{lstlisting}
  13741. \paragraph{Any-vector-ref}
  13742. The index may be an arbitrary atom so instead of computing the offset
  13743. at compile time, instructions need to be generated to compute the
  13744. offset at runtime as follows. Note the use of the new instruction
  13745. \code{imulq}.
  13746. \begin{center}
  13747. \begin{minipage}{0.96\textwidth}
  13748. \begin{lstlisting}
  13749. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  13750. |$\Longrightarrow$|
  13751. movq |$\neg 111$|, %r11
  13752. andq |$a_1'$|, %r11
  13753. movq |$a_2'$|, %rax
  13754. addq $1, %rax
  13755. imulq $8, %rax
  13756. addq %rax, %r11
  13757. movq 0(%r11) |$\itm{lhs'}$|
  13758. \end{lstlisting}
  13759. \end{minipage}
  13760. \end{center}
  13761. \paragraph{Any-vector-set!}
  13762. The code generation for \code{any-vector-set!} is similar to the other
  13763. \code{any-vector} operations.
  13764. \section{Register Allocation for \LangAny{}}
  13765. \label{sec:register-allocation-Rany}
  13766. \index{subject}{register allocation}
  13767. There is an interesting interaction between tagged values and garbage
  13768. collection that has an impact on register allocation. A variable of
  13769. type \code{Any} might refer to a vector and therefore it might be a
  13770. root that needs to be inspected and copied during garbage
  13771. collection. Thus, we need to treat variables of type \code{Any} in a
  13772. similar way to variables of type \code{Vector} for purposes of
  13773. register allocation. In particular,
  13774. \begin{itemize}
  13775. \item If a variable of type \code{Any} is live during a function call,
  13776. then it must be spilled. This can be accomplished by changing
  13777. \code{build\_interference} to mark all variables of type \code{Any}
  13778. that are live after a \code{callq} as interfering with all the
  13779. registers.
  13780. \item If a variable of type \code{Any} is spilled, it must be spilled
  13781. to the root stack instead of the normal procedure call stack.
  13782. \end{itemize}
  13783. Another concern regarding the root stack is that the garbage collector
  13784. needs to differentiate between (1) plain old pointers to tuples, (2) a
  13785. tagged value that points to a tuple, and (3) a tagged value that is
  13786. not a tuple. We enable this differentiation by choosing not to use the
  13787. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  13788. reserved for identifying plain old pointers to tuples. That way, if
  13789. one of the first three bits is set, then we have a tagged value and
  13790. inspecting the tag can differentiation between vectors ($010$) and the
  13791. other kinds of values.
  13792. \begin{exercise}\normalfont
  13793. Expand your compiler to handle \LangAny{} as discussed in the last few
  13794. sections. Create 5 new programs that use the \code{Any} type and the
  13795. new operations (\code{inject}, \code{project}, \code{boolean?},
  13796. etc.). Test your compiler on these new programs and all of your
  13797. previously created test programs.
  13798. \end{exercise}
  13799. \begin{exercise}\normalfont
  13800. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  13801. Create tests for \LangDyn{} by adapting ten of your previous test programs
  13802. by removing type annotations. Add 5 more tests programs that
  13803. specifically rely on the language being dynamically typed. That is,
  13804. they should not be legal programs in a statically typed language, but
  13805. nevertheless, they should be valid \LangDyn{} programs that run to
  13806. completion without error.
  13807. \end{exercise}
  13808. \begin{figure}[p]
  13809. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13810. \node (Rfun) at (0,4) {\large \LangDyn{}};
  13811. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  13812. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  13813. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  13814. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  13815. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  13816. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  13817. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  13818. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  13819. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  13820. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  13821. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  13822. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13823. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13824. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13825. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13826. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13827. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13828. \path[->,bend left=15] (Rfun) edge [above] node
  13829. {\ttfamily\footnotesize shrink} (Rfun-2);
  13830. \path[->,bend left=15] (Rfun-2) edge [above] node
  13831. {\ttfamily\footnotesize uniquify} (Rfun-3);
  13832. \path[->,bend left=15] (Rfun-3) edge [above] node
  13833. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  13834. \path[->,bend right=15] (Rfun-4) edge [left] node
  13835. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  13836. \path[->,bend left=15] (Rfun-5) edge [above] node
  13837. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  13838. \path[->,bend left=15] (Rfun-6) edge [left] node
  13839. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  13840. \path[->,bend left=15] (Rfun-7) edge [below] node
  13841. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  13842. \path[->,bend right=15] (F1-2) edge [above] node
  13843. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  13844. \path[->,bend right=15] (F1-3) edge [above] node
  13845. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13846. \path[->,bend right=15] (F1-4) edge [above] node
  13847. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13848. \path[->,bend right=15] (F1-5) edge [right] node
  13849. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13850. \path[->,bend left=15] (C3-2) edge [left] node
  13851. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13852. \path[->,bend right=15] (x86-2) edge [left] node
  13853. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13854. \path[->,bend right=15] (x86-2-1) edge [below] node
  13855. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13856. \path[->,bend right=15] (x86-2-2) edge [left] node
  13857. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13858. \path[->,bend left=15] (x86-3) edge [above] node
  13859. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13860. \path[->,bend left=15] (x86-4) edge [right] node
  13861. {\ttfamily\footnotesize print\_x86} (x86-5);
  13862. \end{tikzpicture}
  13863. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  13864. \label{fig:Rdyn-passes}
  13865. \end{figure}
  13866. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  13867. for the compilation of \LangDyn{}.
  13868. % Further Reading
  13869. \fi % racketEd
  13870. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13871. \chapter{Objects}
  13872. \label{ch:Robject}
  13873. \index{subject}{objects}
  13874. \index{subject}{classes}
  13875. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13876. \chapter{Gradual Typing}
  13877. \label{ch:Rgrad}
  13878. \index{subject}{gradual typing}
  13879. \if\edition\racketEd
  13880. This chapter studies a language, \LangGrad{}, in which the programmer
  13881. can choose between static and dynamic type checking in different parts
  13882. of a program, thereby mixing the statically typed \LangLoop{} language
  13883. with the dynamically typed \LangDyn{}. There are several approaches to
  13884. mixing static and dynamic typing, including multi-language
  13885. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  13886. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  13887. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  13888. programmer controls the amount of static versus dynamic checking by
  13889. adding or removing type annotations on parameters and
  13890. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  13891. %
  13892. The concrete syntax of \LangGrad{} is defined in
  13893. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  13894. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  13895. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  13896. non-terminals that make type annotations optional. The return types
  13897. are not optional in the abstract syntax; the parser fills in
  13898. \code{Any} when the return type is not specified in the concrete
  13899. syntax.
  13900. \begin{figure}[tp]
  13901. \centering
  13902. \fbox{
  13903. \begin{minipage}{0.96\textwidth}
  13904. \small
  13905. \[
  13906. \begin{array}{lcl}
  13907. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  13908. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  13909. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  13910. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  13911. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  13912. &\MID& \gray{\key{\#t} \MID \key{\#f}
  13913. \MID (\key{and}\;\Exp\;\Exp)
  13914. \MID (\key{or}\;\Exp\;\Exp)
  13915. \MID (\key{not}\;\Exp) } \\
  13916. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  13917. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  13918. (\key{vector-ref}\;\Exp\;\Int)} \\
  13919. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  13920. \MID (\Exp \; \Exp\ldots) } \\
  13921. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  13922. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  13923. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  13924. \MID \CBEGIN{\Exp\ldots}{\Exp}
  13925. \MID \CWHILE{\Exp}{\Exp} } \\
  13926. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  13927. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  13928. \end{array}
  13929. \]
  13930. \end{minipage}
  13931. }
  13932. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  13933. \label{fig:Rgrad-concrete-syntax}
  13934. \end{figure}
  13935. \begin{figure}[tp]
  13936. \centering
  13937. \fbox{
  13938. \begin{minipage}{0.96\textwidth}
  13939. \small
  13940. \[
  13941. \begin{array}{lcl}
  13942. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  13943. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  13944. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  13945. &\MID& \gray{ \BOOL{\itm{bool}}
  13946. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  13947. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  13948. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  13949. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  13950. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  13951. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  13952. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  13953. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13954. \end{array}
  13955. \]
  13956. \end{minipage}
  13957. }
  13958. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  13959. \label{fig:Rgrad-syntax}
  13960. \end{figure}
  13961. Both the type checker and the interpreter for \LangGrad{} require some
  13962. interesting changes to enable gradual typing, which we discuss in the
  13963. next two sections in the context of the \code{map-vec} example from
  13964. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  13965. revised the \code{map-vec} example, omitting the type annotations from
  13966. the \code{add1} function.
  13967. \begin{figure}[btp]
  13968. % gradual_test_9.rkt
  13969. \begin{lstlisting}
  13970. (define (map-vec [f : (Integer -> Integer)]
  13971. [v : (Vector Integer Integer)])
  13972. : (Vector Integer Integer)
  13973. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13974. (define (add1 x) (+ x 1))
  13975. (vector-ref (map-vec add1 (vector 0 41)) 1)
  13976. \end{lstlisting}
  13977. \caption{A partially-typed version of the \code{map-vec} example.}
  13978. \label{fig:gradual-map-vec}
  13979. \end{figure}
  13980. \section{Type Checking \LangGrad{} and \LangCast{}}
  13981. \label{sec:gradual-type-check}
  13982. The type checker for \LangGrad{} uses the \code{Any} type for missing
  13983. parameter and return types. For example, the \code{x} parameter of
  13984. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  13985. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  13986. consider the \code{+} operator inside \code{add1}. It expects both
  13987. arguments to have type \code{Integer}, but its first argument \code{x}
  13988. has type \code{Any}. In a gradually typed language, such differences
  13989. are allowed so long as the types are \emph{consistent}, that is, they
  13990. are equal except in places where there is an \code{Any} type. The type
  13991. \code{Any} is consistent with every other type.
  13992. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  13993. \begin{figure}[tbp]
  13994. \begin{lstlisting}
  13995. (define/public (consistent? t1 t2)
  13996. (match* (t1 t2)
  13997. [('Integer 'Integer) #t]
  13998. [('Boolean 'Boolean) #t]
  13999. [('Void 'Void) #t]
  14000. [('Any t2) #t]
  14001. [(t1 'Any) #t]
  14002. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14003. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  14004. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14005. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  14006. (consistent? rt1 rt2))]
  14007. [(other wise) #f]))
  14008. \end{lstlisting}
  14009. \caption{The consistency predicate on types.}
  14010. \label{fig:consistent}
  14011. \end{figure}
  14012. Returning to the \code{map-vec} example of
  14013. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  14014. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  14015. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  14016. because the two types are consistent. In particular, \code{->} is
  14017. equal to \code{->} and because \code{Any} is consistent with
  14018. \code{Integer}.
  14019. Next consider a program with an error, such as applying the
  14020. \code{map-vec} to a function that sometimes returns a Boolean, as
  14021. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  14022. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  14023. consistent with the type of parameter \code{f} of \code{map-vec}, that
  14024. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  14025. Integer)}. One might say that a gradual type checker is optimistic
  14026. in that it accepts programs that might execute without a runtime type
  14027. error.
  14028. %
  14029. Unfortunately, running this program with input \code{1} triggers an
  14030. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  14031. performs checking at runtime to ensure the integrity of the static
  14032. types, such as the \code{(Integer -> Integer)} annotation on parameter
  14033. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  14034. new \code{Cast} form that is inserted by the type checker. Thus, the
  14035. output of the type checker is a program in the \LangCast{} language, which
  14036. adds \code{Cast} to \LangLoop{}, as shown in
  14037. Figure~\ref{fig:Rgrad-prime-syntax}.
  14038. \begin{figure}[tp]
  14039. \centering
  14040. \fbox{
  14041. \begin{minipage}{0.96\textwidth}
  14042. \small
  14043. \[
  14044. \begin{array}{lcl}
  14045. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  14046. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14047. \end{array}
  14048. \]
  14049. \end{minipage}
  14050. }
  14051. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14052. \label{fig:Rgrad-prime-syntax}
  14053. \end{figure}
  14054. \begin{figure}[tbp]
  14055. \begin{lstlisting}
  14056. (define (map-vec [f : (Integer -> Integer)]
  14057. [v : (Vector Integer Integer)])
  14058. : (Vector Integer Integer)
  14059. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14060. (define (add1 x) (+ x 1))
  14061. (define (true) #t)
  14062. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  14063. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  14064. \end{lstlisting}
  14065. \caption{A variant of the \code{map-vec} example with an error.}
  14066. \label{fig:map-vec-maybe-add1}
  14067. \end{figure}
  14068. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  14069. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  14070. inserted every time the type checker sees two types that are
  14071. consistent but not equal. In the \code{add1} function, \code{x} is
  14072. cast to \code{Integer} and the result of the \code{+} is cast to
  14073. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  14074. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  14075. \begin{figure}[btp]
  14076. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14077. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  14078. : (Vector Integer Integer)
  14079. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14080. (define (add1 [x : Any]) : Any
  14081. (cast (+ (cast x Any Integer) 1) Integer Any))
  14082. (define (true) : Any (cast #t Boolean Any))
  14083. (define (maybe-add1 [x : Any]) : Any
  14084. (if (eq? 0 (read)) (add1 x) (true)))
  14085. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  14086. (vector 0 41)) 0)
  14087. \end{lstlisting}
  14088. \caption{Output of type checking \code{map-vec}
  14089. and \code{maybe-add1}.}
  14090. \label{fig:map-vec-cast}
  14091. \end{figure}
  14092. The type checker for \LangGrad{} is defined in
  14093. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  14094. and \ref{fig:type-check-Rgradual-3}.
  14095. \begin{figure}[tbp]
  14096. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14097. (define type-check-gradual_class
  14098. (class type-check-Rwhile_class
  14099. (super-new)
  14100. (inherit operator-types type-predicates)
  14101. (define/override (type-check-exp env)
  14102. (lambda (e)
  14103. (define recur (type-check-exp env))
  14104. (match e
  14105. [(Prim 'vector-length (list e1))
  14106. (define-values (e1^ t) (recur e1))
  14107. (match t
  14108. [`(Vector ,ts ...)
  14109. (values (Prim 'vector-length (list e1^)) 'Integer)]
  14110. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  14111. [(Prim 'vector-ref (list e1 e2))
  14112. (define-values (e1^ t1) (recur e1))
  14113. (define-values (e2^ t2) (recur e2))
  14114. (check-consistent? t2 'Integer e)
  14115. (match t1
  14116. [`(Vector ,ts ...)
  14117. (match e2^
  14118. [(Int i)
  14119. (unless (and (0 . <= . i) (i . < . (length ts)))
  14120. (error 'type-check "invalid index ~a in ~a" i e))
  14121. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  14122. [else (define e1^^ (make-cast e1^ t1 'Any))
  14123. (define e2^^ (make-cast e2^ t2 'Integer))
  14124. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  14125. ['Any
  14126. (define e2^^ (make-cast e2^ t2 'Integer))
  14127. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  14128. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14129. [(Prim 'vector-set! (list e1 e2 e3) )
  14130. (define-values (e1^ t1) (recur e1))
  14131. (define-values (e2^ t2) (recur e2))
  14132. (define-values (e3^ t3) (recur e3))
  14133. (check-consistent? t2 'Integer e)
  14134. (match t1
  14135. [`(Vector ,ts ...)
  14136. (match e2^
  14137. [(Int i)
  14138. (unless (and (0 . <= . i) (i . < . (length ts)))
  14139. (error 'type-check "invalid index ~a in ~a" i e))
  14140. (check-consistent? (list-ref ts i) t3 e)
  14141. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  14142. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  14143. [else
  14144. (define e1^^ (make-cast e1^ t1 'Any))
  14145. (define e2^^ (make-cast e2^ t2 'Integer))
  14146. (define e3^^ (make-cast e3^ t3 'Any))
  14147. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  14148. ['Any
  14149. (define e2^^ (make-cast e2^ t2 'Integer))
  14150. (define e3^^ (make-cast e3^ t3 'Any))
  14151. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  14152. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14153. \end{lstlisting}
  14154. \caption{Type checker for the \LangGrad{} language, part 1.}
  14155. \label{fig:type-check-Rgradual-1}
  14156. \end{figure}
  14157. \begin{figure}[tbp]
  14158. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14159. [(Prim 'eq? (list e1 e2))
  14160. (define-values (e1^ t1) (recur e1))
  14161. (define-values (e2^ t2) (recur e2))
  14162. (check-consistent? t1 t2 e)
  14163. (define T (meet t1 t2))
  14164. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  14165. 'Boolean)]
  14166. [(Prim 'not (list e1))
  14167. (define-values (e1^ t1) (recur e1))
  14168. (match t1
  14169. ['Any
  14170. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  14171. (Bool #t) (Bool #f)))]
  14172. [else
  14173. (define-values (t-ret new-es^)
  14174. (type-check-op 'not (list t1) (list e1^) e))
  14175. (values (Prim 'not new-es^) t-ret)])]
  14176. [(Prim 'and (list e1 e2))
  14177. (recur (If e1 e2 (Bool #f)))]
  14178. [(Prim 'or (list e1 e2))
  14179. (define tmp (gensym 'tmp))
  14180. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  14181. [(Prim op es)
  14182. #:when (not (set-member? explicit-prim-ops op))
  14183. (define-values (new-es ts)
  14184. (for/lists (exprs types) ([e es])
  14185. (recur e)))
  14186. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  14187. (values (Prim op new-es^) t-ret)]
  14188. [(If e1 e2 e3)
  14189. (define-values (e1^ T1) (recur e1))
  14190. (define-values (e2^ T2) (recur e2))
  14191. (define-values (e3^ T3) (recur e3))
  14192. (check-consistent? T2 T3 e)
  14193. (match T1
  14194. ['Boolean
  14195. (define Tif (join T2 T3))
  14196. (values (If e1^ (make-cast e2^ T2 Tif)
  14197. (make-cast e3^ T3 Tif)) Tif)]
  14198. ['Any
  14199. (define Tif (meet T2 T3))
  14200. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  14201. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  14202. Tif)]
  14203. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  14204. [(HasType e1 T)
  14205. (define-values (e1^ T1) (recur e1))
  14206. (check-consistent? T1 T)
  14207. (values (make-cast e1^ T1 T) T)]
  14208. [(SetBang x e1)
  14209. (define-values (e1^ T1) (recur e1))
  14210. (define varT (dict-ref env x))
  14211. (check-consistent? T1 varT e)
  14212. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  14213. [(WhileLoop e1 e2)
  14214. (define-values (e1^ T1) (recur e1))
  14215. (check-consistent? T1 'Boolean e)
  14216. (define-values (e2^ T2) ((type-check-exp env) e2))
  14217. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  14218. \end{lstlisting}
  14219. \caption{Type checker for the \LangGrad{} language, part 2.}
  14220. \label{fig:type-check-Rgradual-2}
  14221. \end{figure}
  14222. \begin{figure}[tbp]
  14223. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14224. [(Apply e1 e2s)
  14225. (define-values (e1^ T1) (recur e1))
  14226. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  14227. (match T1
  14228. [`(,T1ps ... -> ,T1rt)
  14229. (for ([T2 T2s] [Tp T1ps])
  14230. (check-consistent? T2 Tp e))
  14231. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  14232. (make-cast e2 src tgt)))
  14233. (values (Apply e1^ e2s^^) T1rt)]
  14234. [`Any
  14235. (define e1^^ (make-cast e1^ 'Any
  14236. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  14237. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  14238. (make-cast e2 src 'Any)))
  14239. (values (Apply e1^^ e2s^^) 'Any)]
  14240. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  14241. [(Lambda params Tr e1)
  14242. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  14243. (match p
  14244. [`[,x : ,T] (values x T)]
  14245. [(? symbol? x) (values x 'Any)])))
  14246. (define-values (e1^ T1)
  14247. ((type-check-exp (append (map cons xs Ts) env)) e1))
  14248. (check-consistent? Tr T1 e)
  14249. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  14250. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  14251. [else ((super type-check-exp env) e)]
  14252. )))
  14253. \end{lstlisting}
  14254. \caption{Type checker for the \LangGrad{} language, part 3.}
  14255. \label{fig:type-check-Rgradual-3}
  14256. \end{figure}
  14257. \begin{figure}[tbp]
  14258. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14259. (define/public (join t1 t2)
  14260. (match* (t1 t2)
  14261. [('Integer 'Integer) 'Integer]
  14262. [('Boolean 'Boolean) 'Boolean]
  14263. [('Void 'Void) 'Void]
  14264. [('Any t2) t2]
  14265. [(t1 'Any) t1]
  14266. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14267. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  14268. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14269. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  14270. -> ,(join rt1 rt2))]))
  14271. (define/public (meet t1 t2)
  14272. (match* (t1 t2)
  14273. [('Integer 'Integer) 'Integer]
  14274. [('Boolean 'Boolean) 'Boolean]
  14275. [('Void 'Void) 'Void]
  14276. [('Any t2) 'Any]
  14277. [(t1 'Any) 'Any]
  14278. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14279. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  14280. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14281. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  14282. -> ,(meet rt1 rt2))]))
  14283. (define/public (make-cast e src tgt)
  14284. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  14285. (define/public (check-consistent? t1 t2 e)
  14286. (unless (consistent? t1 t2)
  14287. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  14288. (define/override (type-check-op op arg-types args e)
  14289. (match (dict-ref (operator-types) op)
  14290. [`(,param-types . ,return-type)
  14291. (for ([at arg-types] [pt param-types])
  14292. (check-consistent? at pt e))
  14293. (values return-type
  14294. (for/list ([e args] [s arg-types] [t param-types])
  14295. (make-cast e s t)))]
  14296. [else (error 'type-check-op "unrecognized ~a" op)]))
  14297. (define explicit-prim-ops
  14298. (set-union
  14299. (type-predicates)
  14300. (set 'procedure-arity 'eq?
  14301. 'vector 'vector-length 'vector-ref 'vector-set!
  14302. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  14303. (define/override (fun-def-type d)
  14304. (match d
  14305. [(Def f params rt info body)
  14306. (define ps
  14307. (for/list ([p params])
  14308. (match p
  14309. [`[,x : ,T] T]
  14310. [(? symbol?) 'Any]
  14311. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  14312. `(,@ps -> ,rt)]
  14313. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  14314. \end{lstlisting}
  14315. \caption{Auxiliary functions for type checking \LangGrad{}.}
  14316. \label{fig:type-check-Rgradual-aux}
  14317. \end{figure}
  14318. \clearpage
  14319. \section{Interpreting \LangCast{}}
  14320. \label{sec:interp-casts}
  14321. The runtime behavior of first-order casts is straightforward, that is,
  14322. casts involving simple types such as \code{Integer} and
  14323. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  14324. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  14325. puts the integer into a tagged value
  14326. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  14327. \code{Integer} is accomplished with the \code{Project} operator, that
  14328. is, by checking the value's tag and either retrieving the underlying
  14329. integer or signaling an error if it the tag is not the one for
  14330. integers (Figure~\ref{fig:apply-project}).
  14331. %
  14332. Things get more interesting for higher-order casts, that is, casts
  14333. involving function or vector types.
  14334. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  14335. Any)} to \code{(Integer -> Integer)}. When a function flows through
  14336. this cast at runtime, we can't know in general whether the function
  14337. will always return an integer.\footnote{Predicting the return value of
  14338. a function is equivalent to the halting problem, which is
  14339. undecidable.} The \LangCast{} interpreter therefore delays the checking
  14340. of the cast until the function is applied. This is accomplished by
  14341. wrapping \code{maybe-add1} in a new function that casts its parameter
  14342. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  14343. casts the return value from \code{Any} to \code{Integer}.
  14344. Turning our attention to casts involving vector types, we consider the
  14345. example in Figure~\ref{fig:map-vec-bang} that defines a
  14346. partially-typed version of \code{map-vec} whose parameter \code{v} has
  14347. type \code{(Vector Any Any)} and that updates \code{v} in place
  14348. instead of returning a new vector. So we name this function
  14349. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  14350. the type checker inserts a cast from \code{(Vector Integer Integer)}
  14351. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  14352. cast between vector types would be a build a new vector whose elements
  14353. are the result of casting each of the original elements to the
  14354. appropriate target type. However, this approach is only valid for
  14355. immutable vectors; and our vectors are mutable. In the example of
  14356. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  14357. the updates inside of \code{map-vec!} would happen to the new vector
  14358. and not the original one.
  14359. \begin{figure}[tbp]
  14360. % gradual_test_11.rkt
  14361. \begin{lstlisting}
  14362. (define (map-vec! [f : (Any -> Any)]
  14363. [v : (Vector Any Any)]) : Void
  14364. (begin
  14365. (vector-set! v 0 (f (vector-ref v 0)))
  14366. (vector-set! v 1 (f (vector-ref v 1)))))
  14367. (define (add1 x) (+ x 1))
  14368. (let ([v (vector 0 41)])
  14369. (begin (map-vec! add1 v) (vector-ref v 1)))
  14370. \end{lstlisting}
  14371. \caption{An example involving casts on vectors.}
  14372. \label{fig:map-vec-bang}
  14373. \end{figure}
  14374. Instead the interpreter needs to create a new kind of value, a
  14375. \emph{vector proxy}, that intercepts every vector operation. On a
  14376. read, the proxy reads from the underlying vector and then applies a
  14377. cast to the resulting value. On a write, the proxy casts the argument
  14378. value and then performs the write to the underlying vector. For the
  14379. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  14380. \code{0} from \code{Integer} to \code{Any}. For the first
  14381. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  14382. to \code{Integer}.
  14383. The final category of cast that we need to consider are casts between
  14384. the \code{Any} type and either a function or a vector
  14385. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  14386. in which parameter \code{v} does not have a type annotation, so it is
  14387. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  14388. type \code{(Vector Integer Integer)} so the type checker inserts a
  14389. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  14390. thought is to use \code{Inject}, but that doesn't work because
  14391. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  14392. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  14393. to \code{Any}.
  14394. \begin{figure}[tbp]
  14395. \begin{lstlisting}
  14396. (define (map-vec! [f : (Any -> Any)] v) : Void
  14397. (begin
  14398. (vector-set! v 0 (f (vector-ref v 0)))
  14399. (vector-set! v 1 (f (vector-ref v 1)))))
  14400. (define (add1 x) (+ x 1))
  14401. (let ([v (vector 0 41)])
  14402. (begin (map-vec! add1 v) (vector-ref v 1)))
  14403. \end{lstlisting}
  14404. \caption{Casting a vector to \code{Any}.}
  14405. \label{fig:map-vec-any}
  14406. \end{figure}
  14407. The \LangCast{} interpreter uses an auxiliary function named
  14408. \code{apply-cast} to cast a value from a source type to a target type,
  14409. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  14410. of the kinds of casts that we've discussed in this section.
  14411. \begin{figure}[tbp]
  14412. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14413. (define/public (apply-cast v s t)
  14414. (match* (s t)
  14415. [(t1 t2) #:when (equal? t1 t2) v]
  14416. [('Any t2)
  14417. (match t2
  14418. [`(,ts ... -> ,rt)
  14419. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  14420. (define v^ (apply-project v any->any))
  14421. (apply-cast v^ any->any `(,@ts -> ,rt))]
  14422. [`(Vector ,ts ...)
  14423. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  14424. (define v^ (apply-project v vec-any))
  14425. (apply-cast v^ vec-any `(Vector ,@ts))]
  14426. [else (apply-project v t2)])]
  14427. [(t1 'Any)
  14428. (match t1
  14429. [`(,ts ... -> ,rt)
  14430. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  14431. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  14432. (apply-inject v^ (any-tag any->any))]
  14433. [`(Vector ,ts ...)
  14434. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  14435. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  14436. (apply-inject v^ (any-tag vec-any))]
  14437. [else (apply-inject v (any-tag t1))])]
  14438. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14439. (define x (gensym 'x))
  14440. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  14441. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  14442. (define cast-writes
  14443. (for/list ([t1 ts1] [t2 ts2])
  14444. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  14445. `(vector-proxy ,(vector v (apply vector cast-reads)
  14446. (apply vector cast-writes)))]
  14447. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14448. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  14449. `(function ,xs ,(Cast
  14450. (Apply (Value v)
  14451. (for/list ([x xs][t1 ts1][t2 ts2])
  14452. (Cast (Var x) t2 t1)))
  14453. rt1 rt2) ())]
  14454. ))
  14455. \end{lstlisting}
  14456. \caption{The \code{apply-cast} auxiliary method.}
  14457. \label{fig:apply-cast}
  14458. \end{figure}
  14459. The interpreter for \LangCast{} is defined in
  14460. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  14461. dispatching to \code{apply-cast}. To handle the addition of vector
  14462. proxies, we update the vector primitives in \code{interp-op} using the
  14463. functions in Figure~\ref{fig:guarded-vector}.
  14464. \begin{figure}[tbp]
  14465. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14466. (define interp-Rcast_class
  14467. (class interp-Rwhile_class
  14468. (super-new)
  14469. (inherit apply-fun apply-inject apply-project)
  14470. (define/override (interp-op op)
  14471. (match op
  14472. ['vector-length guarded-vector-length]
  14473. ['vector-ref guarded-vector-ref]
  14474. ['vector-set! guarded-vector-set!]
  14475. ['any-vector-ref (lambda (v i)
  14476. (match v [`(tagged ,v^ ,tg)
  14477. (guarded-vector-ref v^ i)]))]
  14478. ['any-vector-set! (lambda (v i a)
  14479. (match v [`(tagged ,v^ ,tg)
  14480. (guarded-vector-set! v^ i a)]))]
  14481. ['any-vector-length (lambda (v)
  14482. (match v [`(tagged ,v^ ,tg)
  14483. (guarded-vector-length v^)]))]
  14484. [else (super interp-op op)]
  14485. ))
  14486. (define/override ((interp-exp env) e)
  14487. (define (recur e) ((interp-exp env) e))
  14488. (match e
  14489. [(Value v) v]
  14490. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  14491. [else ((super interp-exp env) e)]))
  14492. ))
  14493. (define (interp-Rcast p)
  14494. (send (new interp-Rcast_class) interp-program p))
  14495. \end{lstlisting}
  14496. \caption{The interpreter for \LangCast{}.}
  14497. \label{fig:interp-Rcast}
  14498. \end{figure}
  14499. \begin{figure}[tbp]
  14500. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14501. (define (guarded-vector-ref vec i)
  14502. (match vec
  14503. [`(vector-proxy ,proxy)
  14504. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  14505. (define rd (vector-ref (vector-ref proxy 1) i))
  14506. (apply-fun rd (list val) 'guarded-vector-ref)]
  14507. [else (vector-ref vec i)]))
  14508. (define (guarded-vector-set! vec i arg)
  14509. (match vec
  14510. [`(vector-proxy ,proxy)
  14511. (define wr (vector-ref (vector-ref proxy 2) i))
  14512. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  14513. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  14514. [else (vector-set! vec i arg)]))
  14515. (define (guarded-vector-length vec)
  14516. (match vec
  14517. [`(vector-proxy ,proxy)
  14518. (guarded-vector-length (vector-ref proxy 0))]
  14519. [else (vector-length vec)]))
  14520. \end{lstlisting}
  14521. \caption{The guarded-vector auxiliary functions.}
  14522. \label{fig:guarded-vector}
  14523. \end{figure}
  14524. \section{Lower Casts}
  14525. \label{sec:lower-casts}
  14526. The next step in the journey towards x86 is the \code{lower-casts}
  14527. pass that translates the casts in \LangCast{} to the lower-level
  14528. \code{Inject} and \code{Project} operators and a new operator for
  14529. creating vector proxies, extending the \LangLoop{} language to create
  14530. \LangProxy{}. We recommend creating an auxiliary function named
  14531. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  14532. and a target type, and translates it to expression in \LangProxy{} that has
  14533. the same behavior as casting the expression from the source to the
  14534. target type in the interpreter.
  14535. The \code{lower-cast} function can follow a code structure similar to
  14536. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  14537. the interpreter for \LangCast{} because it must handle the same cases as
  14538. \code{apply-cast} and it needs to mimic the behavior of
  14539. \code{apply-cast}. The most interesting cases are those concerning the
  14540. casts between two vector types and between two function types.
  14541. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  14542. type to another vector type is accomplished by creating a proxy that
  14543. intercepts the operations on the underlying vector. Here we make the
  14544. creation of the proxy explicit with the \code{vector-proxy} primitive
  14545. operation. It takes three arguments, the first is an expression for
  14546. the vector, the second is a vector of functions for casting an element
  14547. that is being read from the vector, and the third is a vector of
  14548. functions for casting an element that is being written to the vector.
  14549. You can create the functions using \code{Lambda}. Also, as we shall
  14550. see in the next section, we need to differentiate these vectors from
  14551. the user-created ones, so we recommend using a new primitive operator
  14552. named \code{raw-vector} instead of \code{vector} to create these
  14553. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  14554. the output of \code{lower-casts} on the example in
  14555. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  14556. integers to a vector of \code{Any}.
  14557. \begin{figure}[tbp]
  14558. \begin{lstlisting}
  14559. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  14560. (begin
  14561. (vector-set! v 0 (f (vector-ref v 0)))
  14562. (vector-set! v 1 (f (vector-ref v 1)))))
  14563. (define (add1 [x : Any]) : Any
  14564. (inject (+ (project x Integer) 1) Integer))
  14565. (let ([v (vector 0 41)])
  14566. (begin
  14567. (map-vec! add1 (vector-proxy v
  14568. (raw-vector (lambda: ([x9 : Integer]) : Any
  14569. (inject x9 Integer))
  14570. (lambda: ([x9 : Integer]) : Any
  14571. (inject x9 Integer)))
  14572. (raw-vector (lambda: ([x9 : Any]) : Integer
  14573. (project x9 Integer))
  14574. (lambda: ([x9 : Any]) : Integer
  14575. (project x9 Integer)))))
  14576. (vector-ref v 1)))
  14577. \end{lstlisting}
  14578. \caption{Output of \code{lower-casts} on the example in
  14579. Figure~\ref{fig:map-vec-bang}.}
  14580. \label{fig:map-vec-bang-lower-cast}
  14581. \end{figure}
  14582. A cast from one function type to another function type is accomplished
  14583. by generating a \code{Lambda} whose parameter and return types match
  14584. the target function type. The body of the \code{Lambda} should cast
  14585. the parameters from the target type to the source type (yes,
  14586. backwards! functions are contravariant\index{subject}{contravariant} in the
  14587. parameters), then call the underlying function, and finally cast the
  14588. result from the source return type to the target return type.
  14589. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  14590. \code{lower-casts} pass on the \code{map-vec} example in
  14591. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  14592. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  14593. \begin{figure}[tbp]
  14594. \begin{lstlisting}
  14595. (define (map-vec [f : (Integer -> Integer)]
  14596. [v : (Vector Integer Integer)])
  14597. : (Vector Integer Integer)
  14598. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14599. (define (add1 [x : Any]) : Any
  14600. (inject (+ (project x Integer) 1) Integer))
  14601. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  14602. (project (add1 (inject x9 Integer)) Integer))
  14603. (vector 0 41)) 1)
  14604. \end{lstlisting}
  14605. \caption{Output of \code{lower-casts} on the example in
  14606. Figure~\ref{fig:gradual-map-vec}.}
  14607. \label{fig:map-vec-lower-cast}
  14608. \end{figure}
  14609. \section{Differentiate Proxies}
  14610. \label{sec:differentiate-proxies}
  14611. So far the job of differentiating vectors and vector proxies has been
  14612. the job of the interpreter. For example, the interpreter for \LangCast{}
  14613. implements \code{vector-ref} using the \code{guarded-vector-ref}
  14614. function in Figure~\ref{fig:guarded-vector}. In the
  14615. \code{differentiate-proxies} pass we shift this responsibility to the
  14616. generated code.
  14617. We begin by designing the output language $R^p_8$. In
  14618. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  14619. proxies. In $R^p_8$ we return the \code{Vector} type to
  14620. its original meaning, as the type of real vectors, and we introduce a
  14621. new type, \code{PVector}, whose values can be either real vectors or
  14622. vector proxies. This new type comes with a suite of new primitive
  14623. operations for creating and using values of type \code{PVector}. We
  14624. don't need to introduce a new type to represent vector proxies. A
  14625. proxy is represented by a vector containing three things: 1) the
  14626. underlying vector, 2) a vector of functions for casting elements that
  14627. are read from the vector, and 3) a vector of functions for casting
  14628. values to be written to the vector. So we define the following
  14629. abbreviation for the type of a vector proxy:
  14630. \[
  14631. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  14632. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  14633. \to (\key{PVector}~ T' \ldots)
  14634. \]
  14635. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  14636. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  14637. %
  14638. Next we describe each of the new primitive operations.
  14639. \begin{description}
  14640. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  14641. (\key{PVector} $T \ldots$)]\ \\
  14642. %
  14643. This operation brands a vector as a value of the \code{PVector} type.
  14644. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  14645. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  14646. %
  14647. This operation brands a vector proxy as value of the \code{PVector} type.
  14648. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  14649. \code{Boolean}] \ \\
  14650. %
  14651. returns true if the value is a vector proxy and false if it is a
  14652. real vector.
  14653. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  14654. (\key{Vector} $T \ldots$)]\ \\
  14655. %
  14656. Assuming that the input is a vector (and not a proxy), this
  14657. operation returns the vector.
  14658. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  14659. $\to$ \code{Boolean}]\ \\
  14660. %
  14661. Given a vector proxy, this operation returns the length of the
  14662. underlying vector.
  14663. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  14664. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  14665. %
  14666. Given a vector proxy, this operation returns the $i$th element of
  14667. the underlying vector.
  14668. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  14669. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  14670. proxy, this operation writes a value to the $i$th element of the
  14671. underlying vector.
  14672. \end{description}
  14673. Now to discuss the translation that differentiates vectors from
  14674. proxies. First, every type annotation in the program must be
  14675. translated (recursively) to replace \code{Vector} with \code{PVector}.
  14676. Next, we must insert uses of \code{PVector} operations in the
  14677. appropriate places. For example, we wrap every vector creation with an
  14678. \code{inject-vector}.
  14679. \begin{lstlisting}
  14680. (vector |$e_1 \ldots e_n$|)
  14681. |$\Rightarrow$|
  14682. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  14683. \end{lstlisting}
  14684. The \code{raw-vector} operator that we introduced in the previous
  14685. section does not get injected.
  14686. \begin{lstlisting}
  14687. (raw-vector |$e_1 \ldots e_n$|)
  14688. |$\Rightarrow$|
  14689. (vector |$e'_1 \ldots e'_n$|)
  14690. \end{lstlisting}
  14691. The \code{vector-proxy} primitive translates as follows.
  14692. \begin{lstlisting}
  14693. (vector-proxy |$e_1~e_2~e_3$|)
  14694. |$\Rightarrow$|
  14695. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  14696. \end{lstlisting}
  14697. We translate the vector operations into conditional expressions that
  14698. check whether the value is a proxy and then dispatch to either the
  14699. appropriate proxy vector operation or the regular vector operation.
  14700. For example, the following is the translation for \code{vector-ref}.
  14701. \begin{lstlisting}
  14702. (vector-ref |$e_1$| |$i$|)
  14703. |$\Rightarrow$|
  14704. (let ([|$v~e_1$|])
  14705. (if (proxy? |$v$|)
  14706. (proxy-vector-ref |$v$| |$i$|)
  14707. (vector-ref (project-vector |$v$|) |$i$|)
  14708. \end{lstlisting}
  14709. Note in the case of a real vector, we must apply \code{project-vector}
  14710. before the \code{vector-ref}.
  14711. \section{Reveal Casts}
  14712. \label{sec:reveal-casts-gradual}
  14713. Recall that the \code{reveal-casts} pass
  14714. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  14715. \code{Inject} and \code{Project} into lower-level operations. In
  14716. particular, \code{Project} turns into a conditional expression that
  14717. inspects the tag and retrieves the underlying value. Here we need to
  14718. augment the translation of \code{Project} to handle the situation when
  14719. the target type is \code{PVector}. Instead of using
  14720. \code{vector-length} we need to use \code{proxy-vector-length}.
  14721. \begin{lstlisting}
  14722. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  14723. |$\Rightarrow$|
  14724. (let |$\itm{tmp}$| |$e'$|
  14725. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  14726. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  14727. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  14728. (exit)))
  14729. \end{lstlisting}
  14730. \section{Closure Conversion}
  14731. \label{sec:closure-conversion-gradual}
  14732. The closure conversion pass only requires one minor adjustment. The
  14733. auxiliary function that translates type annotations needs to be
  14734. updated to handle the \code{PVector} type.
  14735. \section{Explicate Control}
  14736. \label{sec:explicate-control-gradual}
  14737. Update the \code{explicate\_control} pass to handle the new primitive
  14738. operations on the \code{PVector} type.
  14739. \section{Select Instructions}
  14740. \label{sec:select-instructions-gradual}
  14741. Recall that the \code{select\_instructions} pass is responsible for
  14742. lowering the primitive operations into x86 instructions. So we need
  14743. to translate the new \code{PVector} operations to x86. To do so, the
  14744. first question we need to answer is how will we differentiate the two
  14745. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  14746. We need just one bit to accomplish this, and use the bit in position
  14747. $57$ of the 64-bit tag at the front of every vector (see
  14748. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  14749. for \code{inject-vector} we leave it that way.
  14750. \begin{lstlisting}
  14751. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  14752. |$\Rightarrow$|
  14753. movq |$e'_1$|, |$\itm{lhs'}$|
  14754. \end{lstlisting}
  14755. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  14756. \begin{lstlisting}
  14757. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  14758. |$\Rightarrow$|
  14759. movq |$e'_1$|, %r11
  14760. movq |$(1 << 57)$|, %rax
  14761. orq 0(%r11), %rax
  14762. movq %rax, 0(%r11)
  14763. movq %r11, |$\itm{lhs'}$|
  14764. \end{lstlisting}
  14765. The \code{proxy?} operation consumes the information so carefully
  14766. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  14767. isolates the $57$th bit to tell whether the value is a real vector or
  14768. a proxy.
  14769. \begin{lstlisting}
  14770. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  14771. |$\Rightarrow$|
  14772. movq |$e_1'$|, %r11
  14773. movq 0(%r11), %rax
  14774. sarq $57, %rax
  14775. andq $1, %rax
  14776. movq %rax, |$\itm{lhs'}$|
  14777. \end{lstlisting}
  14778. The \code{project-vector} operation is straightforward to translate,
  14779. so we leave it up to the reader.
  14780. Regarding the \code{proxy-vector} operations, the runtime provides
  14781. procedures that implement them (they are recursive functions!) so
  14782. here we simply need to translate these vector operations into the
  14783. appropriate function call. For example, here is the translation for
  14784. \code{proxy-vector-ref}.
  14785. \begin{lstlisting}
  14786. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  14787. |$\Rightarrow$|
  14788. movq |$e_1'$|, %rdi
  14789. movq |$e_2'$|, %rsi
  14790. callq proxy_vector_ref
  14791. movq %rax, |$\itm{lhs'}$|
  14792. \end{lstlisting}
  14793. We have another batch of vector operations to deal with, those for the
  14794. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  14795. \code{any-vector-ref} when there is a \code{vector-ref} on something
  14796. of type \code{Any}, and similarly for \code{any-vector-set!} and
  14797. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  14798. Section~\ref{sec:select-Rany} we selected instructions for these
  14799. operations based on the idea that the underlying value was a real
  14800. vector. But in the current setting, the underlying value is of type
  14801. \code{PVector}. So \code{any-vector-ref} can be translates to
  14802. pseudo-x86 as follows. We begin by projecting the underlying value out
  14803. of the tagged value and then call the \code{proxy\_vector\_ref}
  14804. procedure in the runtime.
  14805. \begin{lstlisting}
  14806. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  14807. movq |$\neg 111$|, %rdi
  14808. andq |$e_1'$|, %rdi
  14809. movq |$e_2'$|, %rsi
  14810. callq proxy_vector_ref
  14811. movq %rax, |$\itm{lhs'}$|
  14812. \end{lstlisting}
  14813. The \code{any-vector-set!} and \code{any-vector-length} operators can
  14814. be translated in a similar way.
  14815. \begin{exercise}\normalfont
  14816. Implement a compiler for the gradually-typed \LangGrad{} language by
  14817. extending and adapting your compiler for \LangLoop{}. Create 10 new
  14818. partially-typed test programs. In addition to testing with these
  14819. new programs, also test your compiler on all the tests for \LangLoop{}
  14820. and tests for \LangDyn{}. Sometimes you may get a type checking error
  14821. on the \LangDyn{} programs but you can adapt them by inserting
  14822. a cast to the \code{Any} type around each subexpression
  14823. causing a type error. While \LangDyn{} doesn't have explicit casts,
  14824. you can induce one by wrapping the subexpression \code{e}
  14825. with a call to an un-annotated identity function, like this:
  14826. \code{((lambda (x) x) e)}.
  14827. \end{exercise}
  14828. \begin{figure}[p]
  14829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14830. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  14831. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  14832. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  14833. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  14834. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  14835. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  14836. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  14837. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  14838. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  14839. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  14840. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  14841. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  14842. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  14843. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  14844. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14845. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14846. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14847. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14848. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14849. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14850. \path[->,bend right=15] (Rgradual) edge [above] node
  14851. {\ttfamily\footnotesize type\_check} (Rgradualp);
  14852. \path[->,bend right=15] (Rgradualp) edge [above] node
  14853. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  14854. \path[->,bend right=15] (Rwhilepp) edge [right] node
  14855. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  14856. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  14857. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  14858. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  14859. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  14860. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  14861. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  14862. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  14863. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  14864. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  14865. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14866. \path[->,bend left=15] (F1-1) edge [below] node
  14867. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14868. \path[->,bend right=15] (F1-2) edge [above] node
  14869. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14870. \path[->,bend right=15] (F1-3) edge [above] node
  14871. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14872. \path[->,bend right=15] (F1-4) edge [above] node
  14873. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14874. \path[->,bend right=15] (F1-5) edge [right] node
  14875. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14876. \path[->,bend left=15] (C3-2) edge [left] node
  14877. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14878. \path[->,bend right=15] (x86-2) edge [left] node
  14879. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14880. \path[->,bend right=15] (x86-2-1) edge [below] node
  14881. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14882. \path[->,bend right=15] (x86-2-2) edge [left] node
  14883. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14884. \path[->,bend left=15] (x86-3) edge [above] node
  14885. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14886. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  14887. \end{tikzpicture}
  14888. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  14889. \label{fig:Rgradual-passes}
  14890. \end{figure}
  14891. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  14892. for the compilation of \LangGrad{}.
  14893. \section{Further Reading}
  14894. This chapter just scratches the surface of gradual typing. The basic
  14895. approach described here is missing two key ingredients that one would
  14896. want in a implementation of gradual typing: blame
  14897. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  14898. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  14899. problem addressed by blame tracking is that when a cast on a
  14900. higher-order value fails, it often does so at a point in the program
  14901. that is far removed from the original cast. Blame tracking is a
  14902. technique for propagating extra information through casts and proxies
  14903. so that when a cast fails, the error message can point back to the
  14904. original location of the cast in the source program.
  14905. The problem addressed by space-efficient casts also relates to
  14906. higher-order casts. It turns out that in partially typed programs, a
  14907. function or vector can flow through very-many casts at runtime. With
  14908. the approach described in this chapter, each cast adds another
  14909. \code{lambda} wrapper or a vector proxy. Not only does this take up
  14910. considerable space, but it also makes the function calls and vector
  14911. operations slow. For example, a partially-typed version of quicksort
  14912. could, in the worst case, build a chain of proxies of length $O(n)$
  14913. around the vector, changing the overall time complexity of the
  14914. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  14915. solution to this problem by representing casts using the coercion
  14916. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  14917. long chains of proxies by compressing them into a concise normal
  14918. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  14919. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  14920. the Grift compiler.
  14921. \begin{center}
  14922. \url{https://github.com/Gradual-Typing/Grift}
  14923. \end{center}
  14924. There are also interesting interactions between gradual typing and
  14925. other language features, such as parametetric polymorphism,
  14926. information-flow types, and type inference, to name a few. We
  14927. recommend the reader to the online gradual typing bibliography:
  14928. \begin{center}
  14929. \url{http://samth.github.io/gradual-typing-bib/}
  14930. \end{center}
  14931. % TODO: challenge problem:
  14932. % type analysis and type specialization?
  14933. % coercions?
  14934. \fi
  14935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14936. \chapter{Parametric Polymorphism}
  14937. \label{ch:Rpoly}
  14938. \index{subject}{parametric polymorphism}
  14939. \index{subject}{generics}
  14940. \if\edition\racketEd
  14941. This chapter studies the compilation of parametric
  14942. polymorphism\index{subject}{parametric polymorphism}
  14943. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  14944. Racket. Parametric polymorphism enables improved code reuse by
  14945. parameterizing functions and data structures with respect to the types
  14946. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  14947. revisits the \code{map-vec} example but this time gives it a more
  14948. fitting type. This \code{map-vec} function is parameterized with
  14949. respect to the element type of the vector. The type of \code{map-vec}
  14950. is the following polymorphic type as specified by the \code{All} and
  14951. the type parameter \code{a}.
  14952. \begin{lstlisting}
  14953. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14954. \end{lstlisting}
  14955. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  14956. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  14957. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  14958. \code{a}, but we could have just as well applied \code{map-vec} to a
  14959. vector of Booleans (and a function on Booleans).
  14960. \begin{figure}[tbp]
  14961. % poly_test_2.rkt
  14962. \begin{lstlisting}
  14963. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  14964. (define (map-vec f v)
  14965. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14966. (define (add1 [x : Integer]) : Integer (+ x 1))
  14967. (vector-ref (map-vec add1 (vector 0 41)) 1)
  14968. \end{lstlisting}
  14969. \caption{The \code{map-vec} example using parametric polymorphism.}
  14970. \label{fig:map-vec-poly}
  14971. \end{figure}
  14972. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  14973. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  14974. syntax. We add a second form for function definitions in which a type
  14975. declaration comes before the \code{define}. In the abstract syntax,
  14976. the return type in the \code{Def} is \code{Any}, but that should be
  14977. ignored in favor of the return type in the type declaration. (The
  14978. \code{Any} comes from using the same parser as in
  14979. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  14980. enables the use of an \code{All} type for a function, thereby making
  14981. it polymorphic. The grammar for types is extended to include
  14982. polymorphic types and type variables.
  14983. \begin{figure}[tp]
  14984. \centering
  14985. \fbox{
  14986. \begin{minipage}{0.96\textwidth}
  14987. \small
  14988. \[
  14989. \begin{array}{lcl}
  14990. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14991. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  14992. &\MID& \LP\key{:}~\Var~\Type\RP \\
  14993. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  14994. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  14995. \end{array}
  14996. \]
  14997. \end{minipage}
  14998. }
  14999. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  15000. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15001. \label{fig:Rpoly-concrete-syntax}
  15002. \end{figure}
  15003. \begin{figure}[tp]
  15004. \centering
  15005. \fbox{
  15006. \begin{minipage}{0.96\textwidth}
  15007. \small
  15008. \[
  15009. \begin{array}{lcl}
  15010. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15011. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15012. &\MID& \DECL{\Var}{\Type} \\
  15013. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  15014. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15015. \end{array}
  15016. \]
  15017. \end{minipage}
  15018. }
  15019. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  15020. (Figure~\ref{fig:Lwhile-syntax}).}
  15021. \label{fig:Rpoly-syntax}
  15022. \end{figure}
  15023. By including polymorphic types in the $\Type$ non-terminal we choose
  15024. to make them first-class which has interesting repercussions on the
  15025. compiler. Many languages with polymorphism, such as
  15026. C++~\citep{stroustrup88:_param_types} and Standard
  15027. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  15028. it is useful to see an example of first-class polymorphism. In
  15029. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  15030. whose parameter is a polymorphic function. The occurrence of a
  15031. polymorphic type underneath a function type is enabled by the normal
  15032. recursive structure of the grammar for $\Type$ and the categorization
  15033. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  15034. applies the polymorphic function to a Boolean and to an integer.
  15035. \begin{figure}[tbp]
  15036. \begin{lstlisting}
  15037. (: apply-twice ((All (b) (b -> b)) -> Integer))
  15038. (define (apply-twice f)
  15039. (if (f #t) (f 42) (f 777)))
  15040. (: id (All (a) (a -> a)))
  15041. (define (id x) x)
  15042. (apply-twice id)
  15043. \end{lstlisting}
  15044. \caption{An example illustrating first-class polymorphism.}
  15045. \label{fig:apply-twice}
  15046. \end{figure}
  15047. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  15048. three new responsibilities (compared to \LangLoop{}). The type checking of
  15049. function application is extended to handle the case where the operator
  15050. expression is a polymorphic function. In that case the type arguments
  15051. are deduced by matching the type of the parameters with the types of
  15052. the arguments.
  15053. %
  15054. The \code{match-types} auxiliary function carries out this deduction
  15055. by recursively descending through a parameter type \code{pt} and the
  15056. corresponding argument type \code{at}, making sure that they are equal
  15057. except when there is a type parameter on the left (in the parameter
  15058. type). If it's the first time that the type parameter has been
  15059. encountered, then the algorithm deduces an association of the type
  15060. parameter to the corresponding type on the right (in the argument
  15061. type). If it's not the first time that the type parameter has been
  15062. encountered, the algorithm looks up its deduced type and makes sure
  15063. that it is equal to the type on the right.
  15064. %
  15065. Once the type arguments are deduced, the operator expression is
  15066. wrapped in an \code{Inst} AST node (for instantiate) that records the
  15067. type of the operator, but more importantly, records the deduced type
  15068. arguments. The return type of the application is the return type of
  15069. the polymorphic function, but with the type parameters replaced by the
  15070. deduced type arguments, using the \code{subst-type} function.
  15071. The second responsibility of the type checker is extending the
  15072. function \code{type-equal?} to handle the \code{All} type. This is
  15073. not quite a simple as equal on other types, such as function and
  15074. vector types, because two polymorphic types can be syntactically
  15075. different even though they are equivalent types. For example,
  15076. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  15077. Two polymorphic types should be considered equal if they differ only
  15078. in the choice of the names of the type parameters. The
  15079. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  15080. renames the type parameters of the first type to match the type
  15081. parameters of the second type.
  15082. The third responsibility of the type checker is making sure that only
  15083. defined type variables appear in type annotations. The
  15084. \code{check-well-formed} function defined in
  15085. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  15086. sure that each type variable has been defined.
  15087. The output language of the type checker is \LangInst{}, defined in
  15088. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  15089. declaration and polymorphic function into a single definition, using
  15090. the \code{Poly} form, to make polymorphic functions more convenient to
  15091. process in next pass of the compiler.
  15092. \begin{figure}[tp]
  15093. \centering
  15094. \fbox{
  15095. \begin{minipage}{0.96\textwidth}
  15096. \small
  15097. \[
  15098. \begin{array}{lcl}
  15099. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15100. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  15101. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15102. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  15103. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15104. \end{array}
  15105. \]
  15106. \end{minipage}
  15107. }
  15108. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  15109. (Figure~\ref{fig:Lwhile-syntax}).}
  15110. \label{fig:Rpoly-prime-syntax}
  15111. \end{figure}
  15112. The output of the type checker on the polymorphic \code{map-vec}
  15113. example is listed in Figure~\ref{fig:map-vec-type-check}.
  15114. \begin{figure}[tbp]
  15115. % poly_test_2.rkt
  15116. \begin{lstlisting}
  15117. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  15118. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  15119. (define (add1 [x : Integer]) : Integer (+ x 1))
  15120. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15121. (Integer))
  15122. add1 (vector 0 41)) 1)
  15123. \end{lstlisting}
  15124. \caption{Output of the type checker on the \code{map-vec} example.}
  15125. \label{fig:map-vec-type-check}
  15126. \end{figure}
  15127. \begin{figure}[tbp]
  15128. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15129. (define type-check-poly-class
  15130. (class type-check-Rwhile-class
  15131. (super-new)
  15132. (inherit check-type-equal?)
  15133. (define/override (type-check-apply env e1 es)
  15134. (define-values (e^ ty) ((type-check-exp env) e1))
  15135. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  15136. ((type-check-exp env) e)))
  15137. (match ty
  15138. [`(,ty^* ... -> ,rt)
  15139. (for ([arg-ty ty*] [param-ty ty^*])
  15140. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  15141. (values e^ es^ rt)]
  15142. [`(All ,xs (,tys ... -> ,rt))
  15143. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  15144. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  15145. (match-types env^^ param-ty arg-ty)))
  15146. (define targs
  15147. (for/list ([x xs])
  15148. (match (dict-ref env^^ x (lambda () #f))
  15149. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  15150. x (Apply e1 es))]
  15151. [ty ty])))
  15152. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  15153. [else (error 'type-check "expected a function, not ~a" ty)]))
  15154. (define/override ((type-check-exp env) e)
  15155. (match e
  15156. [(Lambda `([,xs : ,Ts] ...) rT body)
  15157. (for ([T Ts]) ((check-well-formed env) T))
  15158. ((check-well-formed env) rT)
  15159. ((super type-check-exp env) e)]
  15160. [(HasType e1 ty)
  15161. ((check-well-formed env) ty)
  15162. ((super type-check-exp env) e)]
  15163. [else ((super type-check-exp env) e)]))
  15164. (define/override ((type-check-def env) d)
  15165. (verbose 'type-check "poly/def" d)
  15166. (match d
  15167. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  15168. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  15169. (for ([p ps]) ((check-well-formed ts-env) p))
  15170. ((check-well-formed ts-env) rt)
  15171. (define new-env (append ts-env (map cons xs ps) env))
  15172. (define-values (body^ ty^) ((type-check-exp new-env) body))
  15173. (check-type-equal? ty^ rt body)
  15174. (Generic ts (Def f p:t* rt info body^))]
  15175. [else ((super type-check-def env) d)]))
  15176. (define/override (type-check-program p)
  15177. (match p
  15178. [(Program info body)
  15179. (type-check-program (ProgramDefsExp info '() body))]
  15180. [(ProgramDefsExp info ds body)
  15181. (define ds^ (combine-decls-defs ds))
  15182. (define new-env (for/list ([d ds^])
  15183. (cons (def-name d) (fun-def-type d))))
  15184. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  15185. (define-values (body^ ty) ((type-check-exp new-env) body))
  15186. (check-type-equal? ty 'Integer body)
  15187. (ProgramDefsExp info ds^^ body^)]))
  15188. ))
  15189. \end{lstlisting}
  15190. \caption{Type checker for the \LangPoly{} language.}
  15191. \label{fig:type-check-Lvar0}
  15192. \end{figure}
  15193. \begin{figure}[tbp]
  15194. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15195. (define/override (type-equal? t1 t2)
  15196. (match* (t1 t2)
  15197. [(`(All ,xs ,T1) `(All ,ys ,T2))
  15198. (define env (map cons xs ys))
  15199. (type-equal? (subst-type env T1) T2)]
  15200. [(other wise)
  15201. (super type-equal? t1 t2)]))
  15202. (define/public (match-types env pt at)
  15203. (match* (pt at)
  15204. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  15205. [('Void 'Void) env] [('Any 'Any) env]
  15206. [(`(Vector ,pts ...) `(Vector ,ats ...))
  15207. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  15208. (match-types env^ pt1 at1))]
  15209. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  15210. (define env^ (match-types env prt art))
  15211. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  15212. (match-types env^^ pt1 at1))]
  15213. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  15214. (define env^ (append (map cons pxs axs) env))
  15215. (match-types env^ pt1 at1)]
  15216. [((? symbol? x) at)
  15217. (match (dict-ref env x (lambda () #f))
  15218. [#f (error 'type-check "undefined type variable ~a" x)]
  15219. ['Type (cons (cons x at) env)]
  15220. [t^ (check-type-equal? at t^ 'matching) env])]
  15221. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  15222. (define/public (subst-type env pt)
  15223. (match pt
  15224. ['Integer 'Integer] ['Boolean 'Boolean]
  15225. ['Void 'Void] ['Any 'Any]
  15226. [`(Vector ,ts ...)
  15227. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  15228. [`(,ts ... -> ,rt)
  15229. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  15230. [`(All ,xs ,t)
  15231. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  15232. [(? symbol? x) (dict-ref env x)]
  15233. [else (error 'type-check "expected a type not ~a" pt)]))
  15234. (define/public (combine-decls-defs ds)
  15235. (match ds
  15236. ['() '()]
  15237. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  15238. (unless (equal? name f)
  15239. (error 'type-check "name mismatch, ~a != ~a" name f))
  15240. (match type
  15241. [`(All ,xs (,ps ... -> ,rt))
  15242. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  15243. (cons (Generic xs (Def name params^ rt info body))
  15244. (combine-decls-defs ds^))]
  15245. [`(,ps ... -> ,rt)
  15246. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  15247. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  15248. [else (error 'type-check "expected a function type, not ~a" type) ])]
  15249. [`(,(Def f params rt info body) . ,ds^)
  15250. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  15251. \end{lstlisting}
  15252. \caption{Auxiliary functions for type checking \LangPoly{}.}
  15253. \label{fig:type-check-Lvar0-aux}
  15254. \end{figure}
  15255. \begin{figure}[tbp]
  15256. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  15257. (define/public ((check-well-formed env) ty)
  15258. (match ty
  15259. ['Integer (void)]
  15260. ['Boolean (void)]
  15261. ['Void (void)]
  15262. [(? symbol? a)
  15263. (match (dict-ref env a (lambda () #f))
  15264. ['Type (void)]
  15265. [else (error 'type-check "undefined type variable ~a" a)])]
  15266. [`(Vector ,ts ...)
  15267. (for ([t ts]) ((check-well-formed env) t))]
  15268. [`(,ts ... -> ,t)
  15269. (for ([t ts]) ((check-well-formed env) t))
  15270. ((check-well-formed env) t)]
  15271. [`(All ,xs ,t)
  15272. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  15273. ((check-well-formed env^) t)]
  15274. [else (error 'type-check "unrecognized type ~a" ty)]))
  15275. \end{lstlisting}
  15276. \caption{Well-formed types.}
  15277. \label{fig:well-formed-types}
  15278. \end{figure}
  15279. % TODO: interpreter for R'_10
  15280. \section{Compiling Polymorphism}
  15281. \label{sec:compiling-poly}
  15282. Broadly speaking, there are four approaches to compiling parametric
  15283. polymorphism, which we describe below.
  15284. \begin{description}
  15285. \item[Monomorphization] generates a different version of a polymorphic
  15286. function for each set of type arguments that it is used with,
  15287. producing type-specialized code. This approach results in the most
  15288. efficient code but requires whole-program compilation (no separate
  15289. compilation) and increases code size. For our current purposes
  15290. monomorphization is a non-starter because, with first-class
  15291. polymorphism, it is sometimes not possible to determine which
  15292. generic functions are used with which type arguments during
  15293. compilation. (It can be done at runtime, with just-in-time
  15294. compilation.) This approach is used to compile C++
  15295. templates~\citep{stroustrup88:_param_types} and polymorphic
  15296. functions in NESL~\citep{Blelloch:1993aa} and
  15297. ML~\citep{Weeks:2006aa}.
  15298. \item[Uniform representation] generates one version of each
  15299. polymorphic function but requires all values have a common ``boxed''
  15300. format, such as the tagged values of type \code{Any} in
  15301. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  15302. similarly to code in a dynamically typed language (like \LangDyn{}),
  15303. in which primitive operators require their arguments to be projected
  15304. from \code{Any} and their results are injected into \code{Any}. (In
  15305. object-oriented languages, the projection is accomplished via
  15306. virtual method dispatch.) The uniform representation approach is
  15307. compatible with separate compilation and with first-class
  15308. polymorphism. However, it produces the least-efficient code because
  15309. it introduces overhead in the entire program, including
  15310. non-polymorphic code. This approach is used in implementations of
  15311. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  15312. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  15313. Java~\citep{Bracha:1998fk}.
  15314. \item[Mixed representation] generates one version of each polymorphic
  15315. function, using a boxed representation for type
  15316. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  15317. and conversions are performed at the boundaries between monomorphic
  15318. and polymorphic (e.g. when a polymorphic function is instantiated
  15319. and called). This approach is compatible with separate compilation
  15320. and first-class polymorphism and maintains the efficiency of
  15321. monomorphic code. The tradeoff is increased overhead at the boundary
  15322. between monomorphic and polymorphic code. This approach is used in
  15323. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  15324. Java 5 with the addition of autoboxing.
  15325. \item[Type passing] uses the unboxed representation in both
  15326. monomorphic and polymorphic code. Each polymorphic function is
  15327. compiled to a single function with extra parameters that describe
  15328. the type arguments. The type information is used by the generated
  15329. code to know how to access the unboxed values at runtime. This
  15330. approach is used in implementation of the Napier88
  15331. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  15332. passing is compatible with separate compilation and first-class
  15333. polymorphism and maintains the efficiency for monomorphic
  15334. code. There is runtime overhead in polymorphic code from dispatching
  15335. on type information.
  15336. \end{description}
  15337. In this chapter we use the mixed representation approach, partly
  15338. because of its favorable attributes, and partly because it is
  15339. straightforward to implement using the tools that we have already
  15340. built to support gradual typing. To compile polymorphic functions, we
  15341. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  15342. \LangCast{}.
  15343. \section{Erase Types}
  15344. \label{sec:erase-types}
  15345. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  15346. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  15347. shows the output of the \code{erase-types} pass on the polymorphic
  15348. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  15349. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  15350. \code{All} types are removed from the type of \code{map-vec}.
  15351. \begin{figure}[tbp]
  15352. \begin{lstlisting}
  15353. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  15354. : (Vector Any Any)
  15355. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15356. (define (add1 [x : Integer]) : Integer (+ x 1))
  15357. (vector-ref ((cast map-vec
  15358. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  15359. ((Integer -> Integer) (Vector Integer Integer)
  15360. -> (Vector Integer Integer)))
  15361. add1 (vector 0 41)) 1)
  15362. \end{lstlisting}
  15363. \caption{The polymorphic \code{map-vec} example after type erasure.}
  15364. \label{fig:map-vec-erase}
  15365. \end{figure}
  15366. This process of type erasure creates a challenge at points of
  15367. instantiation. For example, consider the instantiation of
  15368. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  15369. The type of \code{map-vec} is
  15370. \begin{lstlisting}
  15371. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15372. \end{lstlisting}
  15373. and it is instantiated to
  15374. \begin{lstlisting}
  15375. ((Integer -> Integer) (Vector Integer Integer)
  15376. -> (Vector Integer Integer))
  15377. \end{lstlisting}
  15378. After erasure, the type of \code{map-vec} is
  15379. \begin{lstlisting}
  15380. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  15381. \end{lstlisting}
  15382. but we need to convert it to the instantiated type. This is easy to
  15383. do in the target language \LangCast{} with a single \code{cast}. In
  15384. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  15385. has been compiled to a \code{cast} from the type of \code{map-vec} to
  15386. the instantiated type. The source and target type of a cast must be
  15387. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  15388. because both the source and target are obtained from the same
  15389. polymorphic type of \code{map-vec}, replacing the type parameters with
  15390. \code{Any} in the former and with the deduced type arguments in the
  15391. later. (Recall that the \code{Any} type is consistent with any type.)
  15392. To implement the \code{erase-types} pass, we recommend defining a
  15393. recursive auxiliary function named \code{erase-type} that applies the
  15394. following two transformations. It replaces type variables with
  15395. \code{Any}
  15396. \begin{lstlisting}
  15397. |$x$|
  15398. |$\Rightarrow$|
  15399. Any
  15400. \end{lstlisting}
  15401. and it removes the polymorphic \code{All} types.
  15402. \begin{lstlisting}
  15403. (All |$xs$| |$T_1$|)
  15404. |$\Rightarrow$|
  15405. |$T'_1$|
  15406. \end{lstlisting}
  15407. Apply the \code{erase-type} function to all of the type annotations in
  15408. the program.
  15409. Regarding the translation of expressions, the case for \code{Inst} is
  15410. the interesting one. We translate it into a \code{Cast}, as shown
  15411. below. The type of the subexpression $e$ is the polymorphic type
  15412. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  15413. $T$, the type $T'$. The target type $T''$ is the result of
  15414. substituting the arguments types $ts$ for the type parameters $xs$ in
  15415. $T$ followed by doing type erasure.
  15416. \begin{lstlisting}
  15417. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  15418. |$\Rightarrow$|
  15419. (Cast |$e'$| |$T'$| |$T''$|)
  15420. \end{lstlisting}
  15421. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  15422. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  15423. Finally, each polymorphic function is translated to a regular
  15424. functions in which type erasure has been applied to all the type
  15425. annotations and the body.
  15426. \begin{lstlisting}
  15427. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  15428. |$\Rightarrow$|
  15429. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  15430. \end{lstlisting}
  15431. \begin{exercise}\normalfont
  15432. Implement a compiler for the polymorphic language \LangPoly{} by
  15433. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  15434. programs that use polymorphic functions. Some of them should make
  15435. use of first-class polymorphism.
  15436. \end{exercise}
  15437. \begin{figure}[p]
  15438. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15439. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  15440. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  15441. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  15442. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  15443. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  15444. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  15445. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  15446. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  15447. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  15448. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  15449. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  15450. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  15451. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  15452. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  15453. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  15454. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15455. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15456. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15457. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15458. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15459. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15460. \path[->,bend right=15] (Rpoly) edge [above] node
  15461. {\ttfamily\footnotesize type\_check} (Rpolyp);
  15462. \path[->,bend right=15] (Rpolyp) edge [above] node
  15463. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  15464. \path[->,bend right=15] (Rgradualp) edge [above] node
  15465. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  15466. \path[->,bend right=15] (Rwhilepp) edge [right] node
  15467. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  15468. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  15469. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  15470. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  15471. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  15472. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  15473. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  15474. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  15475. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  15476. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  15477. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15478. \path[->,bend left=15] (F1-1) edge [below] node
  15479. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15480. \path[->,bend right=15] (F1-2) edge [above] node
  15481. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15482. \path[->,bend right=15] (F1-3) edge [above] node
  15483. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15484. \path[->,bend right=15] (F1-4) edge [above] node
  15485. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15486. \path[->,bend right=15] (F1-5) edge [right] node
  15487. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15488. \path[->,bend left=15] (C3-2) edge [left] node
  15489. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15490. \path[->,bend right=15] (x86-2) edge [left] node
  15491. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15492. \path[->,bend right=15] (x86-2-1) edge [below] node
  15493. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15494. \path[->,bend right=15] (x86-2-2) edge [left] node
  15495. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15496. \path[->,bend left=15] (x86-3) edge [above] node
  15497. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15498. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  15499. \end{tikzpicture}
  15500. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  15501. \label{fig:Rpoly-passes}
  15502. \end{figure}
  15503. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  15504. for the compilation of \LangPoly{}.
  15505. % TODO: challenge problem: specialization of instantiations
  15506. % Further Reading
  15507. \fi
  15508. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15509. \clearpage
  15510. \appendix
  15511. \chapter{Appendix}
  15512. \if\edition\racketEd
  15513. \section{Interpreters}
  15514. \label{appendix:interp}
  15515. \index{subject}{interpreter}
  15516. We provide interpreters for each of the source languages \LangInt{},
  15517. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  15518. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  15519. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  15520. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  15521. and x86 are in the \key{interp.rkt} file.
  15522. \section{Utility Functions}
  15523. \label{appendix:utilities}
  15524. The utility functions described in this section are in the
  15525. \key{utilities.rkt} file of the support code.
  15526. \paragraph{\code{interp-tests}}
  15527. The \key{interp-tests} function runs the compiler passes and the
  15528. interpreters on each of the specified tests to check whether each pass
  15529. is correct. The \key{interp-tests} function has the following
  15530. parameters:
  15531. \begin{description}
  15532. \item[name (a string)] a name to identify the compiler,
  15533. \item[typechecker] a function of exactly one argument that either
  15534. raises an error using the \code{error} function when it encounters a
  15535. type error, or returns \code{\#f} when it encounters a type
  15536. error. If there is no type error, the type checker returns the
  15537. program.
  15538. \item[passes] a list with one entry per pass. An entry is a list with
  15539. four things:
  15540. \begin{enumerate}
  15541. \item a string giving the name of the pass,
  15542. \item the function that implements the pass (a translator from AST
  15543. to AST),
  15544. \item a function that implements the interpreter (a function from
  15545. AST to result value) for the output language,
  15546. \item and a type checker for the output language. Type checkers for
  15547. the $R$ and $C$ languages are provided in the support code. For
  15548. example, the type checkers for \LangVar{} and \LangCVar{} are in
  15549. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  15550. type checker entry is optional. The support code does not provide
  15551. type checkers for the x86 languages.
  15552. \end{enumerate}
  15553. \item[source-interp] an interpreter for the source language. The
  15554. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  15555. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  15556. \item[tests] a list of test numbers that specifies which tests to
  15557. run. (see below)
  15558. \end{description}
  15559. %
  15560. The \key{interp-tests} function assumes that the subdirectory
  15561. \key{tests} has a collection of Racket programs whose names all start
  15562. with the family name, followed by an underscore and then the test
  15563. number, ending with the file extension \key{.rkt}. Also, for each test
  15564. program that calls \code{read} one or more times, there is a file with
  15565. the same name except that the file extension is \key{.in} that
  15566. provides the input for the Racket program. If the test program is
  15567. expected to fail type checking, then there should be an empty file of
  15568. the same name but with extension \key{.tyerr}.
  15569. \paragraph{\code{compiler-tests}}
  15570. runs the compiler passes to generate x86 (a \key{.s} file) and then
  15571. runs the GNU C compiler (gcc) to generate machine code. It runs the
  15572. machine code and checks that the output is $42$. The parameters to the
  15573. \code{compiler-tests} function are similar to those of the
  15574. \code{interp-tests} function, and consist of
  15575. \begin{itemize}
  15576. \item a compiler name (a string),
  15577. \item a type checker,
  15578. \item description of the passes,
  15579. \item name of a test-family, and
  15580. \item a list of test numbers.
  15581. \end{itemize}
  15582. \paragraph{\code{compile-file}}
  15583. takes a description of the compiler passes (see the comment for
  15584. \key{interp-tests}) and returns a function that, given a program file
  15585. name (a string ending in \key{.rkt}), applies all of the passes and
  15586. writes the output to a file whose name is the same as the program file
  15587. name but with \key{.rkt} replaced with \key{.s}.
  15588. \paragraph{\code{read-program}}
  15589. takes a file path and parses that file (it must be a Racket program)
  15590. into an abstract syntax tree.
  15591. \paragraph{\code{parse-program}}
  15592. takes an S-expression representation of an abstract syntax tree and converts it into
  15593. the struct-based representation.
  15594. \paragraph{\code{assert}}
  15595. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  15596. and displays the message \key{msg} if the Boolean \key{bool} is false.
  15597. \paragraph{\code{lookup}}
  15598. % remove discussion of lookup? -Jeremy
  15599. takes a key and an alist, and returns the first value that is
  15600. associated with the given key, if there is one. If not, an error is
  15601. triggered. The alist may contain both immutable pairs (built with
  15602. \key{cons}) and mutable pairs (built with \key{mcons}).
  15603. %The \key{map2} function ...
  15604. \fi %\racketEd
  15605. \section{x86 Instruction Set Quick-Reference}
  15606. \label{sec:x86-quick-reference}
  15607. \index{subject}{x86}
  15608. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  15609. do. We write $A \to B$ to mean that the value of $A$ is written into
  15610. location $B$. Address offsets are given in bytes. The instruction
  15611. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  15612. registers (such as \code{\%rax}), or memory references (such as
  15613. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  15614. reference per instruction. Other operands must be immediates or
  15615. registers.
  15616. \begin{table}[tbp]
  15617. \centering
  15618. \begin{tabular}{l|l}
  15619. \textbf{Instruction} & \textbf{Operation} \\ \hline
  15620. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  15621. \texttt{negq} $A$ & $- A \to A$ \\
  15622. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  15623. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  15624. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  15625. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  15626. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  15627. \texttt{retq} & Pops the return address and jumps to it \\
  15628. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  15629. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  15630. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  15631. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  15632. be an immediate) \\
  15633. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  15634. matches the condition code of the instruction, otherwise go to the
  15635. next instructions. The condition codes are \key{e} for ``equal'',
  15636. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  15637. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  15638. \texttt{jl} $L$ & \\
  15639. \texttt{jle} $L$ & \\
  15640. \texttt{jg} $L$ & \\
  15641. \texttt{jge} $L$ & \\
  15642. \texttt{jmp} $L$ & Jump to label $L$ \\
  15643. \texttt{movq} $A$, $B$ & $A \to B$ \\
  15644. \texttt{movzbq} $A$, $B$ &
  15645. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  15646. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  15647. and the extra bytes of $B$ are set to zero.} \\
  15648. & \\
  15649. & \\
  15650. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  15651. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  15652. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  15653. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  15654. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  15655. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  15656. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  15657. description of the condition codes. $A$ must be a single byte register
  15658. (e.g., \texttt{al} or \texttt{cl}).} \\
  15659. \texttt{setl} $A$ & \\
  15660. \texttt{setle} $A$ & \\
  15661. \texttt{setg} $A$ & \\
  15662. \texttt{setge} $A$ &
  15663. \end{tabular}
  15664. \vspace{5pt}
  15665. \caption{Quick-reference for the x86 instructions used in this book.}
  15666. \label{tab:x86-instr}
  15667. \end{table}
  15668. \if\edition\racketEd
  15669. \cleardoublepage
  15670. \section{Concrete Syntax for Intermediate Languages}
  15671. The concrete syntax of \LangAny{} is defined in
  15672. Figure~\ref{fig:Rany-concrete-syntax}.
  15673. \begin{figure}[tp]
  15674. \centering
  15675. \fbox{
  15676. \begin{minipage}{0.97\textwidth}\small
  15677. \[
  15678. \begin{array}{lcl}
  15679. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  15680. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  15681. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  15682. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15683. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15684. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15685. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  15686. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  15687. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  15688. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  15689. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  15690. \MID \LP\key{void?}\;\Exp\RP \\
  15691. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  15692. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  15693. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  15694. \end{array}
  15695. \]
  15696. \end{minipage}
  15697. }
  15698. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  15699. (Figure~\ref{fig:Rlam-syntax}).}
  15700. \label{fig:Rany-concrete-syntax}
  15701. \end{figure}
  15702. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  15703. defined in Figures~\ref{fig:c0-concrete-syntax},
  15704. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  15705. and \ref{fig:c3-concrete-syntax}, respectively.
  15706. \begin{figure}[tbp]
  15707. \fbox{
  15708. \begin{minipage}{0.96\textwidth}
  15709. \small
  15710. \[
  15711. \begin{array}{lcl}
  15712. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  15713. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  15714. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  15715. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  15716. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  15717. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  15718. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  15719. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  15720. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  15721. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  15722. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  15723. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  15724. \end{array}
  15725. \]
  15726. \end{minipage}
  15727. }
  15728. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  15729. \label{fig:c2-concrete-syntax}
  15730. \end{figure}
  15731. \begin{figure}[tp]
  15732. \fbox{
  15733. \begin{minipage}{0.96\textwidth}
  15734. \small
  15735. \[
  15736. \begin{array}{lcl}
  15737. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  15738. \\
  15739. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  15740. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  15741. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  15742. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  15743. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  15744. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  15745. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  15746. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  15747. \MID \LP\key{collect} \,\itm{int}\RP }\\
  15748. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  15749. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  15750. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  15751. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  15752. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  15753. \LangCFunM{} & ::= & \Def\ldots
  15754. \end{array}
  15755. \]
  15756. \end{minipage}
  15757. }
  15758. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  15759. \label{fig:c3-concrete-syntax}
  15760. \end{figure}
  15761. \fi % racketEd
  15762. \backmatter
  15763. \addtocontents{toc}{\vspace{11pt}}
  15764. %% \addtocontents{toc}{\vspace{11pt}}
  15765. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  15766. \nocite{*}\let\bibname\refname
  15767. \addcontentsline{toc}{fmbm}{\refname}
  15768. \printbibliography
  15769. \printindex{authors}{Author Index}
  15770. \printindex{subject}{Subject Index}
  15771. \end{document}
  15772. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  15773. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  15774. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  15775. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  15776. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  15777. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  15778. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  15779. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  15780. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  15781. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  15782. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  15783. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  15784. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  15785. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  15786. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  15787. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  15788. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  15789. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  15790. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  15791. % LocalWords: morekeywords fullflexible